diff --git a/.dotnet/example_code/DynamoDB/CreateTablesLoadData.cs b/.dotnet/example_code/DynamoDB/CreateTablesLoadData.cs index 434a7143248..95b3613baa8 100644 --- a/.dotnet/example_code/DynamoDB/CreateTablesLoadData.cs +++ b/.dotnet/example_code/DynamoDB/CreateTablesLoadData.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.CreateTablesLoadData] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.CreateTablesLoadData] using System; using System.Collections.Generic; using Amazon.DynamoDBv2; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/00_Main.cs b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/00_Main.cs index cea2c2dea35..29bdc3f4bc1 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/00_Main.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/00_Main.cs @@ -1,14 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[dynamodb.dotNET.CodeExample.00_Main] using System; using System.Collections.Generic; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/00a_Constants.cs b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/00a_Constants.cs index b2251fc3e03..43a12b8480b 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/00a_Constants.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/00a_Constants.cs @@ -1,14 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[dynamodb.dotNET.CodeExample.00a_Constants] using System.Collections.Generic; using Amazon.DynamoDBv2.Model; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/00b_DDB_Attributes.cs b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/00b_DDB_Attributes.cs index c4d19a9fe23..5659b8f1512 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/00b_DDB_Attributes.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/00b_DDB_Attributes.cs @@ -1,14 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[dynamodb.dotNET.CodeExample.00b_DDB_Attributes] using System; using System.Text; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/01_CreateClient.cs b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/01_CreateClient.cs index 47d38b37f12..ffb02e5dc9e 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/01_CreateClient.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/01_CreateClient.cs @@ -1,14 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[dynamodb.dotNET.CodeExample.01_CreateClient] using System; using System.Net; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/02_CreatingTable.cs b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/02_CreatingTable.cs index 2e164929f40..bacc2d83a7e 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/02_CreatingTable.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/02_CreatingTable.cs @@ -1,14 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[dynamodb.dotNET.CodeExample.02_CreatingTable] using System; using System.Collections.Generic; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/03_LoadingData.cs b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/03_LoadingData.cs index 3321235ce53..7b38e9dea07 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/03_LoadingData.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/03_LoadingData.cs @@ -1,14 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[dynamodb.dotNET.CodeExample.03_LoadingData] using System; using System.IO; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/04_WritingNewItem.cs b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/04_WritingNewItem.cs index 71df158f629..a961aa8d8c6 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/04_WritingNewItem.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/04_WritingNewItem.cs @@ -1,14 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[dynamodb.dotNET.CodeExample.04_WritingNewItem] using System; using System.Threading.Tasks; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/05_ReadingItem.cs b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/05_ReadingItem.cs index 707dcb132eb..d58d240a9d6 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/05_ReadingItem.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/05_ReadingItem.cs @@ -1,14 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[dynamodb.dotNET.CodeExample.05_ReadingItem] using System; using System.Threading.Tasks; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/06_UpdatingItem.cs b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/06_UpdatingItem.cs index 5a266f51357..8e57c456781 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/06_UpdatingItem.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/06_UpdatingItem.cs @@ -1,14 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[dynamodb.dotNET.CodeExample.06_UpdatingItem] using System; using System.Threading.Tasks; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/07_DeletingItem.cs b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/07_DeletingItem.cs index 6a0e49d0761..869229f0a94 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/07_DeletingItem.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/07_DeletingItem.cs @@ -1,14 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[dynamodb.dotNET.CodeExample.07_DeletingItem] using System; using System.Threading.Tasks; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/08_Querying.cs b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/08_Querying.cs index 31277b36e6f..88f151505f3 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/08_Querying.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/08_Querying.cs @@ -1,14 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[dynamodb.dotNET.CodeExample.08_Querying] using System; using System.Threading.Tasks; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/09_Scanning.cs b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/09_Scanning.cs index 08e45cb670b..3e3d964c29a 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/09_Scanning.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/09_Scanning.cs @@ -1,14 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[dynamodb.dotNET.CodeExample.09_Scanning] using System; using System.Collections.Generic; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/10_DeletingTable.cs b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/10_DeletingTable.cs index 5ef07ccc0fa..ce10d9ab9bf 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/10_DeletingTable.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/DynamoDB_intro/DynamoDB_intro/10_DeletingTable.cs @@ -1,14 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[dynamodb.dotNET.CodeExample.10_DeletingTable] using System; using System.Threading.Tasks; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/old/DeleteItem/Program.cs b/.dotnet/example_code/DynamoDB/GettingStarted/old/DeleteItem/Program.cs index ccd5a40a115..7f43dda06fb 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/old/DeleteItem/Program.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/old/DeleteItem/Program.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.DeleteItem] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.DeleteItem] using System; using System.Collections.Generic; using System.Linq; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/old/DeleteTable/Program.cs b/.dotnet/example_code/DynamoDB/GettingStarted/old/DeleteTable/Program.cs index ba0033b7331..af2caac104c 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/old/DeleteTable/Program.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/old/DeleteTable/Program.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.DeleteTable] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.DeleteTable] using System; using System.Text; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/old/LoadJsonMovieData/Program.cs b/.dotnet/example_code/DynamoDB/GettingStarted/old/LoadJsonMovieData/Program.cs index 35544efc791..6ef80c1aa9d 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/old/LoadJsonMovieData/Program.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/old/LoadJsonMovieData/Program.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.LoadJsonMovieData] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.LoadJsonMovieData] using System; using System.Collections.Generic; using System.IO; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/old/MoviesCreateTable/Program.cs b/.dotnet/example_code/DynamoDB/GettingStarted/old/MoviesCreateTable/Program.cs index 94a2d7e023c..65856c8faf6 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/old/MoviesCreateTable/Program.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/old/MoviesCreateTable/Program.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.MoviesCreateTable] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.MoviesCreateTable] using System; using System.Collections.Generic; using System.IO; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/old/PutItem_A/Program.cs b/.dotnet/example_code/DynamoDB/GettingStarted/old/PutItem_A/Program.cs index 30a301413de..b0b63ae904d 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/old/PutItem_A/Program.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/old/PutItem_A/Program.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.PutItem_A] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.PutItem_A] using System; using System.Collections.Generic; using System.Linq; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/old/PutItem_B/Program.cs b/.dotnet/example_code/DynamoDB/GettingStarted/old/PutItem_B/Program.cs index 4cb717a321c..8b0e2314e12 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/old/PutItem_B/Program.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/old/PutItem_B/Program.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.PutItem_B] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.PutItem_B] using System; using System.Collections.Generic; using System.Linq; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/old/Query/Program.cs b/.dotnet/example_code/DynamoDB/GettingStarted/old/Query/Program.cs index 11112c646c9..e1381b8f4e9 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/old/Query/Program.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/old/Query/Program.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.Query] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.Query] using System; using System.Collections.Generic; using System.Linq; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/old/Scan/Program.cs b/.dotnet/example_code/DynamoDB/GettingStarted/old/Scan/Program.cs index ad6047b416f..798a37e2951 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/old/Scan/Program.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/old/Scan/Program.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.Scan] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.Scan] using System; using System.Collections.Generic; using System.Linq; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/old/UpdateItem_A/Program.cs b/.dotnet/example_code/DynamoDB/GettingStarted/old/UpdateItem_A/Program.cs index 1fe0a68a902..01a04c35d3e 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/old/UpdateItem_A/Program.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/old/UpdateItem_A/Program.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.UpdateItem_A] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.UpdateItem_A] using System; using System.Collections.Generic; using System.Linq; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/old/UpdateItem_B/Program.cs b/.dotnet/example_code/DynamoDB/GettingStarted/old/UpdateItem_B/Program.cs index ee82c4038ea..f6d7c7602c4 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/old/UpdateItem_B/Program.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/old/UpdateItem_B/Program.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.UpdateItem_B] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.UpdateItem_B] using System; using System.Collections.Generic; using System.Linq; diff --git a/.dotnet/example_code/DynamoDB/GettingStarted/old/UpdateItem_C/Program.cs b/.dotnet/example_code/DynamoDB/GettingStarted/old/UpdateItem_C/Program.cs index f97adafcbc7..bee5418746a 100644 --- a/.dotnet/example_code/DynamoDB/GettingStarted/old/UpdateItem_C/Program.cs +++ b/.dotnet/example_code/DynamoDB/GettingStarted/old/UpdateItem_C/Program.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.UpdateItem_C] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.UpdateItem_C] using System; using System.Collections.Generic; using System.Linq; diff --git a/.dotnet/example_code/DynamoDB/HighLevelBatchWriteItem.cs b/.dotnet/example_code/DynamoDB/HighLevelBatchWriteItem.cs index bec55b2db69..5cc533f0bc7 100644 --- a/.dotnet/example_code/DynamoDB/HighLevelBatchWriteItem.cs +++ b/.dotnet/example_code/DynamoDB/HighLevelBatchWriteItem.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.HighLevelBatchWriteItem] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.HighLevelBatchWriteItem] using System; using System.Collections.Generic; using Amazon.DynamoDBv2; diff --git a/.dotnet/example_code/DynamoDB/HighLevelItemCRUD.cs b/.dotnet/example_code/DynamoDB/HighLevelItemCRUD.cs index b218e9e5d66..98266c74971 100644 --- a/.dotnet/example_code/DynamoDB/HighLevelItemCRUD.cs +++ b/.dotnet/example_code/DynamoDB/HighLevelItemCRUD.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.HighLevelItemCRUD] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.HighLevelItemCRUD] using System; using System.Collections.Generic; using Amazon.DynamoDBv2; diff --git a/.dotnet/example_code/DynamoDB/HighLevelMappingArbitraryData.cs b/.dotnet/example_code/DynamoDB/HighLevelMappingArbitraryData.cs index 45ab518b575..099bfb56c4b 100644 --- a/.dotnet/example_code/DynamoDB/HighLevelMappingArbitraryData.cs +++ b/.dotnet/example_code/DynamoDB/HighLevelMappingArbitraryData.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.HighLevelMappingArbitraryData] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.HighLevelMappingArbitraryData] using System; using System.Collections.Generic; using Amazon.DynamoDBv2; diff --git a/.dotnet/example_code/DynamoDB/HighLevelQueryAndScan.cs b/.dotnet/example_code/DynamoDB/HighLevelQueryAndScan.cs index 5fd3a89a992..639c2ecc9bc 100644 --- a/.dotnet/example_code/DynamoDB/HighLevelQueryAndScan.cs +++ b/.dotnet/example_code/DynamoDB/HighLevelQueryAndScan.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.HighLevelQueryAndScan] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.HighLevelQueryAndScan] using System; using System.Collections.Generic; using System.Configuration; diff --git a/.dotnet/example_code/DynamoDB/LowLevelBatchGet.cs b/.dotnet/example_code/DynamoDB/LowLevelBatchGet.cs index 3409ff3647e..29942f71c44 100644 --- a/.dotnet/example_code/DynamoDB/LowLevelBatchGet.cs +++ b/.dotnet/example_code/DynamoDB/LowLevelBatchGet.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelBatchGet] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelBatchGet] using System; using System.Collections.Generic; using Amazon.DynamoDBv2; diff --git a/.dotnet/example_code/DynamoDB/LowLevelBatchWrite.cs b/.dotnet/example_code/DynamoDB/LowLevelBatchWrite.cs index 3b38e04f2d2..5dcfcbc63f2 100644 --- a/.dotnet/example_code/DynamoDB/LowLevelBatchWrite.cs +++ b/.dotnet/example_code/DynamoDB/LowLevelBatchWrite.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelBatchWrite] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelBatchWrite] using System; using System.Collections.Generic; using Amazon.DynamoDBv2; diff --git a/.dotnet/example_code/DynamoDB/LowLevelGlobalSecondaryIndexExample.cs b/.dotnet/example_code/DynamoDB/LowLevelGlobalSecondaryIndexExample.cs index c3f9044fa66..b5635b47e7a 100644 --- a/.dotnet/example_code/DynamoDB/LowLevelGlobalSecondaryIndexExample.cs +++ b/.dotnet/example_code/DynamoDB/LowLevelGlobalSecondaryIndexExample.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelGlobalSecondaryIndexExample] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelGlobalSecondaryIndexExample] using System; using System.Collections.Generic; using System.Linq; diff --git a/.dotnet/example_code/DynamoDB/LowLevelItemBinaryExample.cs b/.dotnet/example_code/DynamoDB/LowLevelItemBinaryExample.cs index d2340929375..98513cf13a0 100644 --- a/.dotnet/example_code/DynamoDB/LowLevelItemBinaryExample.cs +++ b/.dotnet/example_code/DynamoDB/LowLevelItemBinaryExample.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelItemBinaryExample] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelItemBinaryExample] using System; using System.Collections.Generic; using System.IO; diff --git a/.dotnet/example_code/DynamoDB/LowLevelItemCRUDExample.cs b/.dotnet/example_code/DynamoDB/LowLevelItemCRUDExample.cs index 694652ac7ad..f53dcc2147f 100644 --- a/.dotnet/example_code/DynamoDB/LowLevelItemCRUDExample.cs +++ b/.dotnet/example_code/DynamoDB/LowLevelItemCRUDExample.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelItemCRUDExample] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelItemCRUDExample] using System; using System.Collections.Generic; using Amazon.DynamoDBv2; diff --git a/.dotnet/example_code/DynamoDB/LowLevelLocalSecondaryIndexExample.cs b/.dotnet/example_code/DynamoDB/LowLevelLocalSecondaryIndexExample.cs index 5028a6b0d23..fbf741a43a2 100644 --- a/.dotnet/example_code/DynamoDB/LowLevelLocalSecondaryIndexExample.cs +++ b/.dotnet/example_code/DynamoDB/LowLevelLocalSecondaryIndexExample.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelLocalSecondaryIndexExample] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelLocalSecondaryIndexExample] using System; using System.Collections.Generic; using System.Linq; diff --git a/.dotnet/example_code/DynamoDB/LowLevelParallelScan.cs b/.dotnet/example_code/DynamoDB/LowLevelParallelScan.cs index 666587c0aba..26f81caec9d 100644 --- a/.dotnet/example_code/DynamoDB/LowLevelParallelScan.cs +++ b/.dotnet/example_code/DynamoDB/LowLevelParallelScan.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelParallelScan] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelParallelScan] using System; using System.Collections.Generic; using System.Threading; diff --git a/.dotnet/example_code/DynamoDB/LowLevelQuery.cs b/.dotnet/example_code/DynamoDB/LowLevelQuery.cs index 0336f6cb68b..e55dea545f9 100644 --- a/.dotnet/example_code/DynamoDB/LowLevelQuery.cs +++ b/.dotnet/example_code/DynamoDB/LowLevelQuery.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelQuery] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelQuery] using System; using System.Collections.Generic; using Amazon.DynamoDBv2; diff --git a/.dotnet/example_code/DynamoDB/LowLevelScan.cs b/.dotnet/example_code/DynamoDB/LowLevelScan.cs index 12e7ea53707..a87c624f7df 100644 --- a/.dotnet/example_code/DynamoDB/LowLevelScan.cs +++ b/.dotnet/example_code/DynamoDB/LowLevelScan.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelScan] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelScan] using System; using System.Collections.Generic; using Amazon.DynamoDBv2; diff --git a/.dotnet/example_code/DynamoDB/LowLevelTableExample.cs b/.dotnet/example_code/DynamoDB/LowLevelTableExample.cs index 08a90b2b600..8863fdb928e 100644 --- a/.dotnet/example_code/DynamoDB/LowLevelTableExample.cs +++ b/.dotnet/example_code/DynamoDB/LowLevelTableExample.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelTableExample] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.LowLevelTableExample] using System; using System.Collections.Generic; using Amazon.DynamoDBv2; diff --git a/.dotnet/example_code/DynamoDB/MidLevelBatchWriteItem.cs b/.dotnet/example_code/DynamoDB/MidLevelBatchWriteItem.cs index 2198d059040..7285fd8ace5 100644 --- a/.dotnet/example_code/DynamoDB/MidLevelBatchWriteItem.cs +++ b/.dotnet/example_code/DynamoDB/MidLevelBatchWriteItem.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.MidLevelBatchWriteItem] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.MidLevelBatchWriteItem] using System; using System.Collections.Generic; using Amazon.DynamoDBv2; diff --git a/.dotnet/example_code/DynamoDB/MidLevelQueryAndScan.cs b/.dotnet/example_code/DynamoDB/MidLevelQueryAndScan.cs index 6e3e4d3883e..c743e5d48bf 100644 --- a/.dotnet/example_code/DynamoDB/MidLevelQueryAndScan.cs +++ b/.dotnet/example_code/DynamoDB/MidLevelQueryAndScan.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.MidLevelQueryAndScan] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.MidLevelQueryAndScan] using System; using System.Collections.Generic; using System.Linq; diff --git a/.dotnet/example_code/DynamoDB/MidLevelScanOnly.cs b/.dotnet/example_code/DynamoDB/MidLevelScanOnly.cs index 5c28270f838..12b46ebbdab 100644 --- a/.dotnet/example_code/DynamoDB/MidLevelScanOnly.cs +++ b/.dotnet/example_code/DynamoDB/MidLevelScanOnly.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.MidLevelScanOnly] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.MidLevelScanOnly] using System; using System.Collections.Generic; using System.Linq; diff --git a/.dotnet/example_code/DynamoDB/MidlevelItemCRUD.cs b/.dotnet/example_code/DynamoDB/MidlevelItemCRUD.cs index 548445a491b..036ea6d0cee 100644 --- a/.dotnet/example_code/DynamoDB/MidlevelItemCRUD.cs +++ b/.dotnet/example_code/DynamoDB/MidlevelItemCRUD.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.MidlevelItemCRUD] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.MidlevelItemCRUD] using System; using System.Collections.Generic; using System.Linq; diff --git a/.dotnet/example_code/DynamoDB/SampleDataLoad.cs b/.dotnet/example_code/DynamoDB/SampleDataLoad.cs index adfe8462a13..e40e33a9cbf 100644 --- a/.dotnet/example_code/DynamoDB/SampleDataLoad.cs +++ b/.dotnet/example_code/DynamoDB/SampleDataLoad.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.SampleDataLoad] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.SampleDataLoad] using System; using System.Collections.Generic; using Amazon.DynamoDBv2; diff --git a/.dotnet/example_code/DynamoDB/SampleDataTryQuery.cs b/.dotnet/example_code/DynamoDB/SampleDataTryQuery.cs index 92ecb4866c5..c9746421f72 100644 --- a/.dotnet/example_code/DynamoDB/SampleDataTryQuery.cs +++ b/.dotnet/example_code/DynamoDB/SampleDataTryQuery.cs @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.dotNET.CodeExample.SampleDataTryQuery] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.dotNET.CodeExample.SampleDataTryQuery] using System; using System.Collections.Generic; using Amazon.DynamoDBv2; diff --git a/.dotnet/example_code/DynamoDB/TryDax/01-CreateTable.cs b/.dotnet/example_code/DynamoDB/TryDax/01-CreateTable.cs index 1b493c0695a..76265e1f8b2 100644 --- a/.dotnet/example_code/DynamoDB/TryDax/01-CreateTable.cs +++ b/.dotnet/example_code/DynamoDB/TryDax/01-CreateTable.cs @@ -1,8 +1,8 @@ -// snippet-start:[dynamodb.dotNET.trydax.01-CreateTable] - // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.dotNET.trydax.01-CreateTable] + using System; using System.Collections.Generic; using System.Threading.Tasks; diff --git a/.dotnet/example_code/DynamoDB/TryDax/02-Write-Data.cs b/.dotnet/example_code/DynamoDB/TryDax/02-Write-Data.cs index dc7f5514797..cdac582e526 100644 --- a/.dotnet/example_code/DynamoDB/TryDax/02-Write-Data.cs +++ b/.dotnet/example_code/DynamoDB/TryDax/02-Write-Data.cs @@ -1,8 +1,8 @@ -// snippet-start:[dynamodb.dotNET.trydax.02-Write-Data] - // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.dotNET.trydax.02-Write-Data] + using System; using System.Collections.Generic; using System.Threading.Tasks; diff --git a/.dotnet/example_code/DynamoDB/TryDax/03-GetItem-Test.cs b/.dotnet/example_code/DynamoDB/TryDax/03-GetItem-Test.cs index 05d1aec7552..aafd26f7e34 100644 --- a/.dotnet/example_code/DynamoDB/TryDax/03-GetItem-Test.cs +++ b/.dotnet/example_code/DynamoDB/TryDax/03-GetItem-Test.cs @@ -1,8 +1,8 @@ -// snippet-start:[dynamodb.dotNET.trydax.03-GetItem-Test] - // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.dotNET.trydax.03-GetItem-Test] + using System; using System.Collections.Generic; using System.Threading.Tasks; diff --git a/.dotnet/example_code/DynamoDB/TryDax/04-Query-Test.cs b/.dotnet/example_code/DynamoDB/TryDax/04-Query-Test.cs index de5a7cc89dc..87e118d4d03 100644 --- a/.dotnet/example_code/DynamoDB/TryDax/04-Query-Test.cs +++ b/.dotnet/example_code/DynamoDB/TryDax/04-Query-Test.cs @@ -1,8 +1,8 @@ -// snippet-start:[dynamodb.dotNET.trydax.04-Query-Test] - // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.dotNET.trydax.04-Query-Test] + using System; using System.Collections.Generic; using System.Threading.Tasks; diff --git a/.dotnet/example_code/DynamoDB/TryDax/05-Scan-Test.cs b/.dotnet/example_code/DynamoDB/TryDax/05-Scan-Test.cs index 08120805710..1c8d2391f52 100644 --- a/.dotnet/example_code/DynamoDB/TryDax/05-Scan-Test.cs +++ b/.dotnet/example_code/DynamoDB/TryDax/05-Scan-Test.cs @@ -1,8 +1,8 @@ -// snippet-start:[dynamodb.dotNET.trydax.05-Scan-Test] - // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.dotNET.trydax.05-Scan-Test] + using System; using System.Threading.Tasks; using Amazon.Runtime; diff --git a/.dotnet/example_code/DynamoDB/TryDax/06-DeleteTable.cs b/.dotnet/example_code/DynamoDB/TryDax/06-DeleteTable.cs index 2a89c918ec6..4c7e4a20c4f 100644 --- a/.dotnet/example_code/DynamoDB/TryDax/06-DeleteTable.cs +++ b/.dotnet/example_code/DynamoDB/TryDax/06-DeleteTable.cs @@ -1,8 +1,8 @@ -// snippet-start:[dynamodb.dotNET.trydax.06-DeleteTable] - // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.dotNET.trydax.06-DeleteTable] + using System; using System.Threading.Tasks; using Amazon.DynamoDBv2.Model; diff --git a/.dotnet/example_code_legacy/Athena/AthenaSample2-SimpleQuery/athena_dotnet_example.cs b/.dotnet/example_code_legacy/Athena/AthenaSample2-SimpleQuery/athena_dotnet_example.cs index 059864bf9b4..755dfab0cd7 100644 --- a/.dotnet/example_code_legacy/Athena/AthenaSample2-SimpleQuery/athena_dotnet_example.cs +++ b/.dotnet/example_code_legacy/Athena/AthenaSample2-SimpleQuery/athena_dotnet_example.cs @@ -1,27 +1,8 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[athena_dotnet_example.cs demonstrates how to query for information from Amazon Athena.] -// snippet-service:[athena] -// snippet-keyword:[csharp] -// snippet-keyword:[Athena] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[] -// snippet-sourceauthor:[AWS] +/* + */ // For more information about Amazon Athena, see the user guide and API reference at: // https://docs.aws.amazon.com/athena diff --git a/.dotnet/example_code_legacy/Athena/AthenaSamples1/AthenaClient.cs b/.dotnet/example_code_legacy/Athena/AthenaSamples1/AthenaClient.cs index 8f1297b8c7e..117260db94a 100644 --- a/.dotnet/example_code_legacy/Athena/AthenaSamples1/AthenaClient.cs +++ b/.dotnet/example_code_legacy/Athena/AthenaSamples1/AthenaClient.cs @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[AthenaClient.cs demonstrates how to create and configure an Amazon Athena client.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Athena] -//snippet-service:[athena] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using Amazon; using Amazon.Athena; diff --git a/.dotnet/example_code_legacy/Athena/AthenaSamples1/CreateNamedQueryExample.cs b/.dotnet/example_code_legacy/Athena/AthenaSamples1/CreateNamedQueryExample.cs index cb93ee83a24..dbcb4063dea 100644 --- a/.dotnet/example_code_legacy/Athena/AthenaSamples1/CreateNamedQueryExample.cs +++ b/.dotnet/example_code_legacy/Athena/AthenaSamples1/CreateNamedQueryExample.cs @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[CreateNamedQueryExample.cs demonstrates how to create a named query.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Athena] -//snippet-service:[athena] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using Amazon; using Amazon.Athena.Model; diff --git a/.dotnet/example_code_legacy/Athena/AthenaSamples1/DeleteNamedQueryExample.cs b/.dotnet/example_code_legacy/Athena/AthenaSamples1/DeleteNamedQueryExample.cs index 54b02211b31..83592c2bef9 100644 --- a/.dotnet/example_code_legacy/Athena/AthenaSamples1/DeleteNamedQueryExample.cs +++ b/.dotnet/example_code_legacy/Athena/AthenaSamples1/DeleteNamedQueryExample.cs @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[DeleteNamedQueryExample.cs demonstrates how to delete a named query by using the named query ID.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Athena] -//snippet-service:[athena] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Threading; diff --git a/.dotnet/example_code_legacy/Athena/AthenaSamples1/ExampleConstants.cs b/.dotnet/example_code_legacy/Athena/AthenaSamples1/ExampleConstants.cs index 55ac3a50880..8ef2c7ce5fa 100644 --- a/.dotnet/example_code_legacy/Athena/AthenaSamples1/ExampleConstants.cs +++ b/.dotnet/example_code_legacy/Athena/AthenaSamples1/ExampleConstants.cs @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[ExampleConstants.cs contains definitions for constants used in Athena examples.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Athena] -//snippet-service:[athena] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; namespace AthenaSamples1 diff --git a/.dotnet/example_code_legacy/Athena/AthenaSamples1/ListNamedQueryExample.cs b/.dotnet/example_code_legacy/Athena/AthenaSamples1/ListNamedQueryExample.cs index f53b7dcccb4..ac580e73d8d 100644 --- a/.dotnet/example_code_legacy/Athena/AthenaSamples1/ListNamedQueryExample.cs +++ b/.dotnet/example_code_legacy/Athena/AthenaSamples1/ListNamedQueryExample.cs @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[ListNamedQueryExample.cs demonstrates how to obtain a list of named query IDs.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Athena] -//snippet-service:[athena] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using Amazon; using Amazon.Athena; diff --git a/.dotnet/example_code_legacy/Athena/AthenaSamples1/ListQueryExecutionsExample.cs b/.dotnet/example_code_legacy/Athena/AthenaSamples1/ListQueryExecutionsExample.cs index f3d211b416d..00e27e7964e 100644 --- a/.dotnet/example_code_legacy/Athena/AthenaSamples1/ListQueryExecutionsExample.cs +++ b/.dotnet/example_code_legacy/Athena/AthenaSamples1/ListQueryExecutionsExample.cs @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[ListQueryExecutionsExample.cs demonstrates how to obtain a list of query execution IDs.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Athena] -//snippet-service:[athena] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using Amazon; using Amazon.Athena; diff --git a/.dotnet/example_code_legacy/Athena/AthenaSamples1/Program.cs b/.dotnet/example_code_legacy/Athena/AthenaSamples1/Program.cs index 298170874b0..a66b0244f00 100644 --- a/.dotnet/example_code_legacy/Athena/AthenaSamples1/Program.cs +++ b/.dotnet/example_code_legacy/Athena/AthenaSamples1/Program.cs @@ -1,16 +1,8 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -//snippet-sourcedescription:[Program.cs can be used to execute the other Athena examples in this solution.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-service:[athena] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] - -using System; +using System; namespace AthenaSamples1 { diff --git a/.dotnet/example_code_legacy/Athena/AthenaSamples1/StartQueryExample.cs b/.dotnet/example_code_legacy/Athena/AthenaSamples1/StartQueryExample.cs index 23e34537347..9c1b795115f 100644 --- a/.dotnet/example_code_legacy/Athena/AthenaSamples1/StartQueryExample.cs +++ b/.dotnet/example_code_legacy/Athena/AthenaSamples1/StartQueryExample.cs @@ -1,17 +1,8 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -//snippet-sourcedescription:[StartQueryExample.cs demonstrates how to submit a query to Athena for execution, wait until results are available and then process the results.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Athena] -//snippet-service:[athena] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] - -using System; +using System; using System.Collections.Generic; using System.Threading; using Amazon; diff --git a/.dotnet/example_code_legacy/Athena/AthenaSamples1/StopQueryExecutionExample.cs b/.dotnet/example_code_legacy/Athena/AthenaSamples1/StopQueryExecutionExample.cs index 9c9e84d4543..66460cd87ca 100644 --- a/.dotnet/example_code_legacy/Athena/AthenaSamples1/StopQueryExecutionExample.cs +++ b/.dotnet/example_code_legacy/Athena/AthenaSamples1/StopQueryExecutionExample.cs @@ -1,17 +1,8 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -//snippet-sourcedescription:[StopQueryExecutionExample.cs demonstrates how to run an example query, immediately stop the query, and check the status of the query to ensure that it was cancelled.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Athena] -//snippet-service:[athena] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] - -using System; +using System; using Amazon; using Amazon.Athena; using Amazon.Athena.Model; diff --git a/.dotnet/example_code_legacy/CloudWatch/AwsCloudWatchSample1/Program.cs b/.dotnet/example_code_legacy/CloudWatch/AwsCloudWatchSample1/Program.cs index 90da0e5abc0..e61f7a4af15 100644 --- a/.dotnet/example_code_legacy/CloudWatch/AwsCloudWatchSample1/Program.cs +++ b/.dotnet/example_code_legacy/CloudWatch/AwsCloudWatchSample1/Program.cs @@ -1,27 +1,5 @@ -//snippet-sourcedescription:[CloudWatch example demonstrates how to various CloudWatch operations such as putting metrics on a CloudWatch alarm, describing all the existing alarms and enabling alarm actions.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Cloudwatch] -//snippet-service:[cloudwatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] -/******************************************************************************* -* Copyright 2009-2019 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. -*******************************************************************************/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; diff --git a/.dotnet/example_code_legacy/CloudWatchLogs/AwsCloudWatchSample1/Program.cs b/.dotnet/example_code_legacy/CloudWatchLogs/AwsCloudWatchSample1/Program.cs index 6c874ed0fcb..d6da5a582aa 100644 --- a/.dotnet/example_code_legacy/CloudWatchLogs/AwsCloudWatchSample1/Program.cs +++ b/.dotnet/example_code_legacy/CloudWatchLogs/AwsCloudWatchSample1/Program.cs @@ -1,27 +1,5 @@ -//snippet-sourcedescription:[CloudWatchLogs example demonstrates how to create a log group in CloudWatch and upload log events.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon CloudWatch Logs] -//snippet-service:[logs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] -/******************************************************************************* -* Copyright 2009-2019 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. -*******************************************************************************/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; diff --git a/.dotnet/example_code_legacy/DirectoryService/DirectoryServicePortTest.cs b/.dotnet/example_code_legacy/DirectoryService/DirectoryServicePortTest.cs index ce026dd0827..15ad411b416 100644 --- a/.dotnet/example_code_legacy/DirectoryService/DirectoryServicePortTest.cs +++ b/.dotnet/example_code_legacy/DirectoryService/DirectoryServicePortTest.cs @@ -1,28 +1,7 @@ -//snippet-sourcedescription:[Determines if the necessary ports are open from the VPC to your domain, and also verifies the minimum forest and domain functional levels.] -//snippet-keyword:[dotNET] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Directory Service] -//snippet-keyword:[DirectoryServicePortTest] -//snippet-service:[ds] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] -//snippet-start:[directoryservice.dotNET.directory_service_port_test.complete] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[directoryservice.dotNET.directory_service_port_test.complete] using System; using System.Collections.Generic; using System.IO; @@ -286,5 +265,5 @@ static List TestUdpPorts(List portList) } } } -//snippet-end:[directoryservice.dotNET.directory_service_port_test.complete] +// snippet-end:[directoryservice.dotNET.directory_service_port_test.complete] diff --git a/.dotnet/example_code_legacy/GameLift/GameLift-Unity-game-server.cs b/.dotnet/example_code_legacy/GameLift/GameLift-Unity-game-server.cs index f6579124df7..8beccc61fdb 100644 --- a/.dotnet/example_code_legacy/GameLift/GameLift-Unity-game-server.cs +++ b/.dotnet/example_code_legacy/GameLift/GameLift-Unity-game-server.cs @@ -1,31 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[GameLift-Unity-game-server.cs demonstrates a basic integration of Amazon GameLift into a Unity-built game server.] -// snippet-service:[gamelift] -// snippet-keyword:[Amazon GameLift] -//snippet-keyword:[dotNET] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[InitSDK] -//snippet-keyword:[ActivateGameSession] -//snippet-keyword:[ProcessReady] -//snippet-keyword:[ProcessEnding] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-11-5] -// snippet-sourceauthor:[AWS] // snippet-start:[gamelift.dotnet.game-server.unity] using UnityEngine; using Aws.GameLift.Server; diff --git a/.dotnet/example_code_legacy/GuardDuty/ListFindingsWCriteria/Program.cs b/.dotnet/example_code_legacy/GuardDuty/ListFindingsWCriteria/Program.cs index 612fbabf364..52960a59931 100644 --- a/.dotnet/example_code_legacy/GuardDuty/ListFindingsWCriteria/Program.cs +++ b/.dotnet/example_code_legacy/GuardDuty/ListFindingsWCriteria/Program.cs @@ -1,27 +1,5 @@ -//snippet-sourcedescription:[ListFindingsWCriteria example demonstrates how to list findings with criteria filters.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon GuardDuty] -//snippet-service:[guardduty] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] -/******************************************************************************* -* Copyright 2009-2019 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. -*******************************************************************************/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using System.Text; using System.Threading.Tasks; diff --git a/.dotnet/example_code_legacy/IAM/AwsInstanceProfile1/Program.cs b/.dotnet/example_code_legacy/IAM/AwsInstanceProfile1/Program.cs index db55de7b72b..7f343a6cd85 100644 --- a/.dotnet/example_code_legacy/IAM/AwsInstanceProfile1/Program.cs +++ b/.dotnet/example_code_legacy/IAM/AwsInstanceProfile1/Program.cs @@ -1,27 +1,5 @@ -//snippet-sourcedescription:[AwsInstanceProfile1 example demonstrates how to use the various operations, like create user, on the IAM client.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] -/******************************************************************************* -* Copyright 2009-2019 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. -*******************************************************************************/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using System.IO; diff --git a/.dotnet/example_code_legacy/Pinpoint/pinpoint_send_email_message_api.cs b/.dotnet/example_code_legacy/Pinpoint/pinpoint_send_email_message_api.cs index e8e6e6b007f..eea77e4c6cc 100644 --- a/.dotnet/example_code_legacy/Pinpoint/pinpoint_send_email_message_api.cs +++ b/.dotnet/example_code_legacy/Pinpoint/pinpoint_send_email_message_api.cs @@ -1,28 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[pinpoint_send_email_message_api demonstrates how to send a transactional email message by using the SendMessages operation in the Amazon Pinpoint API.] -// snippet-service:[mobiletargeting] -// snippet-keyword:[dotnet] -// snippet-keyword:[.NET] -// snippet-sourcesyntax:[.net] -// snippet-keyword:[Amazon Pinpoint] -// snippet-keyword:[Code Sample] -// snippet-keyword:[SendMessages] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-20] -// snippet-sourceauthor:[AWS] // snippet-start:[pinpoint.dotnet.pinpoint_send_email_message_api.complete] using System; diff --git a/.dotnet/example_code_legacy/Pinpoint/pinpoint_send_email_smtp.cs b/.dotnet/example_code_legacy/Pinpoint/pinpoint_send_email_smtp.cs index 1de2ed3ac0e..36d50d28cfa 100644 --- a/.dotnet/example_code_legacy/Pinpoint/pinpoint_send_email_smtp.cs +++ b/.dotnet/example_code_legacy/Pinpoint/pinpoint_send_email_smtp.cs @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[pinpoint_send_email_smtp demonstrates how to send a transactional email message by using Amazon Pinpoint SMTP interface.] -// snippet-service:[mobiletargeting] -// snippet-keyword:[dotnet] -// snippet-keyword:[.NET] -// snippet-sourcesyntax:[.net] -// snippet-keyword:[Amazon Pinpoint] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-20] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[pinpoint.dotnet.pinpoint_send_email_smtp.complete] using System; diff --git a/.dotnet/example_code_legacy/Pinpoint/pinpoint_send_sms_message_api.cs b/.dotnet/example_code_legacy/Pinpoint/pinpoint_send_sms_message_api.cs index 673a41c7679..3b9bea229cd 100644 --- a/.dotnet/example_code_legacy/Pinpoint/pinpoint_send_sms_message_api.cs +++ b/.dotnet/example_code_legacy/Pinpoint/pinpoint_send_sms_message_api.cs @@ -1,28 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[pinpoint_send_sms_message_api demonstrates how to send a transactional SMS message by using the SendMessages operation in the Amazon Pinpoint API.] -// snippet-service:[mobiletargeting] -// snippet-keyword:[dotnet] -// snippet-keyword:[.NET] -// snippet-sourcesyntax:[.net] -// snippet-keyword:[Amazon Pinpoint] -// snippet-keyword:[Code Sample] -// snippet-keyword:[SendMessages] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-20] -// snippet-sourceauthor:[AWS] // snippet-start:[pinpoint.dotnet.pinpoint_send_sms_message_api.complete] using System; diff --git a/.dotnet/example_code_legacy/Polly/pollysamples1/DeleteLexiconSample.cs b/.dotnet/example_code_legacy/Polly/pollysamples1/DeleteLexiconSample.cs index c1397229cb7..cb7418f38ca 100644 --- a/.dotnet/example_code_legacy/Polly/pollysamples1/DeleteLexiconSample.cs +++ b/.dotnet/example_code_legacy/Polly/pollysamples1/DeleteLexiconSample.cs @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[DeleteLexiconSample.cs demonstrates how to delete an existing lexicon.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Polly] -//snippet-service:[polly] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using Amazon.Polly; using Amazon.Polly.Model; diff --git a/.dotnet/example_code_legacy/Polly/pollysamples1/DescribeVoicesSample.cs b/.dotnet/example_code_legacy/Polly/pollysamples1/DescribeVoicesSample.cs index 4de4c09ba93..f7bf347ddec 100644 --- a/.dotnet/example_code_legacy/Polly/pollysamples1/DescribeVoicesSample.cs +++ b/.dotnet/example_code_legacy/Polly/pollysamples1/DescribeVoicesSample.cs @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[DescribeVoicesSample.cs demonstrates how to get information on all defined AWS Polly voices and all defined voices for a specific language.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Polly] -//snippet-service:[polly] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using Amazon.Polly; using Amazon.Polly.Model; diff --git a/.dotnet/example_code_legacy/Polly/pollysamples1/GetLexiconSample.cs b/.dotnet/example_code_legacy/Polly/pollysamples1/GetLexiconSample.cs index c51896d7a18..60b45f33a3c 100644 --- a/.dotnet/example_code_legacy/Polly/pollysamples1/GetLexiconSample.cs +++ b/.dotnet/example_code_legacy/Polly/pollysamples1/GetLexiconSample.cs @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[GetLexiconSample.cs demonstrates how to get the content of the specified pronunciation lexicon.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Polly] -//snippet-service:[polly] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using Amazon.Polly; using Amazon.Polly.Model; diff --git a/.dotnet/example_code_legacy/Polly/pollysamples1/ListLexiconsSample.cs b/.dotnet/example_code_legacy/Polly/pollysamples1/ListLexiconsSample.cs index ac97fcfd6fb..0b9d8ea1fc4 100644 --- a/.dotnet/example_code_legacy/Polly/pollysamples1/ListLexiconsSample.cs +++ b/.dotnet/example_code_legacy/Polly/pollysamples1/ListLexiconsSample.cs @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[ListLexiconsSample.cs demonstrates how to get a list of pronunciation lexicons stored in an AWS Region.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Polly] -//snippet-service:[polly] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using Amazon.Polly; using Amazon.Polly.Model; diff --git a/.dotnet/example_code_legacy/Polly/pollysamples1/Program.cs b/.dotnet/example_code_legacy/Polly/pollysamples1/Program.cs index e1cba59bc0b..9bc56bcf4f7 100644 --- a/.dotnet/example_code_legacy/Polly/pollysamples1/Program.cs +++ b/.dotnet/example_code_legacy/Polly/pollysamples1/Program.cs @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[Program.cs can be used to execute the Polly examples in this solution.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Polly] -//snippet-service:[polly] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; diff --git a/.dotnet/example_code_legacy/Polly/pollysamples1/Properties/AssemblyInfo.cs b/.dotnet/example_code_legacy/Polly/pollysamples1/Properties/AssemblyInfo.cs index 481bee400b2..1589a87c97a 100644 --- a/.dotnet/example_code_legacy/Polly/pollysamples1/Properties/AssemblyInfo.cs +++ b/.dotnet/example_code_legacy/Polly/pollysamples1/Properties/AssemblyInfo.cs @@ -1,16 +1,6 @@ -//snippet-sourcedescription:[<> demonstrates how to ...] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-service:[<>] -//snippet-sourcetype:[<>] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] - -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/.dotnet/example_code_legacy/Polly/pollysamples1/PutLexiconSample.cs b/.dotnet/example_code_legacy/Polly/pollysamples1/PutLexiconSample.cs index 1a92645da08..7bc6a406c54 100644 --- a/.dotnet/example_code_legacy/Polly/pollysamples1/PutLexiconSample.cs +++ b/.dotnet/example_code_legacy/Polly/pollysamples1/PutLexiconSample.cs @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[PutLexiconSample.cs demonstrates how to add a new lexicon.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Polly] -//snippet-service:[polly] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using Amazon.Polly; using Amazon.Polly.Model; diff --git a/.dotnet/example_code_legacy/Polly/pollysamples1/SynthesizeSpeechMarksSample.cs b/.dotnet/example_code_legacy/Polly/pollysamples1/SynthesizeSpeechMarksSample.cs index 88e1fd94203..abae3a98d53 100644 --- a/.dotnet/example_code_legacy/Polly/pollysamples1/SynthesizeSpeechMarksSample.cs +++ b/.dotnet/example_code_legacy/Polly/pollysamples1/SynthesizeSpeechMarksSample.cs @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[SynthesizeSpeechMarksSample.cs demonstrates how to synthesize speech marks for an input text.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Polly] -//snippet-service:[polly] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; diff --git a/.dotnet/example_code_legacy/Polly/pollysamples1/SynthesizeSpeechSample.cs b/.dotnet/example_code_legacy/Polly/pollysamples1/SynthesizeSpeechSample.cs index 77be8a20e32..c1f1869336f 100644 --- a/.dotnet/example_code_legacy/Polly/pollysamples1/SynthesizeSpeechSample.cs +++ b/.dotnet/example_code_legacy/Polly/pollysamples1/SynthesizeSpeechSample.cs @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[SynthesizeSpeechSample.cs demonstrates how to get a synthesized audio file as a stream of bytes from a text input.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Polly] -//snippet-service:[polly] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; diff --git a/.dotnet/example_code_legacy/Redshift/ConnectToClusterExample.cs b/.dotnet/example_code_legacy/Redshift/ConnectToClusterExample.cs index 15670b313e1..fc563db18b0 100644 --- a/.dotnet/example_code_legacy/Redshift/ConnectToClusterExample.cs +++ b/.dotnet/example_code_legacy/Redshift/ConnectToClusterExample.cs @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[ConnectToClusterExample demonstrates how to connect to an Amazon Redshift cluster.] -// snippet-service:[redshift] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon Redshift] -// snippet-keyword:[Code Sample] -// snippet-keyword:[Connect] -// snippet-keyword:[ODBC] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2015-02-19] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[redshift.dotnet.ConnectToClusterExample.complete] using System; diff --git a/.dotnet/example_code_legacy/S3/Program.cs b/.dotnet/example_code_legacy/S3/Program.cs index 1264e4e5d5c..df581c33255 100644 --- a/.dotnet/example_code_legacy/S3/Program.cs +++ b/.dotnet/example_code_legacy/S3/Program.cs @@ -1,28 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[Program.cs demonstrates how to list, create, and delete a bucket in Amazon S3.] -// snippet-service:[s3] -// snippet-keyword:[dotNET] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ListBucketsAsync] -// snippet-keyword:[PutBucketAsync] -// snippet-keyword:[DeleteBucketAsync] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-05-29] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.dotnet.bucket_operations.list_create_delete] using Amazon; using Amazon.S3; diff --git a/.dotnet/example_code_legacy/S3/S3Async.cs b/.dotnet/example_code_legacy/S3/S3Async.cs index 331683caf0c..c5b765edf4a 100644 --- a/.dotnet/example_code_legacy/S3/S3Async.cs +++ b/.dotnet/example_code_legacy/S3/S3Async.cs @@ -1,27 +1,6 @@ -// snippet-sourcedescription:[S3Async.cs demonstrates how to synchronously and asynchronously add objects to an Amazon S3 bucket.] -// snippet-service:[s3] -// snippet-keyword:[.NET] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[PutObject] -// snippet-keyword:[BeginPutObject] -// snippet-keyword:[EndPutObject] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-01-12] -// snippet-sourceauthor:[AWS-NET-DG] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[s3.dotnet.putobject.async.complete] using System; using System.Threading; diff --git a/.dotnet/example_code_legacy/S3/S3ShowTextItem.cs b/.dotnet/example_code_legacy/S3/S3ShowTextItem.cs index bc92f56191d..146cae0fd5f 100644 --- a/.dotnet/example_code_legacy/S3/S3ShowTextItem.cs +++ b/.dotnet/example_code_legacy/S3/S3ShowTextItem.cs @@ -1,27 +1,5 @@ -//snippet-sourcedescription:[S3ShowTextItem.cs demonstrates how to display a text-only Amazon S3 bucket item.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2020-01-18] -//snippet-sourceauthor:[AWS-NET-DG] -/******************************************************************************* -* Copyright 2009-2019 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. -*******************************************************************************/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* To compile, use the VS command prompt and run (all on one line): diff --git a/.dotnet/example_code_legacy/SNS/Sns_Samples.cs b/.dotnet/example_code_legacy/SNS/Sns_Samples.cs index 7cd9dacdd8e..88bec507b23 100644 --- a/.dotnet/example_code_legacy/SNS/Sns_Samples.cs +++ b/.dotnet/example_code_legacy/SNS/Sns_Samples.cs @@ -1,28 +1,5 @@ -//snippet-sourcedescription:[Sns_Samples contains various examples that use Amazon SNS.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Notification Service] -//snippet-service:[sns] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-11-18] -//snippet-sourceauthor:[Doug-AWS] - -/******************************************************************************* -* Copyright 2009-2019 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. -*******************************************************************************/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* using System; diff --git a/.dotnet/example_code_legacy/SQS/AwsSqsSample1/Program.cs b/.dotnet/example_code_legacy/SQS/AwsSqsSample1/Program.cs index 918d04a5b43..af9eb17451a 100644 --- a/.dotnet/example_code_legacy/SQS/AwsSqsSample1/Program.cs +++ b/.dotnet/example_code_legacy/SQS/AwsSqsSample1/Program.cs @@ -1,27 +1,5 @@ -//snippet-sourcedescription:[AwsSqsSample1 example demonstrates how to use the various queue and message operations on the Amazon SQS client.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Queue Service] -//snippet-service:[sqs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] -/******************************************************************************* -* Copyright 2009-2019 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. -*******************************************************************************/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using System.Collections; diff --git a/.dotnet/example_code_legacy/STS/AssumeRole/AssumeRole.cs b/.dotnet/example_code_legacy/STS/AssumeRole/AssumeRole.cs index 10e90b97087..a6c8b9d507a 100644 --- a/.dotnet/example_code_legacy/STS/AssumeRole/AssumeRole.cs +++ b/.dotnet/example_code_legacy/STS/AssumeRole/AssumeRole.cs @@ -1,27 +1,5 @@ -//snippet-sourcedescription:[AssumeRole.cs demonstrates how to get temporary credentials using the AWS STS client.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Security Token Service (STS)] -//snippet-service:[sts] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] -/******************************************************************************* -* Copyright 2009-2019 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. -*******************************************************************************/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using Amazon.SecurityToken; diff --git a/.dotnet/example_code_legacy/STS/AssumeRoleWithSAML/AssumeRoleWithSAML.cs b/.dotnet/example_code_legacy/STS/AssumeRoleWithSAML/AssumeRoleWithSAML.cs index 772ba13dbc6..37baf36461b 100644 --- a/.dotnet/example_code_legacy/STS/AssumeRoleWithSAML/AssumeRoleWithSAML.cs +++ b/.dotnet/example_code_legacy/STS/AssumeRoleWithSAML/AssumeRoleWithSAML.cs @@ -1,28 +1,7 @@ -//snippet-sourcedescription:[AssumeRole.cs demonstrates how to get temporary credentials using the AWS STS client.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Security Token Service (STS)] -//snippet-service:[sts] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-03-26] -//snippet-sourceauthor:[walkerk1980] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[sts.dotNET.CodeExample.AssumeRoleWithSAML] -/******************************************************************************* -* Copyright 2009-2019 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. -*******************************************************************************/ using System; using System.IO; diff --git a/.dotnet/example_code_legacy/STS/GetCallerIdentity/GetCallerIdentity.cs b/.dotnet/example_code_legacy/STS/GetCallerIdentity/GetCallerIdentity.cs index 2942feba20d..ad0104c8440 100644 --- a/.dotnet/example_code_legacy/STS/GetCallerIdentity/GetCallerIdentity.cs +++ b/.dotnet/example_code_legacy/STS/GetCallerIdentity/GetCallerIdentity.cs @@ -1,27 +1,5 @@ -//snippet-sourcedescription:[AssumeRole.cs demonstrates how to get caller identity using the AWS STS client.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Security Token Service (STS)] -//snippet-service:[sts] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[walkerk1980] -/******************************************************************************* -* Copyright 2009-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. -*******************************************************************************/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using Amazon.SecurityToken; diff --git a/.dotnet/example_code_legacy/SecretsManager/GetSecretValue/GetSecretValue.cs b/.dotnet/example_code_legacy/SecretsManager/GetSecretValue/GetSecretValue.cs index 88d6969320e..3a0d2f2462b 100644 --- a/.dotnet/example_code_legacy/SecretsManager/GetSecretValue/GetSecretValue.cs +++ b/.dotnet/example_code_legacy/SecretsManager/GetSecretValue/GetSecretValue.cs @@ -1,29 +1,6 @@ -//snippet-sourcedescription:[GetSecretValue demonstrates how to retrieve a secret from AWS Secrets Manager] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Secrets Manager] -//snippet-service:[secretsmanager] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[9/25/18] -//snippet-sourceauthor:[AWS] - -/******************************************************************************* -* Copyright 2009-2019 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. -*******************************************************************************/ -`/* +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* * Use this code snippet in your app. * If you need more information about configurations or implementing the sample code, visit the AWS docs: * https://aws.amazon.com/developers/getting-started/net/ diff --git a/.dotnet/example_code_legacy/WorkDocs/workdocssample1/DownloadUserDoc.cs b/.dotnet/example_code_legacy/WorkDocs/workdocssample1/DownloadUserDoc.cs index ddcb75973ea..bd50930f607 100644 --- a/.dotnet/example_code_legacy/WorkDocs/workdocssample1/DownloadUserDoc.cs +++ b/.dotnet/example_code_legacy/WorkDocs/workdocssample1/DownloadUserDoc.cs @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[DownloadUserDoc.cs demonstrates how to download a document from Amazon Workdocs.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon WorkDocs] -//snippet-service:[workdocs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Net; diff --git a/.dotnet/example_code_legacy/WorkDocs/workdocssample1/ListUserDocs.cs b/.dotnet/example_code_legacy/WorkDocs/workdocssample1/ListUserDocs.cs index e5aacbaaf95..66f90d5196c 100644 --- a/.dotnet/example_code_legacy/WorkDocs/workdocssample1/ListUserDocs.cs +++ b/.dotnet/example_code_legacy/WorkDocs/workdocssample1/ListUserDocs.cs @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[<> demonstrates how to list user documents in a folder from Amazon Workdocs.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon WorkDocs] -//snippet-service:[workdocs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; diff --git a/.dotnet/example_code_legacy/WorkDocs/workdocssample1/ListUsers.cs b/.dotnet/example_code_legacy/WorkDocs/workdocssample1/ListUsers.cs index 7ba81b67039..972596fafc1 100644 --- a/.dotnet/example_code_legacy/WorkDocs/workdocssample1/ListUsers.cs +++ b/.dotnet/example_code_legacy/WorkDocs/workdocssample1/ListUsers.cs @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[ListUsers.cs demonstrates how to list the users for Amazon WorkDocs.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon WorkDocs] -//snippet-service:[workdocs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; diff --git a/.dotnet/example_code_legacy/WorkDocs/workdocssample1/Program.cs b/.dotnet/example_code_legacy/WorkDocs/workdocssample1/Program.cs index a40107f2050..f601422f068 100644 --- a/.dotnet/example_code_legacy/WorkDocs/workdocssample1/Program.cs +++ b/.dotnet/example_code_legacy/WorkDocs/workdocssample1/Program.cs @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[Program.cs can be used to execute the WorkDocs examples in this solution.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon WorkDocs] -//snippet-service:[workdocs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; diff --git a/.dotnet/example_code_legacy/WorkDocs/workdocssample1/UploadUserDoc.cs b/.dotnet/example_code_legacy/WorkDocs/workdocssample1/UploadUserDoc.cs index f054d7f1298..a4f6a5f2b3b 100644 --- a/.dotnet/example_code_legacy/WorkDocs/workdocssample1/UploadUserDoc.cs +++ b/.dotnet/example_code_legacy/WorkDocs/workdocssample1/UploadUserDoc.cs @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[UploadUserDoc.cs demonstrates how to upload a file to Amazon WorkDocs.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon WorkDocs] -//snippet-service:[workdocs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Net; diff --git a/.dotnet/example_code_legacy/comprehend/ComprehendSamples1/Program.cs b/.dotnet/example_code_legacy/comprehend/ComprehendSamples1/Program.cs index 8d426438568..721804a076a 100644 --- a/.dotnet/example_code_legacy/comprehend/ComprehendSamples1/Program.cs +++ b/.dotnet/example_code_legacy/comprehend/ComprehendSamples1/Program.cs @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[Program.cs can be used to run the examples in this ComprehendSamples1 solution.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Comprehend] -//snippet-service:[comprehend] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; diff --git a/.dotnet/example_code_legacy/ec2/AwsEC2Sample1/Program.cs b/.dotnet/example_code_legacy/ec2/AwsEC2Sample1/Program.cs index 59ab3ad06ad..1e6e53e4264 100644 --- a/.dotnet/example_code_legacy/ec2/AwsEC2Sample1/Program.cs +++ b/.dotnet/example_code_legacy/ec2/AwsEC2Sample1/Program.cs @@ -1,27 +1,5 @@ -//snippet-sourcedescription:[AwsEC2Sample2 example demonstrates how to use various operations, like create instance and create key pairs, in the EC2 client.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] -/******************************************************************************* -* Copyright 2009-2019 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. -*******************************************************************************/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; diff --git a/.dotnet/example_code_legacy/ec2/Ec2SpotCRUD.cs b/.dotnet/example_code_legacy/ec2/Ec2SpotCRUD.cs index 3d489318651..57bff1a0eea 100644 --- a/.dotnet/example_code_legacy/ec2/Ec2SpotCRUD.cs +++ b/.dotnet/example_code_legacy/ec2/Ec2SpotCRUD.cs @@ -1,28 +1,5 @@ -//snippet-sourcedescription:[Ec2SpotCRUD demonstrates how to create, cancel, and terminate a spot instance request using Amazon EC2.] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Elastic Compute Cloud] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[Oct 10, 2019] -//snippet-sourceauthor:[Doug-AWS] -/******************************************************************************* -* Copyright 2009-2019 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. -*******************************************************************************/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* Build Don't forget to use the Visual Studio command prompt Tested with csc /version == 2.10.0.0 diff --git a/.dotnet/example_code_legacy/ec2/SampleHarness/ManageKeyPairs.cs b/.dotnet/example_code_legacy/ec2/SampleHarness/ManageKeyPairs.cs index 10057c4a077..3c21f59d2e8 100644 --- a/.dotnet/example_code_legacy/ec2/SampleHarness/ManageKeyPairs.cs +++ b/.dotnet/example_code_legacy/ec2/SampleHarness/ManageKeyPairs.cs @@ -1,30 +1,9 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -//snippet-sourcedescription:[<> demonstrates how to ...] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[<>] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] - -/******************************************************************************* -* Copyright 2009-2019 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. -*******************************************************************************/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon.EC2; using Amazon.EC2.Model; diff --git a/.dotnet/example_code_legacy/ec2/SampleHarness/ManageSecurityGroups.cs b/.dotnet/example_code_legacy/ec2/SampleHarness/ManageSecurityGroups.cs index fe8124bfb70..4959ebb0089 100644 --- a/.dotnet/example_code_legacy/ec2/SampleHarness/ManageSecurityGroups.cs +++ b/.dotnet/example_code_legacy/ec2/SampleHarness/ManageSecurityGroups.cs @@ -1,30 +1,9 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -//snippet-sourcedescription:[<> demonstrates how to ...] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[<>] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] - -/******************************************************************************* -* Copyright 2009-2019 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. -*******************************************************************************/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon.EC2; using Amazon.EC2.Model; diff --git a/.dotnet/example_code_legacy/ec2/SampleHarness/Program.cs b/.dotnet/example_code_legacy/ec2/SampleHarness/Program.cs index f08039ac806..2205cae7a84 100644 --- a/.dotnet/example_code_legacy/ec2/SampleHarness/Program.cs +++ b/.dotnet/example_code_legacy/ec2/SampleHarness/Program.cs @@ -1,30 +1,9 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -//snippet-sourcedescription:[<> demonstrates how to ...] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[<>] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] - - -/******************************************************************************* -* Copyright 2009-2019 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. -*******************************************************************************/ + +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using Amazon; diff --git a/.dotnet/example_code_legacy/ec2/SampleHarness/Properties/AssemblyInfo.cs b/.dotnet/example_code_legacy/ec2/SampleHarness/Properties/AssemblyInfo.cs index 856f4e3a838..1f4dd8c8663 100644 --- a/.dotnet/example_code_legacy/ec2/SampleHarness/Properties/AssemblyInfo.cs +++ b/.dotnet/example_code_legacy/ec2/SampleHarness/Properties/AssemblyInfo.cs @@ -1,17 +1,6 @@ -//snippet-sourcedescription:[<> demonstrates how to ...] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[<>] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] - -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/.dotnet/example_code_legacy/ec2/SampleHarness/RunAndControlInstances.cs b/.dotnet/example_code_legacy/ec2/SampleHarness/RunAndControlInstances.cs index 1b41481e12d..788f5bc45ad 100644 --- a/.dotnet/example_code_legacy/ec2/SampleHarness/RunAndControlInstances.cs +++ b/.dotnet/example_code_legacy/ec2/SampleHarness/RunAndControlInstances.cs @@ -1,30 +1,9 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -//snippet-sourcedescription:[<> demonstrates how to ...] -//snippet-keyword:[dotnet] -//snippet-keyword:[.NET] -//snippet-sourcesyntax:[.net] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[<>] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] - - -/******************************************************************************* -* Copyright 2009-2019 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. -*******************************************************************************/ + +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon.EC2; using Amazon.EC2.Model; diff --git a/.github/extract-snippets/README.md b/.github/extract-snippets/README.md index 36ae2d1939f..3800ea7ceff 100644 --- a/.github/extract-snippets/README.md +++ b/.github/extract-snippets/README.md @@ -7,104 +7,100 @@ Last updated 24-Jun-2021 This is a suite of GitHub Actions workflows with supporting scripts that extracts code snippets from source code files, which can then be used in -documentation via include directives. When the code changes, the snippets are +documentation via include directives. When the code changes, the snippets are automatically extracted again, and the documentation will pick them up on the next build. -There are two separate workflows: +There are two separate workflows: -* Extract Snippets (`extract-snippets.yaml`): Extracts snippets from all source - files in the repo. Runs on a commit to the main or master branch; can also be +- Extract Snippets (`extract-snippets.yaml`): Extracts snippets from all source + files in the repo. Runs on a commit to the main or master branch; can also be run manually. -* Extract Snippets Dry Run (`extract-snippets-dryrun.yml`): Extracts snippets +- Extract Snippets Dry Run (`extract-snippets-dryrun.yml`): Extracts snippets from all source files in a pull request but does not check in any snippets; - meant to validate PRs. Displays only the issue report (problems found in the - extraction process). Can also be run manually. + meant to validate PRs. Displays only the issue report (problems found in the + extraction process). Can also be run manually. To prevent the introduction of consistency problems in the snippets (e.g. duplicate snippet filenames with different content), all files in the repo are -always processed. This is not noticeably slower than e.g. processing only the +always processed. This is not noticeably slower than e.g. processing only the files in a given commit; the overhead of the action setup and Git commands overshadows the run time of the actual snippet extraction. ## Compared to other snippet extraction tools The AWS Docs organization has a tool which it uses to extract snippets from -source files. Compared to that tool, this tool has the following additional +source files. Compared to that tool, this tool has the following additional features: -* Runs on GitHub so snippets can be automatically updated on every commit. -* Includes snippet-append and snippet-echo tags (see below). -* Can dedent (remove indentation from) extracted snippets. -* Checks for and logs a variety of problems, including conflicting snippet +- Runs on GitHub so snippets can be automatically updated on every commit. +- Includes snippet-append and snippet-echo tags (see below). +- Can dedent (remove indentation from) extracted snippets. +- Checks for and logs a variety of problems, including conflicting snippet tags (same tag in multiple files). -* Besides a processing log, produces a report of files with problems and an +- Besides a processing log, produces a report of files with problems and an index mapping snippet tags back to the file(s) that contain them. It does not have the following features of the AWS Docs tool: -* Extract metadata from snippets for use in catalogs. The metadata tags are +- Extract metadata from snippets for use in catalogs. The metadata tags are recognized, but do not do anything, in this snippet extractor. - + ## Snippet tags -Snippet tags are special single-line comments in source files. They must not +Snippet tags are special single-line comments in source files. They must not follow any code on their line and must begin with the language's single-line -comment marker (`//` in many languages, `#` in some others). If a language does +comment marker (`//` in many languages, `#` in some others). If a language does not have a single-line comment marker, the block comment delimiter may be used, -but should be closed on the same line following the snippet tag. The snippet +but should be closed on the same line following the snippet tag. The snippet tag is followed by the snippet directive, a colon, and an argument in square -brackets. Whitespace is permitted (but optional) between the comment marker and +brackets. Whitespace is permitted (but optional) between the comment marker and the snippet directive. For example: -// snippet-start:[cdk.typescript.widget_service] - -Here, the directive begins the extraction of a code snippet to the filename +Here, the directive begins the extraction of a code snippet to the filename specified, with a `.txt` extension. -The main tags used in our repos are `snippet-start` and `snippet-end`. Each +The main tags used in our repos are `snippet-start` and `snippet-end`. Each `snippet-start` requires a matching `snippet-end` (specifying the same snippet -name) in the same source file. Multiple snippets may be extracted from one -source file, and may overlap. The snippet tags do not appear in the extracted +name) in the same source file. Multiple snippets may be extracted from one +source file, and may overlap. The snippet tags do not appear in the extracted snippets. The following tags are unique to this extractor (they are not supported by the snippet extractor used by the AWS Docs team). -* `snippet-append`: Extracts additional source code to a snippet file that has +- `snippet-append`: Extracts additional source code to a snippet file that has already been created by a previous `snippet-start` directive, stopping at `snippet-end` as with `snippet-start`. -* `snippet-echo`: Writes the argument literally to the snippet(s) currently - being extracted. Useful for adding closing braces etc. when extracting a - partial code block. Whitespace is stripped from the right of the argument but +- `snippet-echo`: Writes the argument literally to the snippet(s) currently + being extracted. Useful for adding closing braces etc. when extracting a + partial code block. Whitespace is stripped from the right of the argument but not the left, so you can match indentation. Also unique to this extractor, `snippet-start` supports an optional number -following the closing bracket. - -// snippet-start:[my-snippet] 8 +following the closing bracket. -If this number is present, that many spaces are removed from the beginning of +If this number is present, that many spaces are removed from the beginning of each line of the snippet, allowing snippets to be dedented (have indentation -removed), so their left margin is decreased. Each snippet, even overlapping -snippets, has its own dedent level. If you use `snippet-append`, it uses the -same dedent specified on `snippet-start`. Dedent does not affect +removed), so their left margin is decreased. Each snippet, even overlapping +snippets, has its own dedent level. If you use `snippet-append`, it uses the +same dedent specified on `snippet-start`. Dedent does not affect `snippet-echo`, so provide the desired indentation yourself. This extractor also recognizes the following tags (i.e. they are not errors), -but does not do anything with them. They are supported for compatibility with +but does not do anything with them. They are supported for compatibility with source files tagged for the original AWS Docs extractor, which can register metadata about each snippet. -* `snippet-keyword` -* `snippet-service` -* `snippet-sourceauthor` -* `snippet-sourcedate` -* `snippet-sourcedescription` -* `snippet-sourcesyntax` -* `snippet-sourcetype` +- `snippet-keyword` +- `snippet-service` +- `snippet-sourceauthor` +- `snippet-sourcedate` +- `snippet-sourcedescription` +- `snippet-sourcesyntax` +- `snippet-sourcetype` ## extract-snippets.sh @@ -116,10 +112,10 @@ extracting the snippets without adding them to the repo ("dry run" mode). ## extract-snippets.py This script reads from standard input the paths of the files containing the -snippets to be extracted. It ignores non-source files, hidden files, and files +snippets to be extracted. It ignores non-source files, hidden files, and files in hidden directories (it is not necessary to filter out such files beforehand). The script's required argument is the directory that the snippets should be -extracted into. This directory must not contain any files named the same as a +extracted into. This directory must not contain any files named the same as a snippet being extracted. For example, the following command runs the script on source files in the @@ -134,7 +130,7 @@ Windows during development. The supported source file formats are stored in `snippet-extensions.yml` or another file specified as the second command-line argument. This file is a YAML -map of filename extensions to comment markers. If a language supports more than +map of filename extensions to comment markers. If a language supports more than one line comment marker, you can provide them separated by whitespace in a single string: @@ -143,30 +139,30 @@ single string: ``` If a language does not support a line comment marker (e.g. C), you can specify -its starting block comment marker. However, the extraction process does not +its starting block comment marker. However, the extraction process does not include the lines with the snippet tags in the snippets, so you should include the closing block comment marker on the same line to avoid the closing marker -being included in the snippet. For example: +being included in the snippet. For example: -/* snippet-start:[terry.riley.in-c] */ +/_ snippet-start:[terry.riley.in-c] _/ Not: -/* snippet-start:[terry.riley.in-c]
-*/ +/_ snippet-start:[terry.riley.in-c]
+_/ -Some languages support both line and block comments. In this case, we suggest +Some languages support both line and block comments. In this case, we suggest you always use the line comment marker for snippet tags. You may pass a different YAML (or JSON) file as the script's second argument -- for example, the provided `snippet-extensions-more.yml`, which contains a more -extensive map of source formats. Note that if you specify only a filename, the -file of that name *in the same directory as the script* (not in the working -directory!) is used. To specify a file in the current directory, use `./`, e.g. +extensive map of source formats. Note that if you specify only a filename, the +file of that name _in the same directory as the script_ (not in the working +directory!) is used. To specify a file in the current directory, use `./`, e.g. `./my-snippet-extensions.yml`. The keys in `snippet-extensions.yml` are matched case-sensitively at the end of -file paths, and can be used to match more than extensions. If you wanted to +file paths, and can be used to match more than extensions. If you wanted to extract snippets from makefiles, for example, you could add to the mapping: ``` @@ -174,7 +170,7 @@ extract snippets from makefiles, for example, you could add to the mapping: ``` The slash makes it match the complete filename: i.e., there is a directory -separator, then "makefile", at the end of the path. Always use `/` for this +separator, then "makefile", at the end of the path. Always use `/` for this purpose even if you are using Windows paths with backslashes; paths are normalized to use slashes before this comparison. @@ -182,13 +178,13 @@ If a given path could match more than one language, the first one listed in the extension file wins. To match all files, use `""` as the key (after all, there's an empty string at -the end of every path -- in fact, infinitely many of them). You probably -shouldn't do this, but you *can.* It might be useful as a catch-all in a repo +the end of every path -- in fact, infinitely many of them). You probably +shouldn't do this, but you _can._ It might be useful as a catch-all in a repo where you want to process all files and most languages in the repo use the same -comment marker. It should go last in the extensions file. +comment marker. It should go last in the extensions file. To exclude a file or files from being processed, specify the end of its path and -an empty string as the comment marker. Such items should appear earlier in the +an empty string as the comment marker. Such items should appear earlier in the file than others that might match, since the first match wins. ``` @@ -197,63 +193,63 @@ file than others that might match, since the first match wins. The output of `extract-snippets.py` is a list of the source files processed. Indented under each source file is a list of the snippets extracted from it, if -any, notated with EXTRACT. APPEND operations, errors, and warnings are also -flagged in similar fashion under the source file. +any, notated with EXTRACT. APPEND operations, errors, and warnings are also +flagged in similar fashion under the source file. At the end of the run, a summary line displays the number of unique snippets -extracted and the number of source files examined. This is followed by a report +extracted and the number of source files examined. This is followed by a report of all files with issues, and an index that maps snippets back to the files that contain them. ## Errors -The following situations are considered problematic to varying degrees. To the +The following situations are considered problematic to varying degrees. To the extent possible, errors do not stop processing. -* Unrecognized snippet tag (see earlier section for supported tags). +- Unrecognized snippet tag (see earlier section for supported tags). -* Text decoding error. By default, source files are assumed to be UTF-8. To +- Text decoding error. By default, source files are assumed to be UTF-8. To change the encoding used, sent the environment variable `SOURCE_ENCODING` to - `utf16` or another encoding. Use the Python name, which you can find here: + `utf16` or another encoding. Use the Python name, which you can find here: https://docs.python.org/3/library/codecs.html#standard-encodings - Generally you'd do this in the action file, not in the `bash` script. Like: + Generally you'd do this in the action file, not in the `bash` script. Like: ```yaml - # goes under the `steps` key - env: - SOURCE_ENCODING: utf-16 +# goes under the `steps` key +env: + SOURCE_ENCODING: utf-16 ``` - If a file cannot be read, processing continues with the next file, if any. +If a file cannot be read, processing continues with the next file, if any. -* `snippet-start` for a snippet file that has already been extracted, *unless* +- `snippet-start` for a snippet file that has already been extracted, _unless_ the source file has the same filename and contains exactly the same code. This behavior supports multiple examples that contain the same source code for an incorporated Lambda function or other asset, where that code contains snippets. The former situation is an error, the latter a warning. -* `snippet-end` with no corresponding `snippet-start` or `snippet-append` in the +- `snippet-end` with no corresponding `snippet-start` or `snippet-append` in the same source file. -* Missing `snippet-end` corresponding to a `snippet-start` or `snippet-append`. +- Missing `snippet-end` corresponding to a `snippet-start` or `snippet-append`. -* `snippet-append` with no corresponding `snippet-start` in the same source file +- `snippet-append` with no corresponding `snippet-start` in the same source file (you can't append to snippets created in a different source file since there's no guarantee the files will be processed in any particular order, or that all files will even be processed, leading to consistency issues). -* `snippet-echo` outside of a snippet. +- `snippet-echo` outside of a snippet. -* Insufficient whitespace at the beginning of a line to dedent it as required. +- Insufficient whitespace at the beginning of a line to dedent it as required. -* Any source file contains both a tag and a tab character (ASCII 9), as - indenting by tab is not well-supported in documentation. This is a warning, +- Any source file contains both a tag and a tab character (ASCII 9), as + indenting by tab is not well-supported in documentation. This is a warning, and will not on its own stop extracted snippets from being checked in. If there is at least one error, none of the extracted snippets will be checked -in. Warnings *do not* prevent snippets from being checked in. +in. Warnings _do not_ prevent snippets from being checked in. # README-SNIPPETS.txt @@ -262,11 +258,11 @@ provide information that users of the snippets should know. # Version history -* v1.0.0 - Initial pull request against the CDK Examples repo. -* v1.1.0 - Test against SDK team's examples repo and fix the problems found. - Continue processing after errors instead of stopping at the first. - Generate report of files with issues. - Generate index of files containing each snippet. - Other fixes and tweaks. -* v1.2.0 - Allow log, issue report, and index to be selectively enabled. - Don't try to call non-method attributes to handle snippet tags. +- v1.0.0 - Initial pull request against the CDK Examples repo. +- v1.1.0 - Test against SDK team's examples repo and fix the problems found. + Continue processing after errors instead of stopping at the first. + Generate report of files with issues. + Generate index of files containing each snippet. + Other fixes and tweaks. +- v1.2.0 - Allow log, issue report, and index to be selectively enabled. + Don't try to call non-method attributes to handle snippet tags. diff --git a/.github/extract-snippets/extract-snippets.py b/.github/extract-snippets/extract-snippets.py index 21d908370af..688810adc1b 100644 --- a/.github/extract-snippets/extract-snippets.py +++ b/.github/extract-snippets/extract-snippets.py @@ -1,3 +1,5 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 # extract-snippets.py v1.2.0 6/24/2021 # Jerry Kindall, Amazon Web Services diff --git a/.github/extract-snippets/extract-snippets.sh b/.github/extract-snippets/extract-snippets.sh index 0af3e82200b..0b79798873a 100755 --- a/.github/extract-snippets/extract-snippets.sh +++ b/.github/extract-snippets/extract-snippets.sh @@ -1,3 +1,5 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 # extract-snippets.sh v1.1.0 # Jerry Kindall, Amazon Web Services diff --git a/.github/sd-cpp-linter/sd_review.py b/.github/sd-cpp-linter/sd_review.py index 572d39d14bf..e7792fa97a2 100755 --- a/.github/sd-cpp-linter/sd_review.py +++ b/.github/sd-cpp-linter/sd_review.py @@ -1,8 +1,7 @@ #!/usr/bin/env python3 - -# Original copyright (c) 2020 Peter Hill # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# SPDX - License - Identifier: Apache - 2.0 +# SPDX-License-Identifier: Apache-2.0 +# Original copyright (c) 2020 Peter Hill # The original source was part of the GitHub action Clang Tidy Review, https://github.com/ZedThree/clang-tidy-review. # This is an alteration of Clang Tidy Review which posts to annotations instead of pull-request diff --git a/.gitignore b/.gitignore index f1e24e594e7..d2f486eb147 100644 --- a/.gitignore +++ b/.gitignore @@ -21,4 +21,6 @@ venv xcuserdata # Ignore rust_dev_preview as it's no longer part of the project -rust_dev_preview \ No newline at end of file +rust_dev_preview +.vectors +.snippets diff --git a/.tools/README.md b/.tools/README.md index 1fc0537c2a6..7e2f516829b 100644 --- a/.tools/README.md +++ b/.tools/README.md @@ -38,6 +38,7 @@ SDK Code Examples tools team uses Python for our tools because of its cross-plat 17. Use requests for web calls, but prefer a native wrapper (like boto3 or pygithub) when available. - If you http/2, you might consider httpx. 18. Use subprocess for system calls, but prefer a native wrapper (like gitpython) when available. +19. When reading project files, use `encoding="utf-8-sig"`, as many `.cs` files have a BOM. ## Some PEPs you might want to know about: diff --git a/.tools/images/render-blurbs.py b/.tools/images/render-blurbs.py index b5494934a70..695120b38ab 100644 --- a/.tools/images/render-blurbs.py +++ b/.tools/images/render-blurbs.py @@ -1,3 +1,5 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 import os import jinja2 diff --git a/.tools/snippets/get_vendors.sh b/.tools/snippets/get_vendors.sh index 04124919781..8871d02ea21 100755 --- a/.tools/snippets/get_vendors.sh +++ b/.tools/snippets/get_vendors.sh @@ -1,5 +1,4 @@ #!/usr/bin/env bash - # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 diff --git a/.tools/snippets/sitter.py b/.tools/snippets/sitter.py index b1ff564e32a..3f4da47b1b9 100644 --- a/.tools/snippets/sitter.py +++ b/.tools/snippets/sitter.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 - # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 diff --git a/.tools/test/eventbridge_rule_with_sns_fanout/app.py b/.tools/test/eventbridge_rule_with_sns_fanout/app.py index 2f0b75eb5e3..ad7cfc7bc5a 100644 --- a/.tools/test/eventbridge_rule_with_sns_fanout/app.py +++ b/.tools/test/eventbridge_rule_with_sns_fanout/app.py @@ -1,4 +1,6 @@ #!/usr/bin/env python3 +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 import os diff --git a/.tools/test/public_ecr_repositories/app.py b/.tools/test/public_ecr_repositories/app.py index 0688359c02e..d653bfcf289 100644 --- a/.tools/test/public_ecr_repositories/app.py +++ b/.tools/test/public_ecr_repositories/app.py @@ -1,4 +1,6 @@ #!/usr/bin/env python3 +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 import os import aws_cdk as cdk diff --git a/.tools/test/public_ecr_repositories/public_ecr_repositories_stack/public_ecr_repositories_stack.py b/.tools/test/public_ecr_repositories/public_ecr_repositories_stack/public_ecr_repositories_stack.py index 016a51b9602..3cefdf80175 100644 --- a/.tools/test/public_ecr_repositories/public_ecr_repositories_stack/public_ecr_repositories_stack.py +++ b/.tools/test/public_ecr_repositories/public_ecr_repositories_stack/public_ecr_repositories_stack.py @@ -1,3 +1,5 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 import yaml from aws_cdk import Stack from aws_cdk import aws_ecr as ecr diff --git a/.tools/test/public_ecr_repositories/scripts/upload_image.sh b/.tools/test/public_ecr_repositories/scripts/upload_image.sh index 3487962485d..54df9b09bc6 100755 --- a/.tools/test/public_ecr_repositories/scripts/upload_image.sh +++ b/.tools/test/public_ecr_repositories/scripts/upload_image.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 # Set your AWS region AWS_REGION=us-east-1 diff --git a/.tools/test/sqs_lambda_to_batch_fargate/app.py b/.tools/test/sqs_lambda_to_batch_fargate/app.py index 4bbc9424745..f27783b89f9 100644 --- a/.tools/test/sqs_lambda_to_batch_fargate/app.py +++ b/.tools/test/sqs_lambda_to_batch_fargate/app.py @@ -1,4 +1,6 @@ #!/usr/bin/env python3 +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 import os diff --git a/.tools/test/sqs_lambda_to_batch_fargate/lambda/export_logs.py b/.tools/test/sqs_lambda_to_batch_fargate/lambda/export_logs.py index b4d1e0f646d..23246517984 100644 --- a/.tools/test/sqs_lambda_to_batch_fargate/lambda/export_logs.py +++ b/.tools/test/sqs_lambda_to_batch_fargate/lambda/export_logs.py @@ -1,3 +1,5 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 import json import logging import os diff --git a/.tools/verify_python.sh b/.tools/verify_python.sh index e6b03066d26..c5e03d35f17 100644 --- a/.tools/verify_python.sh +++ b/.tools/verify_python.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 MIN_VERSION=11 diff --git a/applications/feedback_sentiment_analyzer/cdk/bin/cdk.ts b/applications/feedback_sentiment_analyzer/cdk/bin/cdk.ts index f70061873dd..aa3f1254b88 100644 --- a/applications/feedback_sentiment_analyzer/cdk/bin/cdk.ts +++ b/applications/feedback_sentiment_analyzer/cdk/bin/cdk.ts @@ -1,4 +1,6 @@ #!/usr/bin/env node +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import "source-map-support/register"; import * as cdk from "aws-cdk-lib"; diff --git a/applications/feedback_sentiment_analyzer/cdk/jest.config.js b/applications/feedback_sentiment_analyzer/cdk/jest.config.js index 08263b8954a..2da421ba094 100644 --- a/applications/feedback_sentiment_analyzer/cdk/jest.config.js +++ b/applications/feedback_sentiment_analyzer/cdk/jest.config.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 module.exports = { testEnvironment: 'node', roots: ['/test'], diff --git a/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-api-models.ts b/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-api-models.ts index 7b91e317003..226c49f699b 100644 --- a/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-api-models.ts +++ b/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-api-models.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { JsonSchemaType, JsonSchemaVersion, diff --git a/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-auth.ts b/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-auth.ts index 1c89ed19a65..1296bc8c8f9 100644 --- a/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-auth.ts +++ b/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-auth.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { RemovalPolicy } from "aws-cdk-lib"; import { AccountRecovery, diff --git a/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-database.ts b/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-database.ts index 6cecd8c83eb..0099e560c84 100644 --- a/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-database.ts +++ b/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-database.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { AttributeType, Table } from "aws-cdk-lib/aws-dynamodb"; import { Construct } from "constructs"; diff --git a/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-env-lambda.ts b/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-env-lambda.ts index b144de3839e..249394ae78c 100644 --- a/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-env-lambda.ts +++ b/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-env-lambda.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { Construct } from "constructs"; import { readFileSync } from "fs"; import { join } from "path"; diff --git a/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-lambdas.ts b/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-lambdas.ts index 452b58518c8..eb7e30550ac 100644 --- a/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-lambdas.ts +++ b/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-lambdas.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { Construct } from "constructs"; import { Code, Function, FunctionProps } from "aws-cdk-lib/aws-lambda"; diff --git a/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-routes.ts b/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-routes.ts index f0d93bd0ba6..0e1e3db2b2b 100644 --- a/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-routes.ts +++ b/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-routes.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { AwsIntegration, ContentHandling, diff --git a/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-s3-website.ts b/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-s3-website.ts index 6d160d10f70..eedaefdf8cb 100644 --- a/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-s3-website.ts +++ b/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-s3-website.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { BundlingOutput, DockerImage, RemovalPolicy } from "aws-cdk-lib"; import { Distribution } from "aws-cdk-lib/aws-cloudfront"; import { diff --git a/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-state-machine.ts b/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-state-machine.ts index 70d13a34902..8b0cdc63143 100644 --- a/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-state-machine.ts +++ b/applications/feedback_sentiment_analyzer/cdk/lib/constructs/app-state-machine.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { Construct } from "constructs"; import { AppFunction } from "./app-lambdas"; import { DefinitionBody, StateMachine } from "aws-cdk-lib/aws-stepfunctions"; diff --git a/applications/feedback_sentiment_analyzer/cdk/lib/constructs/website-env-fn.js b/applications/feedback_sentiment_analyzer/cdk/lib/constructs/website-env-fn.js index c703d604c83..7ba17b7be42 100644 --- a/applications/feedback_sentiment_analyzer/cdk/lib/constructs/website-env-fn.js +++ b/applications/feedback_sentiment_analyzer/cdk/lib/constructs/website-env-fn.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 const { CognitoIdentityProviderClient, paginateListUserPoolClients, diff --git a/applications/feedback_sentiment_analyzer/cdk/lib/env.ts b/applications/feedback_sentiment_analyzer/cdk/lib/env.ts index 04ccc7852a0..e2bd04f5046 100644 --- a/applications/feedback_sentiment_analyzer/cdk/lib/env.ts +++ b/applications/feedback_sentiment_analyzer/cdk/lib/env.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 let APP_NAME: string, APP_EMAIL: string, APP_LANG: string; if (!process.env.FSA_NAME) { diff --git a/applications/feedback_sentiment_analyzer/cdk/lib/functions.ts b/applications/feedback_sentiment_analyzer/cdk/lib/functions.ts index a326fa69c02..b9526b56d08 100644 --- a/applications/feedback_sentiment_analyzer/cdk/lib/functions.ts +++ b/applications/feedback_sentiment_analyzer/cdk/lib/functions.ts @@ -1,12 +1,10 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -import {resolve} from "path"; -import {BundlingOutput, Duration} from "aws-cdk-lib"; -import {Code, Runtime} from "aws-cdk-lib/aws-lambda"; -import {AppFunctionConfig} from "./constructs/app-lambdas"; +import { resolve } from "path"; +import { BundlingOutput, Duration } from "aws-cdk-lib"; +import { Code, Runtime } from "aws-cdk-lib/aws-lambda"; +import { AppFunctionConfig } from "./constructs/app-lambdas"; const BASE_APP_FUNCTION: AppFunctionConfig = { name: "TestLambda", @@ -45,9 +43,9 @@ const BASE_APP_FUNCTION: AppFunctionConfig = { const EXAMPLE_LANG_FUNCTIONS: AppFunctionConfig[] = [ // The 'name' property must match the examples below in new examples. - {...BASE_APP_FUNCTION, name: "ExtractText"}, + { ...BASE_APP_FUNCTION, name: "ExtractText" }, // Override properties by including them after expanding the function object. - {...BASE_APP_FUNCTION, memorySize: 256, name: "AnalyzeSentiment"}, + { ...BASE_APP_FUNCTION, memorySize: 256, name: "AnalyzeSentiment" }, { ...BASE_APP_FUNCTION, codeAsset() { @@ -60,7 +58,7 @@ const EXAMPLE_LANG_FUNCTIONS: AppFunctionConfig[] = [ }, name: "TranslateText", }, - {...BASE_APP_FUNCTION, name: "SynthesizeAudio"}, + { ...BASE_APP_FUNCTION, name: "SynthesizeAudio" }, ]; const RUBY_ROOT = @@ -218,11 +216,12 @@ const DOTNET_FUNCTIONS = [ { ...BASE_APP_FUNCTION, name: "ExtractText", - handler: "FsaExtractText::FsaExtractText.ExtractTextFunction::FunctionHandler", + handler: + "FsaExtractText::FsaExtractText.ExtractTextFunction::FunctionHandler", runtime: Runtime.DOTNET_6, codeAsset() { const source = resolve( - "../../../dotnetv3/cross-service/FeedbackSentimentAnalyzer" + "../../../dotnetv3/cross-service/FeedbackSentimentAnalyzer" ); return Code.fromAsset(source, { bundling: { @@ -230,9 +229,9 @@ const DOTNET_FUNCTIONS = [ "/bin/sh", "-c", " dotnet tool install -g Amazon.Lambda.Tools" + - " && dotnet build" + - " && cd FsaExtractText" + - " && dotnet lambda package --output-package /asset-output/function.zip", + " && dotnet build" + + " && cd FsaExtractText" + + " && dotnet lambda package --output-package /asset-output/function.zip", ], image: Runtime.DOTNET_6.bundlingImage, user: "root", @@ -244,11 +243,12 @@ const DOTNET_FUNCTIONS = [ { ...BASE_APP_FUNCTION, name: "AnalyzeSentiment", - handler: "FsaAnalyzeSentiment::FsaAnalyzeSentiment.AnalyzeSentimentFunction::FunctionHandler", + handler: + "FsaAnalyzeSentiment::FsaAnalyzeSentiment.AnalyzeSentimentFunction::FunctionHandler", runtime: Runtime.DOTNET_6, codeAsset() { const source = resolve( - "../../../dotnetv3/cross-service/FeedbackSentimentAnalyzer" + "../../../dotnetv3/cross-service/FeedbackSentimentAnalyzer" ); return Code.fromAsset(source, { bundling: { @@ -256,9 +256,9 @@ const DOTNET_FUNCTIONS = [ "/bin/sh", "-c", " dotnet tool install -g Amazon.Lambda.Tools" + - " && dotnet build" + - " && cd FsaAnalyzeSentiment" + - " && dotnet lambda package --output-package /asset-output/function.zip", + " && dotnet build" + + " && cd FsaAnalyzeSentiment" + + " && dotnet lambda package --output-package /asset-output/function.zip", ], image: Runtime.DOTNET_6.bundlingImage, user: "root", @@ -270,11 +270,12 @@ const DOTNET_FUNCTIONS = [ { ...BASE_APP_FUNCTION, name: "TranslateText", - handler: "FsaTranslateText::FsaTranslateText.TranslateTextFunction::FunctionHandler", + handler: + "FsaTranslateText::FsaTranslateText.TranslateTextFunction::FunctionHandler", runtime: Runtime.DOTNET_6, codeAsset() { const source = resolve( - "../../../dotnetv3/cross-service/FeedbackSentimentAnalyzer" + "../../../dotnetv3/cross-service/FeedbackSentimentAnalyzer" ); return Code.fromAsset(source, { bundling: { @@ -282,9 +283,9 @@ const DOTNET_FUNCTIONS = [ "/bin/sh", "-c", " dotnet tool install -g Amazon.Lambda.Tools" + - " && dotnet build" + - " && cd FsaTranslateText" + - " && dotnet lambda package --output-package /asset-output/function.zip", + " && dotnet build" + + " && cd FsaTranslateText" + + " && dotnet lambda package --output-package /asset-output/function.zip", ], image: Runtime.DOTNET_6.bundlingImage, user: "root", @@ -296,11 +297,12 @@ const DOTNET_FUNCTIONS = [ { ...BASE_APP_FUNCTION, name: "SynthesizeAudio", - handler: "FsaSynthesizeAudio::FsaSynthesizeAudio.SynthesizeAudioFunction::FunctionHandler", + handler: + "FsaSynthesizeAudio::FsaSynthesizeAudio.SynthesizeAudioFunction::FunctionHandler", runtime: Runtime.DOTNET_6, codeAsset() { const source = resolve( - "../../../dotnetv3/cross-service/FeedbackSentimentAnalyzer" + "../../../dotnetv3/cross-service/FeedbackSentimentAnalyzer" ); return Code.fromAsset(source, { bundling: { @@ -308,9 +310,9 @@ const DOTNET_FUNCTIONS = [ "/bin/sh", "-c", " dotnet tool install -g Amazon.Lambda.Tools" + - " && dotnet build" + - " && cd FsaSynthesizeAudio" + - " && dotnet lambda package --output-package /asset-output/function.zip", + " && dotnet build" + + " && cd FsaSynthesizeAudio" + + " && dotnet lambda package --output-package /asset-output/function.zip", ], image: Runtime.DOTNET_6.bundlingImage, user: "root", diff --git a/applications/feedback_sentiment_analyzer/cdk/lib/stack.ts b/applications/feedback_sentiment_analyzer/cdk/lib/stack.ts index 8d6aeba2175..721d61bd411 100644 --- a/applications/feedback_sentiment_analyzer/cdk/lib/stack.ts +++ b/applications/feedback_sentiment_analyzer/cdk/lib/stack.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { Stack, CfnOutput, RemovalPolicy, Duration } from "aws-cdk-lib"; import { Construct } from "constructs"; diff --git a/applications/feedback_sentiment_analyzer/cdk/test/cdk.test.ts b/applications/feedback_sentiment_analyzer/cdk/test/cdk.test.ts index 1e6b29c8579..403903c12df 100644 --- a/applications/feedback_sentiment_analyzer/cdk/test/cdk.test.ts +++ b/applications/feedback_sentiment_analyzer/cdk/test/cdk.test.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // import * as cdk from 'aws-cdk-lib'; // import { Template } from 'aws-cdk-lib/assertions'; // import * as Cdk from '../lib/cdk-stack'; diff --git a/applications/feedback_sentiment_analyzer/client/src/api.ts b/applications/feedback_sentiment_analyzer/client/src/api.ts index 5a45b55982e..d4cdf52561b 100644 --- a/applications/feedback_sentiment_analyzer/client/src/api.ts +++ b/applications/feedback_sentiment_analyzer/client/src/api.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 export interface ApiConfig { token: string | null; } diff --git a/applications/feedback_sentiment_analyzer/client/src/env.ts b/applications/feedback_sentiment_analyzer/client/src/env.ts index d06c18e01e4..08ee23900fc 100644 --- a/applications/feedback_sentiment_analyzer/client/src/env.ts +++ b/applications/feedback_sentiment_analyzer/client/src/env.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 interface AppEnv extends Window { APP_ENV: { COGNITO_SIGN_IN_URL: string; diff --git a/applications/feedback_sentiment_analyzer/client/src/polyfills.ts b/applications/feedback_sentiment_analyzer/client/src/polyfills.ts index f677a95e359..bb582ea30c6 100644 --- a/applications/feedback_sentiment_analyzer/client/src/polyfills.ts +++ b/applications/feedback_sentiment_analyzer/client/src/polyfills.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 (window as any).global = window; export {} \ No newline at end of file diff --git a/applications/feedback_sentiment_analyzer/client/src/store.ts b/applications/feedback_sentiment_analyzer/client/src/store.ts index ca9ceb567bd..1418a7c7660 100644 --- a/applications/feedback_sentiment_analyzer/client/src/store.ts +++ b/applications/feedback_sentiment_analyzer/client/src/store.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { create } from "zustand"; import { decodeJwt } from "jose"; diff --git a/applications/feedback_sentiment_analyzer/client/vite.config.ts b/applications/feedback_sentiment_analyzer/client/vite.config.ts index 9cc50ead1c0..48abbc84a33 100644 --- a/applications/feedback_sentiment_analyzer/client/vite.config.ts +++ b/applications/feedback_sentiment_analyzer/client/vite.config.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; diff --git a/applications/photo-asset-manager/cdk/bin/app.ts b/applications/photo-asset-manager/cdk/bin/app.ts index d84050cb754..1518449e562 100644 --- a/applications/photo-asset-manager/cdk/bin/app.ts +++ b/applications/photo-asset-manager/cdk/bin/app.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { CloudFormationClient, Export, diff --git a/applications/photo-asset-manager/cdk/lib/backend/api.ts b/applications/photo-asset-manager/cdk/lib/backend/api.ts index 7a9f2474f8d..0781fe722ef 100644 --- a/applications/photo-asset-manager/cdk/lib/backend/api.ts +++ b/applications/photo-asset-manager/cdk/lib/backend/api.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Cognito User Pool * API Gateway diff --git a/applications/photo-asset-manager/cdk/lib/backend/api_models.ts b/applications/photo-asset-manager/cdk/lib/backend/api_models.ts index cd65180f763..edbb69d1345 100644 --- a/applications/photo-asset-manager/cdk/lib/backend/api_models.ts +++ b/applications/photo-asset-manager/cdk/lib/backend/api_models.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { JsonSchemaType, JsonSchemaVersion, diff --git a/applications/photo-asset-manager/cdk/lib/backend/auth.ts b/applications/photo-asset-manager/cdk/lib/backend/auth.ts index d8ffad47570..2338e7e9328 100644 --- a/applications/photo-asset-manager/cdk/lib/backend/auth.ts +++ b/applications/photo-asset-manager/cdk/lib/backend/auth.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { RemovalPolicy } from "aws-cdk-lib"; import { AccountRecovery, diff --git a/applications/photo-asset-manager/cdk/lib/backend/lambdas.ts b/applications/photo-asset-manager/cdk/lib/backend/lambdas.ts index f89537fbd7c..d0a56ebf7c4 100644 --- a/applications/photo-asset-manager/cdk/lib/backend/lambdas.ts +++ b/applications/photo-asset-manager/cdk/lib/backend/lambdas.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { Duration } from "aws-cdk-lib"; import { Architecture, Code, Function, Runtime } from "aws-cdk-lib/aws-lambda"; import { Construct } from "constructs"; diff --git a/applications/photo-asset-manager/cdk/lib/backend/resources.ts b/applications/photo-asset-manager/cdk/lib/backend/resources.ts index 412d5322838..d0ea9dfb4b6 100644 --- a/applications/photo-asset-manager/cdk/lib/backend/resources.ts +++ b/applications/photo-asset-manager/cdk/lib/backend/resources.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { Duration, RemovalPolicy } from "aws-cdk-lib"; import { AttributeType, Table } from "aws-cdk-lib/aws-dynamodb"; import { Bucket, HttpMethods, StorageClass } from "aws-cdk-lib/aws-s3"; diff --git a/applications/photo-asset-manager/cdk/lib/backend/stack.ts b/applications/photo-asset-manager/cdk/lib/backend/stack.ts index 44c9b9048a1..2e307cd93c9 100644 --- a/applications/photo-asset-manager/cdk/lib/backend/stack.ts +++ b/applications/photo-asset-manager/cdk/lib/backend/stack.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { CfnOutput, Stack, StackProps } from "aws-cdk-lib"; import { PolicyStatement } from "aws-cdk-lib/aws-iam"; import { LambdaDestination } from "aws-cdk-lib/aws-s3-notifications"; diff --git a/applications/photo-asset-manager/cdk/lib/backend/strategies.ts b/applications/photo-asset-manager/cdk/lib/backend/strategies.ts index c87757e6d3e..bbb5fcd7d51 100644 --- a/applications/photo-asset-manager/cdk/lib/backend/strategies.ts +++ b/applications/photo-asset-manager/cdk/lib/backend/strategies.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { BundlingOutput, Duration } from "aws-cdk-lib"; import { Architecture, Code, Runtime } from "aws-cdk-lib/aws-lambda"; import { resolve } from "path"; diff --git a/applications/photo-asset-manager/cdk/lib/common.ts b/applications/photo-asset-manager/cdk/lib/common.ts index c67a10f8489..d46e78f83ae 100644 --- a/applications/photo-asset-manager/cdk/lib/common.ts +++ b/applications/photo-asset-manager/cdk/lib/common.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { ok } from "assert"; import { resolve } from "path"; diff --git a/applications/photo-asset-manager/cdk/lib/frontend/asset-stack.ts b/applications/photo-asset-manager/cdk/lib/frontend/asset-stack.ts index 0c1e945403e..8db9437ca72 100644 --- a/applications/photo-asset-manager/cdk/lib/frontend/asset-stack.ts +++ b/applications/photo-asset-manager/cdk/lib/frontend/asset-stack.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { BundlingOutput, DockerImage, Stack, StackProps } from "aws-cdk-lib"; import { Bucket } from "aws-cdk-lib/aws-s3"; import { BucketDeployment, Source } from "aws-cdk-lib/aws-s3-deployment"; diff --git a/applications/photo-asset-manager/cdk/lib/frontend/infra-stack.ts b/applications/photo-asset-manager/cdk/lib/frontend/infra-stack.ts index dfe84092088..dfcc1a770c8 100644 --- a/applications/photo-asset-manager/cdk/lib/frontend/infra-stack.ts +++ b/applications/photo-asset-manager/cdk/lib/frontend/infra-stack.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { Arn, CfnOutput, RemovalPolicy, Stack } from "aws-cdk-lib"; import { CfnDistribution, diff --git a/applications/photo-asset-manager/cdk/rekognition_photo_analyzer/rekfunction.py b/applications/photo-asset-manager/cdk/rekognition_photo_analyzer/rekfunction.py index 2882cbe7904..aa2d0ae1349 100644 --- a/applications/photo-asset-manager/cdk/rekognition_photo_analyzer/rekfunction.py +++ b/applications/photo-asset-manager/cdk/rekognition_photo_analyzer/rekfunction.py @@ -1,3 +1,5 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 # This code is a sample only. Not for use in production. # # Author: Katreena Mullican diff --git a/applications/photo-asset-manager/elros-pam/src/pam-api.ts b/applications/photo-asset-manager/elros-pam/src/pam-api.ts index 25fb2254d42..7eb92dabb0c 100644 --- a/applications/photo-asset-manager/elros-pam/src/pam-api.ts +++ b/applications/photo-asset-manager/elros-pam/src/pam-api.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 export interface PamApiConfig { token: string | null; } diff --git a/applications/photo-asset-manager/elros-pam/src/polyfills.ts b/applications/photo-asset-manager/elros-pam/src/polyfills.ts index f677a95e359..bb582ea30c6 100644 --- a/applications/photo-asset-manager/elros-pam/src/polyfills.ts +++ b/applications/photo-asset-manager/elros-pam/src/polyfills.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 (window as any).global = window; export {} \ No newline at end of file diff --git a/applications/photo-asset-manager/elros-pam/src/store.ts b/applications/photo-asset-manager/elros-pam/src/store.ts index bac98ab5913..e4ee3efd3a0 100644 --- a/applications/photo-asset-manager/elros-pam/src/store.ts +++ b/applications/photo-asset-manager/elros-pam/src/store.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { create } from "zustand"; import { decodeJwt } from "jose"; import * as PAM from "./pam-api"; diff --git a/applications/photo-asset-manager/elros-pam/vite.config.ts b/applications/photo-asset-manager/elros-pam/vite.config.ts index 5a33944a9b4..f40b68055be 100644 --- a/applications/photo-asset-manager/elros-pam/vite.config.ts +++ b/applications/photo-asset-manager/elros-pam/vite.config.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' diff --git a/aws-cli/bash-linux/dynamodb/awsdocs_general.sh b/aws-cli/bash-linux/dynamodb/awsdocs_general.sh index 066b66eff27..976d9ce2ca8 100644 --- a/aws-cli/bash-linux/dynamodb/awsdocs_general.sh +++ b/aws-cli/bash-linux/dynamodb/awsdocs_general.sh @@ -1,12 +1,8 @@ #!/bin/bash -#bashsupport disable=BP5001 +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 -################################################################################ -## -## Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -## SPDX-License-Identifier: Apache-2.0 -## -################################################################################ +#bashsupport disable=BP5001 ################################################################################ ## diff --git a/aws-cli/bash-linux/dynamodb/dynamodb_operations.sh b/aws-cli/bash-linux/dynamodb/dynamodb_operations.sh index 7b01a7a0ec0..5963c66af9e 100644 --- a/aws-cli/bash-linux/dynamodb/dynamodb_operations.sh +++ b/aws-cli/bash-linux/dynamodb/dynamodb_operations.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 ############################################################################## # diff --git a/aws-cli/bash-linux/dynamodb/scenario_getting_started_movies.sh b/aws-cli/bash-linux/dynamodb/scenario_getting_started_movies.sh index e19a2e3f4cb..4b0cb19be1d 100755 --- a/aws-cli/bash-linux/dynamodb/scenario_getting_started_movies.sh +++ b/aws-cli/bash-linux/dynamodb/scenario_getting_started_movies.sh @@ -1,12 +1,9 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 # bashsupport disable=BP2002 - -############################################################################### -# -# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# SPDX-License-Identifier: Apache-2.0 -# -############################################################################### +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 ############################################################################### # diff --git a/aws-cli/bash-linux/dynamodb/tests/include_tests.sh b/aws-cli/bash-linux/dynamodb/tests/include_tests.sh index b86cd405a0a..b3c4cf6ba75 100644 --- a/aws-cli/bash-linux/dynamodb/tests/include_tests.sh +++ b/aws-cli/bash-linux/dynamodb/tests/include_tests.sh @@ -1,12 +1,8 @@ #!/bin/bash -#bashsupport disable=BP5001 +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 -################################################################################ -## -## Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -## SPDX-License-Identifier: Apache-2.0 -## -################################################################################ +#bashsupport disable=BP5001 ################################################################################ ## diff --git a/aws-cli/bash-linux/dynamodb/tests/test_dynamodb_examples.sh b/aws-cli/bash-linux/dynamodb/tests/test_dynamodb_examples.sh index 413e8478db1..6f3ab24ae1d 100755 --- a/aws-cli/bash-linux/dynamodb/tests/test_dynamodb_examples.sh +++ b/aws-cli/bash-linux/dynamodb/tests/test_dynamodb_examples.sh @@ -1,11 +1,6 @@ #!/bin/bash - -############################################################################### -# -# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# SPDX-License-Identifier: Apache-2.0 -# -############################################################################### +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 ############################################################################### # diff --git a/aws-cli/bash-linux/ec2/change-ec2-instance-type/awsdocs_general.sh b/aws-cli/bash-linux/ec2/change-ec2-instance-type/awsdocs_general.sh index 12330db1bd4..95df738b0db 100644 --- a/aws-cli/bash-linux/ec2/change-ec2-instance-type/awsdocs_general.sh +++ b/aws-cli/bash-linux/ec2/change-ec2-instance-type/awsdocs_general.sh @@ -1,15 +1,7 @@ #!/usr/bin/env bash -############################################################################### # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# This file is 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/. -# -# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -# CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. -############################################################################### +# SPDX-License-Identifier: Apache-2.0 + # # This script contains general-purpose functions that are used throughout # the AWS Command Line Interface (AWS CLI) code examples that are maintained diff --git a/aws-cli/bash-linux/ec2/change-ec2-instance-type/change_ec2_instance_type.sh b/aws-cli/bash-linux/ec2/change-ec2-instance-type/change_ec2_instance_type.sh index e15b90a7ccb..a4dcc850847 100644 --- a/aws-cli/bash-linux/ec2/change-ec2-instance-type/change_ec2_instance_type.sh +++ b/aws-cli/bash-linux/ec2/change-ec2-instance-type/change_ec2_instance_type.sh @@ -1,15 +1,7 @@ #!/usr/bin/env bash -############################################################################### # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# This file is 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/. -# -# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -# CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. -############################################################################### +# SPDX-License-Identifier: Apache-2.0 + #// snippet-start:[ec2.bash.change-instance-type.complete] ############################################################################### # diff --git a/aws-cli/bash-linux/ec2/change-ec2-instance-type/test_change_ec2_instance_type.sh b/aws-cli/bash-linux/ec2/change-ec2-instance-type/test_change_ec2_instance_type.sh index e66903238fe..b3fa53072fb 100644 --- a/aws-cli/bash-linux/ec2/change-ec2-instance-type/test_change_ec2_instance_type.sh +++ b/aws-cli/bash-linux/ec2/change-ec2-instance-type/test_change_ec2_instance_type.sh @@ -1,16 +1,7 @@ #!/usr/bin/env bash - -############################################################################### # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# This file is 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/. -# -# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -# CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. -############################################################################### +# SPDX-License-Identifier: Apache-2.0 + source ./awsdocs_general.sh source ./change_ec2_instance_type.sh diff --git a/aws-cli/bash-linux/iam/awsdocs_general.sh b/aws-cli/bash-linux/iam/awsdocs_general.sh index fa6d4cf6655..40955d094f2 100644 --- a/aws-cli/bash-linux/iam/awsdocs_general.sh +++ b/aws-cli/bash-linux/iam/awsdocs_general.sh @@ -1,12 +1,8 @@ #!/bin/bash -#bashsupport disable=BP5001 +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 -################################################################################ -## -## Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -## SPDX-License-Identifier: Apache-2.0 -## -################################################################################ +#bashsupport disable=BP5001 ################################################################################ ## diff --git a/aws-cli/bash-linux/iam/iam_create_user_assume_role_scenario.sh b/aws-cli/bash-linux/iam/iam_create_user_assume_role_scenario.sh index e541577973a..c115f9d1aba 100755 --- a/aws-cli/bash-linux/iam/iam_create_user_assume_role_scenario.sh +++ b/aws-cli/bash-linux/iam/iam_create_user_assume_role_scenario.sh @@ -1,12 +1,9 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 # bashsupport disable=BP2002 - -############################################################################### -# -# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# SPDX-License-Identifier: Apache-2.0 -# -############################################################################### +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 ############################################################################### # diff --git a/aws-cli/bash-linux/iam/iam_operations.sh b/aws-cli/bash-linux/iam/iam_operations.sh index 26e30c1c40f..664155229f8 100644 --- a/aws-cli/bash-linux/iam/iam_operations.sh +++ b/aws-cli/bash-linux/iam/iam_operations.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 ############################################################################## # diff --git a/aws-cli/bash-linux/iam/tests/include_tests.sh b/aws-cli/bash-linux/iam/tests/include_tests.sh index 6bc1aec82c4..1e535176c38 100644 --- a/aws-cli/bash-linux/iam/tests/include_tests.sh +++ b/aws-cli/bash-linux/iam/tests/include_tests.sh @@ -1,12 +1,8 @@ #!/bin/bash -#bashsupport disable=BP5001 +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 -################################################################################ -## -## Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -## SPDX-License-Identifier: Apache-2.0 -## -################################################################################ +#bashsupport disable=BP5001 ################################################################################ ## diff --git a/aws-cli/bash-linux/iam/tests/test_iam_examples.sh b/aws-cli/bash-linux/iam/tests/test_iam_examples.sh index 1f96feae023..0d8a75466aa 100755 --- a/aws-cli/bash-linux/iam/tests/test_iam_examples.sh +++ b/aws-cli/bash-linux/iam/tests/test_iam_examples.sh @@ -1,11 +1,6 @@ #!/bin/bash - -############################################################################### -# -# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# SPDX-License-Identifier: Apache-2.0 -# -############################################################################### +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 ############################################################################### # diff --git a/aws-cli/bash-linux/medical-imaging/awsdocs_general.sh b/aws-cli/bash-linux/medical-imaging/awsdocs_general.sh index 38fc949a9f3..4cf65980cc6 100644 --- a/aws-cli/bash-linux/medical-imaging/awsdocs_general.sh +++ b/aws-cli/bash-linux/medical-imaging/awsdocs_general.sh @@ -1,12 +1,8 @@ #!/bin/bash -#bashsupport disable=BP5001 +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 -################################################################################ -## -## Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -## SPDX-License-Identifier: Apache-2.0 -## -################################################################################ +#bashsupport disable=BP5001 ################################################################################ ## diff --git a/aws-cli/bash-linux/medical-imaging/medical_imaging_operations.sh b/aws-cli/bash-linux/medical-imaging/medical_imaging_operations.sh index 54aa780e379..09b6d1af360 100644 --- a/aws-cli/bash-linux/medical-imaging/medical_imaging_operations.sh +++ b/aws-cli/bash-linux/medical-imaging/medical_imaging_operations.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 ############################################################################## # diff --git a/aws-cli/bash-linux/medical-imaging/tests/include_tests.sh b/aws-cli/bash-linux/medical-imaging/tests/include_tests.sh index 6bc1aec82c4..1e535176c38 100644 --- a/aws-cli/bash-linux/medical-imaging/tests/include_tests.sh +++ b/aws-cli/bash-linux/medical-imaging/tests/include_tests.sh @@ -1,12 +1,8 @@ #!/bin/bash -#bashsupport disable=BP5001 +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 -################################################################################ -## -## Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -## SPDX-License-Identifier: Apache-2.0 -## -################################################################################ +#bashsupport disable=BP5001 ################################################################################ ## diff --git a/aws-cli/bash-linux/medical-imaging/tests/test_medical_imaging_examples.sh b/aws-cli/bash-linux/medical-imaging/tests/test_medical_imaging_examples.sh index 21e8f07655b..0cae9df8a37 100755 --- a/aws-cli/bash-linux/medical-imaging/tests/test_medical_imaging_examples.sh +++ b/aws-cli/bash-linux/medical-imaging/tests/test_medical_imaging_examples.sh @@ -1,11 +1,6 @@ #!/bin/bash - -############################################################################### -# -# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# SPDX-License-Identifier: Apache-2.0 -# -############################################################################### +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 ############################################################################### # diff --git a/aws-cli/bash-linux/run_tests.sh b/aws-cli/bash-linux/run_tests.sh index 6541a66d4d8..6eca444ab2d 100755 --- a/aws-cli/bash-linux/run_tests.sh +++ b/aws-cli/bash-linux/run_tests.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 base_dir=$(pwd) diff --git a/aws-cli/bash-linux/s3/bucket-lifecycle-operations/awsdocs_general.sh b/aws-cli/bash-linux/s3/bucket-lifecycle-operations/awsdocs_general.sh index 5eddab51272..587ae3d5048 100644 --- a/aws-cli/bash-linux/s3/bucket-lifecycle-operations/awsdocs_general.sh +++ b/aws-cli/bash-linux/s3/bucket-lifecycle-operations/awsdocs_general.sh @@ -1,12 +1,8 @@ #!/bin/bash -#bashsupport disable=BP5001 +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 -################################################################################ -## -## Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -## SPDX-License-Identifier: Apache-2.0 -## -################################################################################ +#bashsupport disable=BP5001 ################################################################################ ## diff --git a/aws-cli/bash-linux/s3/bucket-lifecycle-operations/bucket_operations.sh b/aws-cli/bash-linux/s3/bucket-lifecycle-operations/bucket_operations.sh index 7135964d34b..7d13d89c7a2 100644 --- a/aws-cli/bash-linux/s3/bucket-lifecycle-operations/bucket_operations.sh +++ b/aws-cli/bash-linux/s3/bucket-lifecycle-operations/bucket_operations.sh @@ -1,13 +1,8 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 # bashsupport disable=BP5001 -############################################################################### -# -# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# SPDX-License-Identifier: Apache-2.0 -# -############################################################################### - ############################################################################### # # Before running this AWS CLI example, set up your development environment, including your credentials. diff --git a/aws-cli/bash-linux/s3/bucket-lifecycle-operations/test_bucket_operations.sh b/aws-cli/bash-linux/s3/bucket-lifecycle-operations/test_bucket_operations.sh index 6d7c3bf609a..3e233841867 100755 --- a/aws-cli/bash-linux/s3/bucket-lifecycle-operations/test_bucket_operations.sh +++ b/aws-cli/bash-linux/s3/bucket-lifecycle-operations/test_bucket_operations.sh @@ -1,11 +1,6 @@ #!/bin/bash - -############################################################################### -# -# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# SPDX-License-Identifier: Apache-2.0 -# -############################################################################### +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 ############################################################################### # diff --git a/aws-cli/bash-linux/s3/s3_getting_started.sh b/aws-cli/bash-linux/s3/s3_getting_started.sh index 4c979fa79e6..b1305803f65 100755 --- a/aws-cli/bash-linux/s3/s3_getting_started.sh +++ b/aws-cli/bash-linux/s3/s3_getting_started.sh @@ -1,11 +1,6 @@ #!/bin/bash - -############################################################################### -# -# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# SPDX-License-Identifier: Apache-2.0 -# -############################################################################### +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 ############################################################################### # diff --git a/cpp/build_all_examples.sh b/cpp/build_all_examples.sh index 4f25f5db2ec..560aa13725a 100755 --- a/cpp/build_all_examples.sh +++ b/cpp/build_all_examples.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 # Build the AWS example code for C++ . diff --git a/cpp/example_code/acm/acm_basic_operations.cpp b/cpp/example_code/acm/acm_basic_operations.cpp index 95f0c85a419..fd4cf91a2bd 100644 --- a/cpp/example_code/acm/acm_basic_operations.cpp +++ b/cpp/example_code/acm/acm_basic_operations.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 /* //////////////////////////////////////////////////////////////////////////// * Purpose: diff --git a/cpp/example_code/acm/include/awsdoc/acm/acm_examples.h b/cpp/example_code/acm/include/awsdoc/acm/acm_examples.h index cec1f34eee6..eb5c0bc4cd1 100644 --- a/cpp/example_code/acm/include/awsdoc/acm/acm_examples.h +++ b/cpp/example_code/acm/include/awsdoc/acm/acm_examples.h @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 #pragma once diff --git a/cpp/example_code/acm/tests/test_acm_basic_operations.cpp b/cpp/example_code/acm/tests/test_acm_basic_operations.cpp index abd60a10941..67529eb9a22 100644 --- a/cpp/example_code/acm/tests/test_acm_basic_operations.cpp +++ b/cpp/example_code/acm/tests/test_acm_basic_operations.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/aurora/aurora_samples.h b/cpp/example_code/aurora/aurora_samples.h index 57086f5619f..179d3533d4d 100644 --- a/cpp/example_code/aurora/aurora_samples.h +++ b/cpp/example_code/aurora/aurora_samples.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef RDS_EXAMPLES_AURORA_SAMPLES_H diff --git a/cpp/example_code/aurora/getting_started_with_db_clusters.cpp b/cpp/example_code/aurora/getting_started_with_db_clusters.cpp index 7aee4246cb5..2bd6aefa4f4 100644 --- a/cpp/example_code/aurora/getting_started_with_db_clusters.cpp +++ b/cpp/example_code/aurora/getting_started_with_db_clusters.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. diff --git a/cpp/example_code/aurora/hello_aurora/hello_aurora.cpp b/cpp/example_code/aurora/hello_aurora/hello_aurora.cpp index 208c91672fa..c5d37a701ff 100644 --- a/cpp/example_code/aurora/hello_aurora/hello_aurora.cpp +++ b/cpp/example_code/aurora/hello_aurora/hello_aurora.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/aurora/tests/aurora_gtests.cpp b/cpp/example_code/aurora/tests/aurora_gtests.cpp index 39e6d7eb75e..b0792276aa8 100644 --- a/cpp/example_code/aurora/tests/aurora_gtests.cpp +++ b/cpp/example_code/aurora/tests/aurora_gtests.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "aurora_gtests.h" #include diff --git a/cpp/example_code/aurora/tests/aurora_gtests.h b/cpp/example_code/aurora/tests/aurora_gtests.h index 975dca4e876..bf1fb1a5221 100644 --- a/cpp/example_code/aurora/tests/aurora_gtests.h +++ b/cpp/example_code/aurora/tests/aurora_gtests.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef RDS_EXAMPLES_AURORA_GTESTS_H diff --git a/cpp/example_code/aurora/tests/gtest_getting_started_with_db_clusters.cpp b/cpp/example_code/aurora/tests/gtest_getting_started_with_db_clusters.cpp index 340a2826bb2..80d2938ddf1 100644 --- a/cpp/example_code/aurora/tests/gtest_getting_started_with_db_clusters.cpp +++ b/cpp/example_code/aurora/tests/gtest_getting_started_with_db_clusters.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/aurora/tests/test_main.cpp b/cpp/example_code/aurora/tests/test_main.cpp index 4d36ef85dcb..26a4a87d947 100644 --- a/cpp/example_code/aurora/tests/test_main.cpp +++ b/cpp/example_code/aurora/tests/test_main.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "gtest/gtest.h" diff --git a/cpp/example_code/autoscaling/autoscaling_samples.h b/cpp/example_code/autoscaling/autoscaling_samples.h index 260f4a7d87b..e85d35c24b3 100644 --- a/cpp/example_code/autoscaling/autoscaling_samples.h +++ b/cpp/example_code/autoscaling/autoscaling_samples.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef AUTO_SCALING_EXAMPLES_AUTOSCALING_SAMPLES_H diff --git a/cpp/example_code/autoscaling/groups_and_instances_scenario.cpp b/cpp/example_code/autoscaling/groups_and_instances_scenario.cpp index c008f68a592..c5e5755f559 100644 --- a/cpp/example_code/autoscaling/groups_and_instances_scenario.cpp +++ b/cpp/example_code/autoscaling/groups_and_instances_scenario.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. diff --git a/cpp/example_code/autoscaling/hello_autoscaling/hello_autoscaling.cpp b/cpp/example_code/autoscaling/hello_autoscaling/hello_autoscaling.cpp index c8d12bf3a19..df4964a6527 100644 --- a/cpp/example_code/autoscaling/hello_autoscaling/hello_autoscaling.cpp +++ b/cpp/example_code/autoscaling/hello_autoscaling/hello_autoscaling.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/autoscaling/tests/autoscaling_gtests.cpp b/cpp/example_code/autoscaling/tests/autoscaling_gtests.cpp index df6edfbd14c..b02c597d257 100644 --- a/cpp/example_code/autoscaling/tests/autoscaling_gtests.cpp +++ b/cpp/example_code/autoscaling/tests/autoscaling_gtests.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "autoscaling_gtests.h" #include diff --git a/cpp/example_code/autoscaling/tests/autoscaling_gtests.h b/cpp/example_code/autoscaling/tests/autoscaling_gtests.h index 5dbb0c70a1a..c944707b872 100644 --- a/cpp/example_code/autoscaling/tests/autoscaling_gtests.h +++ b/cpp/example_code/autoscaling/tests/autoscaling_gtests.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef AUTOSCALING_EXAMPLES_AUTOSCALING_GTESTS_H diff --git a/cpp/example_code/autoscaling/tests/gtest_groups_and_instances_scenario.cpp b/cpp/example_code/autoscaling/tests/gtest_groups_and_instances_scenario.cpp index 01ebbd16d56..baaed3ef9e3 100644 --- a/cpp/example_code/autoscaling/tests/gtest_groups_and_instances_scenario.cpp +++ b/cpp/example_code/autoscaling/tests/gtest_groups_and_instances_scenario.cpp @@ -1,7 +1,6 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/autoscaling/tests/test_main.cpp b/cpp/example_code/autoscaling/tests/test_main.cpp index 00ed3e2b055..656f92cb221 100644 --- a/cpp/example_code/autoscaling/tests/test_main.cpp +++ b/cpp/example_code/autoscaling/tests/test_main.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "gtest/gtest.h" diff --git a/cpp/example_code/cloudtrail/create_trail.cpp b/cpp/example_code/cloudtrail/create_trail.cpp index b115aaac054..62fa135a2cf 100644 --- a/cpp/example_code/cloudtrail/create_trail.cpp +++ b/cpp/example_code/cloudtrail/create_trail.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[create_trail.cpp demonstrates how to create an AWS CloudTrail resource using command-line input.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS CloudTrail] -//snippet-service:[cloudtrail] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/cloudtrail/delete_trail.cpp b/cpp/example_code/cloudtrail/delete_trail.cpp index 37f60d214ee..f62673d49bd 100644 --- a/cpp/example_code/cloudtrail/delete_trail.cpp +++ b/cpp/example_code/cloudtrail/delete_trail.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[delete_trail.cpp demonstrates how to delete an AWS CloudTrail resource using command-line input.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS CloudTrail] -//snippet-service:[cloudtrail] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/cloudtrail/describe_trails.cpp b/cpp/example_code/cloudtrail/describe_trails.cpp index d580a7fe3aa..5dac5f515cf 100644 --- a/cpp/example_code/cloudtrail/describe_trails.cpp +++ b/cpp/example_code/cloudtrail/describe_trails.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[describe_trails.cpp demonstrates how to retrieve information about an AWS CloudTrail resource.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS CloudTrail] -//snippet-service:[cloudtrail] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/cloudtrail/lookup_events.cpp b/cpp/example_code/cloudtrail/lookup_events.cpp index 071efab6055..090d37f6553 100644 --- a/cpp/example_code/cloudtrail/lookup_events.cpp +++ b/cpp/example_code/cloudtrail/lookup_events.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[lookup_events.cpp demonstrates how to retrieve information about an AWS CloudTrail event.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS CloudTrail] -//snippet-service:[cloudtrail] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/cloudwatch-logs/delete_subscription_filter.cpp b/cpp/example_code/cloudwatch-logs/delete_subscription_filter.cpp index aa4d21f5542..a36d586f109 100644 --- a/cpp/example_code/cloudwatch-logs/delete_subscription_filter.cpp +++ b/cpp/example_code/cloudwatch-logs/delete_subscription_filter.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 /* //////////////////////////////////////////////////////////////////////////// * Purpose: delete_subscription_filter.cpp demonstrates how to delete an Amazon CloudWatch Logs subscription filter. @@ -14,14 +14,14 @@ * Outputs: * The subscription filter is deleted. * ///////////////////////////////////////////////////////////////////////// */ -//snippet-start:[cwl.cpp.delete_subscription_filter.inc] +// snippet-start:[cwl.cpp.delete_subscription_filter.inc] #include #include #include #include #include -//snippet-end:[cwl.cpp.delete_subscription_filter.inc] +// snippet-end:[cwl.cpp.delete_subscription_filter.inc] /** * Delete a CloudWatch Logs subscription filter based on command-line input @@ -40,7 +40,7 @@ int main(int argc, char** argv) Aws::SDKOptions options; Aws::InitAPI(options); { - //snippet-start:[cwl.cpp.delete_subscription_filter] + // snippet-start:[cwl.cpp.delete_subscription_filter] Aws::CloudWatchLogs::CloudWatchLogsClient cwl; Aws::CloudWatchLogs::Model::DeleteSubscriptionFilterRequest request; @@ -56,7 +56,7 @@ int main(int argc, char** argv) std::cout << "Successfully deleted CloudWatch logs subscription " << "filter " << filter_name << std::endl; } - //snippet-end:[cwl.cpp.delete_subscription_filter] + // snippet-end:[cwl.cpp.delete_subscription_filter] } Aws::ShutdownAPI(options); diff --git a/cpp/example_code/cloudwatch-logs/describe_subscription_filters.cpp b/cpp/example_code/cloudwatch-logs/describe_subscription_filters.cpp index f5dc245c377..5f4c5c546d8 100644 --- a/cpp/example_code/cloudwatch-logs/describe_subscription_filters.cpp +++ b/cpp/example_code/cloudwatch-logs/describe_subscription_filters.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 /* //////////////////////////////////////////////////////////////////////////// * Purpose: describe_subscription_filters.cpp demonstrates how to list the subscription filters for an Amazon CloudWatch Logs resource. * @@ -12,7 +12,7 @@ * Outputs: * This subscription filters are described. * ///////////////////////////////////////////////////////////////////////// */ -//snippet-start:[cwl.cpp.describe_subscription_filters.inc] +// snippet-start:[cwl.cpp.describe_subscription_filters.inc] #include #include #include @@ -20,7 +20,7 @@ #include #include #include -//snippet-end:[cwl.cpp.describe_subscription_filters.inc] +// snippet-end:[cwl.cpp.describe_subscription_filters.inc] /** * List CloudWatch subscription filters associated with a log group @@ -38,7 +38,7 @@ int main(int argc, char** argv) Aws::SDKOptions options; Aws::InitAPI(options); { - //snippet-start:[cwl.cpp.describe_subscription_filters] + // snippet-start:[cwl.cpp.describe_subscription_filters] Aws::CloudWatchLogs::CloudWatchLogsClient cwl; Aws::CloudWatchLogs::Model::DescribeSubscriptionFiltersRequest request; request.SetLogGroupName(log_group); @@ -75,7 +75,7 @@ int main(int argc, char** argv) request.SetNextToken(next_token); done = next_token.empty(); } - //snippet-end:[cwl.cpp.describe_subscription_filters] + // snippet-end:[cwl.cpp.describe_subscription_filters] } Aws::ShutdownAPI(options); diff --git a/cpp/example_code/cloudwatch-logs/put_subscription_filter.cpp b/cpp/example_code/cloudwatch-logs/put_subscription_filter.cpp index f931bad7aed..a3d45359307 100644 --- a/cpp/example_code/cloudwatch-logs/put_subscription_filter.cpp +++ b/cpp/example_code/cloudwatch-logs/put_subscription_filter.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 /* //////////////////////////////////////////////////////////////////////////// * Purpose: put_subscription_filter.cpp demonstrates how to create an Amazon Cloudwatch Logs subscription filter. @@ -13,13 +13,13 @@ * Outputs: * A subscription filter is created. * ///////////////////////////////////////////////////////////////////////// */ -//snippet-start:[cwl.cpp.put_subscription_filter.inc] +// snippet-start:[cwl.cpp.put_subscription_filter.inc] #include #include #include #include #include -//snippet-end:[cwl.cpp.put_subscription_filter.inc] +// snippet-end:[cwl.cpp.put_subscription_filter.inc] /** * Create a CloudWatch Logs subscription filter based on command-line input */ @@ -41,7 +41,7 @@ int main(int argc, char** argv) Aws::String log_group(argv[3]); Aws::String dest_arn(argv[4]); - //snippet-start:[cwl.cpp.put_subscription_filter] + // snippet-start:[cwl.cpp.put_subscription_filter] Aws::CloudWatchLogs::CloudWatchLogsClient cwl; Aws::CloudWatchLogs::Model::PutSubscriptionFilterRequest request; request.SetFilterName(filter_name); @@ -60,7 +60,7 @@ int main(int argc, char** argv) std::cout << "Successfully created CloudWatch logs subscription " << "filter " << filter_name << std::endl; } - //snippet-end:[cwl.cpp.put_subscription_filter] + // snippet-end:[cwl.cpp.put_subscription_filter] } Aws::ShutdownAPI(options); diff --git a/cpp/example_code/cloudwatch/delete_alarm.cpp b/cpp/example_code/cloudwatch/delete_alarm.cpp index 6cb37dae521..7f4f6f46a00 100644 --- a/cpp/example_code/cloudwatch/delete_alarm.cpp +++ b/cpp/example_code/cloudwatch/delete_alarm.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 /* /* //////////////////////////////////////////////////////////////////////////// * Purpose: delete_alarm.cpp demonstrates how to delete an Amazon CloudWatch alarm. @@ -12,12 +12,12 @@ * * ///////////////////////////////////////////////////////////////////////// */ -//snippet-start:[cw.cpp.delete_alarm.inc] +// snippet-start:[cw.cpp.delete_alarm.inc] #include #include #include #include -//snippet-end:[cw.cpp.delete_alarm.inc] +// snippet-end:[cw.cpp.delete_alarm.inc] /** * Deletes a CloudWatch alarm diff --git a/cpp/example_code/cloudwatch/describe_alarms.cpp b/cpp/example_code/cloudwatch/describe_alarms.cpp index 2008c548ae2..fc4caa2c8db 100644 --- a/cpp/example_code/cloudwatch/describe_alarms.cpp +++ b/cpp/example_code/cloudwatch/describe_alarms.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 /* /* //////////////////////////////////////////////////////////////////////////// @@ -10,14 +10,14 @@ * Outputs: * The name, Amazon Resource Name (ARN), description and date last updated of your alarms. * ///////////////////////////////////////////////////////////////////////// */ -//snippet-start:[cw.cpp.describe_alarms.inc] +// snippet-start:[cw.cpp.describe_alarms.inc] #include #include #include #include #include #include -//snippet-end:[cw.cpp.describe_alarms.inc] +// snippet-end:[cw.cpp.describe_alarms.inc] static const char* SIMPLE_DATE_FORMAT_STR = "%Y-%m-%d"; diff --git a/cpp/example_code/cloudwatch/disable_alarm_actions.cpp b/cpp/example_code/cloudwatch/disable_alarm_actions.cpp index 27d64b3a04b..98582a5f493 100644 --- a/cpp/example_code/cloudwatch/disable_alarm_actions.cpp +++ b/cpp/example_code/cloudwatch/disable_alarm_actions.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 /* */ @@ -15,12 +15,12 @@ * Outputs: * The alarm is disabled. * ///////////////////////////////////////////////////////////////////////// */ -//snippet-start:[cw.cpp.disable_alarm_actions.inc] +// snippet-start:[cw.cpp.disable_alarm_actions.inc] #include #include #include #include -//snippet-end:[cw.cpp.disable_alarm_actions.inc] +// snippet-end:[cw.cpp.disable_alarm_actions.inc] /** * Disable actions on a CloudWatch alarm based on command-line input @@ -40,7 +40,7 @@ int main(int argc, char** argv) { Aws::String alarm_name(argv[1]); - //snippet-start:[cw.cpp.disable_alarm_actions.code] + // snippet-start:[cw.cpp.disable_alarm_actions.code] Aws::CloudWatch::CloudWatchClient cw; Aws::CloudWatch::Model::DisableAlarmActionsRequest disableAlarmActionsRequest; @@ -58,7 +58,7 @@ int main(int argc, char** argv) std::cout << "Successfully disabled actions for alarm " << alarm_name << std::endl; } - //snippet-end:[cw.cpp.disable_alarm_actions.code] + // snippet-end:[cw.cpp.disable_alarm_actions.code] } Aws::ShutdownAPI(options); return 0; diff --git a/cpp/example_code/cloudwatch/enable_alarm_actions.cpp b/cpp/example_code/cloudwatch/enable_alarm_actions.cpp index 35bca3cb7e6..8f63a94e9e2 100644 --- a/cpp/example_code/cloudwatch/enable_alarm_actions.cpp +++ b/cpp/example_code/cloudwatch/enable_alarm_actions.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 /* */ @@ -17,13 +17,13 @@ * Outputs: * The metric alarm is enabled. * ///////////////////////////////////////////////////////////////////////// */ -//snippet-start:[cw.cpp.enable_alarm_actions.inc] +// snippet-start:[cw.cpp.enable_alarm_actions.inc] #include #include #include #include #include -//snippet-end:[cw.cpp.enable_alarm_actions.inc] +// snippet-end:[cw.cpp.enable_alarm_actions.inc] void CreateAlarmAndEnableActions( const Aws::String& alarm_name, const Aws::String& instanceId, diff --git a/cpp/example_code/cloudwatch/list_metrics.cpp b/cpp/example_code/cloudwatch/list_metrics.cpp index a1c00c808b6..dcb948490c8 100644 --- a/cpp/example_code/cloudwatch/list_metrics.cpp +++ b/cpp/example_code/cloudwatch/list_metrics.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 /* /* //////////////////////////////////////////////////////////////////////////// @@ -15,14 +15,14 @@ * Outputs: * A list of metrics. * ///////////////////////////////////////////////////////////////////////// */ -//snippet-start:[cw.cpp.list_metrics.inc] +// snippet-start:[cw.cpp.list_metrics.inc] #include #include #include #include #include #include -//snippet-end:[cw.cpp.list_metrics.inc] +// snippet-end:[cw.cpp.list_metrics.inc] static const char* SIMPLE_DATE_FORMAT_STR = "%Y-%m-%d"; diff --git a/cpp/example_code/cloudwatch/put_metric_alarm.cpp b/cpp/example_code/cloudwatch/put_metric_alarm.cpp index 31b585cb932..dd81d7b83a6 100644 --- a/cpp/example_code/cloudwatch/put_metric_alarm.cpp +++ b/cpp/example_code/cloudwatch/put_metric_alarm.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 /* //////////////////////////////////////////////////////////////////////////// * Purpose: put_metric_alarm.cpp demonstrates how to attach an Amazon CloudWatch metrics alarm. @@ -15,12 +15,12 @@ * Output: * The alarm is added to the metric. * ///////////////////////////////////////////////////////////////////////// */ -//snippet-start:[cw.cpp.put_metric_alarm.inc] +// snippet-start:[cw.cpp.put_metric_alarm.inc] #include #include #include #include -//snippet-end:[cw.cpp.put_metric_alarm.inc] +// snippet-end:[cw.cpp.put_metric_alarm.inc] /** * Adds a CloudWatch alarm to an instance based on CPU utilization. diff --git a/cpp/example_code/cloudwatch/put_metric_data.cpp b/cpp/example_code/cloudwatch/put_metric_data.cpp index d29f291d617..54f6748d6a9 100644 --- a/cpp/example_code/cloudwatch/put_metric_data.cpp +++ b/cpp/example_code/cloudwatch/put_metric_data.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 /* //////////////////////////////////////////////////////////////////////////// * Purpose: put_metric_data.cpp demonstrates how to submit Amazon CloudWatch metric data. @@ -11,12 +11,12 @@ * - value_stream: The CloudWatch metric stream (entered as the second argument in the command line). * * ///////////////////////////////////////////////////////////////////////// */ -//snippet-start:[cw.cpp.put_metric_data.inc] +// snippet-start:[cw.cpp.put_metric_data.inc] #include #include #include #include -//snippet-end:[cw.cpp.put_metric_data.inc] +// snippet-end:[cw.cpp.put_metric_data.inc] /** * Attempts to put a sample metric data point with value based on command line input diff --git a/cpp/example_code/codebuild/build_project.cpp b/cpp/example_code/codebuild/build_project.cpp index 1ea735b0a12..39435e6826e 100644 --- a/cpp/example_code/codebuild/build_project.cpp +++ b/cpp/example_code/codebuild/build_project.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[build_project.cpp demonstrates how to start building a project with AWS CodeBuild.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS CodeBuild] -//snippet-service:[codebuild] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/codebuild/list_builds.cpp b/cpp/example_code/codebuild/list_builds.cpp index b1d5d97ed19..64e7d276b73 100644 --- a/cpp/example_code/codebuild/list_builds.cpp +++ b/cpp/example_code/codebuild/list_builds.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[list_builds.cpp demonstrates how to retrieve and list build information using AWS CodeBuild.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS CodeBuild] -//snippet-service:[codebuild] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/codebuild/list_projects.cpp b/cpp/example_code/codebuild/list_projects.cpp index 05c6c3f7712..2ad56735aa6 100644 --- a/cpp/example_code/codebuild/list_projects.cpp +++ b/cpp/example_code/codebuild/list_projects.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[list_projects.cpp demonstrates how to list AWS CodeBuild projects.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS CodeBuild] -//snippet-service:[codebuild] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/codecommit/create_pull_request.cpp b/cpp/example_code/codecommit/create_pull_request.cpp index 8635855706c..43909230d1e 100644 --- a/cpp/example_code/codecommit/create_pull_request.cpp +++ b/cpp/example_code/codecommit/create_pull_request.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[create_pull_request.cpp demonstrates how to create a pull request with AWS CodeCommit.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS CodeCommit] -//snippet-service:[codecommit] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/codecommit/create_repository.cpp b/cpp/example_code/codecommit/create_repository.cpp index 20f8c5920e3..00cd155a746 100644 --- a/cpp/example_code/codecommit/create_repository.cpp +++ b/cpp/example_code/codecommit/create_repository.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[create_repository.cpp demonstrates how to create an AWS CodeCommit repository.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS CodeCommit] -//snippet-service:[codecommit] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/codecommit/delete_branch.cpp b/cpp/example_code/codecommit/delete_branch.cpp index 52d9edd70c3..73abd889e86 100644 --- a/cpp/example_code/codecommit/delete_branch.cpp +++ b/cpp/example_code/codecommit/delete_branch.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[delete_branch.cpp demonstrates how to delete a repository branch using AWS CodeCommit.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS CodeCommit] -//snippet-service:[codecommit] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/codecommit/delete_repository.cpp b/cpp/example_code/codecommit/delete_repository.cpp index 823c7e6ac51..814d1a3b270 100644 --- a/cpp/example_code/codecommit/delete_repository.cpp +++ b/cpp/example_code/codecommit/delete_repository.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[delete_repository.cpp demonstrates how to delete an AWS CodeCommit repository.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS CodeCommit] -//snippet-service:[codecommit] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/codecommit/list_branches.cpp b/cpp/example_code/codecommit/list_branches.cpp index 3a1bff32933..666bdf71486 100644 --- a/cpp/example_code/codecommit/list_branches.cpp +++ b/cpp/example_code/codecommit/list_branches.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[list_branches.cpp demonstrates how to list the branches of an AWS CodeCommit repository.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS CodeCommit] -//snippet-service:[codecommit] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/codecommit/list_pull_requests.cpp b/cpp/example_code/codecommit/list_pull_requests.cpp index 834d0eddb13..c4034098eb7 100644 --- a/cpp/example_code/codecommit/list_pull_requests.cpp +++ b/cpp/example_code/codecommit/list_pull_requests.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[list_pull_requests.cpp demonstrates how to list the pull requests for an AWS CodeCommit repository.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS CodeCommit] -//snippet-service:[codecommit] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/codecommit/update_pull_request.cpp b/cpp/example_code/codecommit/update_pull_request.cpp index 4d996b8deba..5ddbdfdde27 100644 --- a/cpp/example_code/codecommit/update_pull_request.cpp +++ b/cpp/example_code/codecommit/update_pull_request.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[update_pull_request.cpp demonstrates how to update an AWS CodeCommit pull request.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS CodeCommit] -//snippet-service:[codecommit] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/codecommit/update_repository.cpp b/cpp/example_code/codecommit/update_repository.cpp index 029e97cc069..2322a872b8e 100644 --- a/cpp/example_code/codecommit/update_repository.cpp +++ b/cpp/example_code/codecommit/update_repository.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[update_repository.cpp demonstrates how to update information about an AWS CodeCommit repository.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS CodeCommit] -//snippet-service:[codecommit] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/cognito/cognito_samples.h b/cpp/example_code/cognito/cognito_samples.h index 6b61321f10b..489d637390c 100644 --- a/cpp/example_code/cognito/cognito_samples.h +++ b/cpp/example_code/cognito/cognito_samples.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once diff --git a/cpp/example_code/cognito/getting_started_with_user_pools.cpp b/cpp/example_code/cognito/getting_started_with_user_pools.cpp index c027123090d..24b17bbe4b2 100644 --- a/cpp/example_code/cognito/getting_started_with_user_pools.cpp +++ b/cpp/example_code/cognito/getting_started_with_user_pools.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/cognito/hello_cognito/hello_cognito.cpp b/cpp/example_code/cognito/hello_cognito/hello_cognito.cpp index 5d25d55b127..d8d30459e1a 100644 --- a/cpp/example_code/cognito/hello_cognito/hello_cognito.cpp +++ b/cpp/example_code/cognito/hello_cognito/hello_cognito.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/cognito/tests/cognito_gtests.cpp b/cpp/example_code/cognito/tests/cognito_gtests.cpp index 5167c879756..8f5f4bfa931 100644 --- a/cpp/example_code/cognito/tests/cognito_gtests.cpp +++ b/cpp/example_code/cognito/tests/cognito_gtests.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "cognito_gtests.h" #include diff --git a/cpp/example_code/cognito/tests/cognito_gtests.h b/cpp/example_code/cognito/tests/cognito_gtests.h index 29471b455b1..97b72d14929 100644 --- a/cpp/example_code/cognito/tests/cognito_gtests.h +++ b/cpp/example_code/cognito/tests/cognito_gtests.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef S3_EXAMPLES_S3_GTESTS_H diff --git a/cpp/example_code/cognito/tests/gtest_getting_started_with_user_pools.cpp b/cpp/example_code/cognito/tests/gtest_getting_started_with_user_pools.cpp index eab403cced1..e85fc94e931 100644 --- a/cpp/example_code/cognito/tests/gtest_getting_started_with_user_pools.cpp +++ b/cpp/example_code/cognito/tests/gtest_getting_started_with_user_pools.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/cognito/tests/test_main.cpp b/cpp/example_code/cognito/tests/test_main.cpp index 00ed3e2b055..656f92cb221 100644 --- a/cpp/example_code/cognito/tests/test_main.cpp +++ b/cpp/example_code/cognito/tests/test_main.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "gtest/gtest.h" diff --git a/cpp/example_code/cross-service/photo_asset_manager/cpp_lambda_functions.cpp b/cpp/example_code/cross-service/photo_asset_manager/cpp_lambda_functions.cpp index 73b9150afa6..1778215c662 100644 --- a/cpp/example_code/cross-service/photo_asset_manager/cpp_lambda_functions.cpp +++ b/cpp/example_code/cross-service/photo_asset_manager/cpp_lambda_functions.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/cross-service/photo_asset_manager/cpp_lambda_functions.h b/cpp/example_code/cross-service/photo_asset_manager/cpp_lambda_functions.h index cfbfcab4659..fd574073370 100644 --- a/cpp/example_code/cross-service/photo_asset_manager/cpp_lambda_functions.h +++ b/cpp/example_code/cross-service/photo_asset_manager/cpp_lambda_functions.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef PAM_EXAMPLES_GTESTS_CPP_LAMBDA_FUNCTIONS_H diff --git a/cpp/example_code/cross-service/photo_asset_manager/cpp_pam_lambdas.cpp b/cpp/example_code/cross-service/photo_asset_manager/cpp_pam_lambdas.cpp index 6ec63d36a64..749fd139e17 100644 --- a/cpp/example_code/cross-service/photo_asset_manager/cpp_pam_lambdas.cpp +++ b/cpp/example_code/cross-service/photo_asset_manager/cpp_pam_lambdas.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/cross-service/photo_asset_manager/tests/cpp_lambda_tests.cpp b/cpp/example_code/cross-service/photo_asset_manager/tests/cpp_lambda_tests.cpp index 93782312604..52c2468232f 100644 --- a/cpp/example_code/cross-service/photo_asset_manager/tests/cpp_lambda_tests.cpp +++ b/cpp/example_code/cross-service/photo_asset_manager/tests/cpp_lambda_tests.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/cross-service/photo_asset_manager/tests/pam_gtests.cpp b/cpp/example_code/cross-service/photo_asset_manager/tests/pam_gtests.cpp index 0598e13bac3..21c119c704e 100644 --- a/cpp/example_code/cross-service/photo_asset_manager/tests/pam_gtests.cpp +++ b/cpp/example_code/cross-service/photo_asset_manager/tests/pam_gtests.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "pam_gtests.h" #include diff --git a/cpp/example_code/cross-service/photo_asset_manager/tests/pam_gtests.h b/cpp/example_code/cross-service/photo_asset_manager/tests/pam_gtests.h index 753e8924a42..b1c3d87ba5c 100644 --- a/cpp/example_code/cross-service/photo_asset_manager/tests/pam_gtests.h +++ b/cpp/example_code/cross-service/photo_asset_manager/tests/pam_gtests.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef S3_EXAMPLES_S3_GTESTS_H diff --git a/cpp/example_code/cross-service/photo_asset_manager/tests/test_main.cpp b/cpp/example_code/cross-service/photo_asset_manager/tests/test_main.cpp index 00ed3e2b055..656f92cb221 100644 --- a/cpp/example_code/cross-service/photo_asset_manager/tests/test_main.cpp +++ b/cpp/example_code/cross-service/photo_asset_manager/tests/test_main.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "gtest/gtest.h" diff --git a/cpp/example_code/cross-service/serverless-aurora/HTTPReceiver.h b/cpp/example_code/cross-service/serverless-aurora/HTTPReceiver.h index 05b0be7e36d..b1635f9a1fc 100644 --- a/cpp/example_code/cross-service/serverless-aurora/HTTPReceiver.h +++ b/cpp/example_code/cross-service/serverless-aurora/HTTPReceiver.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #ifndef AWSDOC_CROSSSERVICE_HTTPRECEIVER_H #define AWSDOC_CROSSSERVICE_HTTPRECEIVER_H diff --git a/cpp/example_code/cross-service/serverless-aurora/ItemTrackerHTTPHandler.cpp b/cpp/example_code/cross-service/serverless-aurora/ItemTrackerHTTPHandler.cpp index 6a9083b2fd9..15a860f78d8 100644 --- a/cpp/example_code/cross-service/serverless-aurora/ItemTrackerHTTPHandler.cpp +++ b/cpp/example_code/cross-service/serverless-aurora/ItemTrackerHTTPHandler.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * ItemTrackerHTTPHandler.h/.cpp diff --git a/cpp/example_code/cross-service/serverless-aurora/ItemTrackerHTTPHandler.h b/cpp/example_code/cross-service/serverless-aurora/ItemTrackerHTTPHandler.h index 6032439801e..3c7fe774bc0 100644 --- a/cpp/example_code/cross-service/serverless-aurora/ItemTrackerHTTPHandler.h +++ b/cpp/example_code/cross-service/serverless-aurora/ItemTrackerHTTPHandler.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * ItemTrackerHTTPHandler.h/.cpp diff --git a/cpp/example_code/cross-service/serverless-aurora/PocoHTTPServer.cpp b/cpp/example_code/cross-service/serverless-aurora/PocoHTTPServer.cpp index 89ec87c0dc7..ba1f74e184e 100644 --- a/cpp/example_code/cross-service/serverless-aurora/PocoHTTPServer.cpp +++ b/cpp/example_code/cross-service/serverless-aurora/PocoHTTPServer.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * PocoHTTPHandler.h/.cpp diff --git a/cpp/example_code/cross-service/serverless-aurora/PocoHTTPServer.h b/cpp/example_code/cross-service/serverless-aurora/PocoHTTPServer.h index 91de78ac2e3..3972766d716 100644 --- a/cpp/example_code/cross-service/serverless-aurora/PocoHTTPServer.h +++ b/cpp/example_code/cross-service/serverless-aurora/PocoHTTPServer.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * PocoHTTPHandler.h/.cpp * diff --git a/cpp/example_code/cross-service/serverless-aurora/RDSDataHandler.cpp b/cpp/example_code/cross-service/serverless-aurora/RDSDataHandler.cpp index a3685f6df5e..b375162e611 100644 --- a/cpp/example_code/cross-service/serverless-aurora/RDSDataHandler.cpp +++ b/cpp/example_code/cross-service/serverless-aurora/RDSDataHandler.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * RDSDataHandler.h/.cpp * diff --git a/cpp/example_code/cross-service/serverless-aurora/RDSDataHandler.h b/cpp/example_code/cross-service/serverless-aurora/RDSDataHandler.h index 170375c42e4..4fee7759a48 100644 --- a/cpp/example_code/cross-service/serverless-aurora/RDSDataHandler.h +++ b/cpp/example_code/cross-service/serverless-aurora/RDSDataHandler.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * RDSDataHandler.h/.cpp diff --git a/cpp/example_code/cross-service/serverless-aurora/SESV2EmailHandler.cpp b/cpp/example_code/cross-service/serverless-aurora/SESV2EmailHandler.cpp index 1065cb8b172..13b8cf266e6 100644 --- a/cpp/example_code/cross-service/serverless-aurora/SESV2EmailHandler.cpp +++ b/cpp/example_code/cross-service/serverless-aurora/SESV2EmailHandler.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * SESV2EmailHandler.h/.cpp diff --git a/cpp/example_code/cross-service/serverless-aurora/SESV2EmailHandler.h b/cpp/example_code/cross-service/serverless-aurora/SESV2EmailHandler.h index 4324b8559d7..61cf6b3b7ac 100644 --- a/cpp/example_code/cross-service/serverless-aurora/SESV2EmailHandler.h +++ b/cpp/example_code/cross-service/serverless-aurora/SESV2EmailHandler.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * SESV2EmailHandler.h/.cpp diff --git a/cpp/example_code/cross-service/serverless-aurora/serverless_aurora.cpp b/cpp/example_code/cross-service/serverless-aurora/serverless_aurora.cpp index da70c5b719e..210ea42406a 100644 --- a/cpp/example_code/cross-service/serverless-aurora/serverless_aurora.cpp +++ b/cpp/example_code/cross-service/serverless-aurora/serverless_aurora.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * serverless_aurora.cpp * diff --git a/cpp/example_code/cross-service/serverless-aurora/tests/gtest_serverless_aurora.cpp b/cpp/example_code/cross-service/serverless-aurora/tests/gtest_serverless_aurora.cpp index 14558588ccb..4bada5019b3 100644 --- a/cpp/example_code/cross-service/serverless-aurora/tests/gtest_serverless_aurora.cpp +++ b/cpp/example_code/cross-service/serverless-aurora/tests/gtest_serverless_aurora.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/cross-service/serverless-aurora/tests/serverless_aurora_gtests.cpp b/cpp/example_code/cross-service/serverless-aurora/tests/serverless_aurora_gtests.cpp index e34e93b4181..40b2833bff1 100644 --- a/cpp/example_code/cross-service/serverless-aurora/tests/serverless_aurora_gtests.cpp +++ b/cpp/example_code/cross-service/serverless-aurora/tests/serverless_aurora_gtests.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "serverless_aurora_gtests.h" #include diff --git a/cpp/example_code/cross-service/serverless-aurora/tests/serverless_aurora_gtests.h b/cpp/example_code/cross-service/serverless-aurora/tests/serverless_aurora_gtests.h index 71cfb10bc71..4c266bd5b06 100644 --- a/cpp/example_code/cross-service/serverless-aurora/tests/serverless_aurora_gtests.h +++ b/cpp/example_code/cross-service/serverless-aurora/tests/serverless_aurora_gtests.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef S3_EXAMPLES_S3_GTESTS_H diff --git a/cpp/example_code/cross-service/topics_and_queues/messaging_with_topics_and_queues.cpp b/cpp/example_code/cross-service/topics_and_queues/messaging_with_topics_and_queues.cpp index a2b95f50ab9..6247a577cdd 100644 --- a/cpp/example_code/cross-service/topics_and_queues/messaging_with_topics_and_queues.cpp +++ b/cpp/example_code/cross-service/topics_and_queues/messaging_with_topics_and_queues.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/cross-service/topics_and_queues/tests/gtest_messaging_with_topics_and_queues.cpp b/cpp/example_code/cross-service/topics_and_queues/tests/gtest_messaging_with_topics_and_queues.cpp index 6b8472c5f3f..2bdb04bb942 100644 --- a/cpp/example_code/cross-service/topics_and_queues/tests/gtest_messaging_with_topics_and_queues.cpp +++ b/cpp/example_code/cross-service/topics_and_queues/tests/gtest_messaging_with_topics_and_queues.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/cross-service/topics_and_queues/tests/test_main.cpp b/cpp/example_code/cross-service/topics_and_queues/tests/test_main.cpp index 00ed3e2b055..656f92cb221 100644 --- a/cpp/example_code/cross-service/topics_and_queues/tests/test_main.cpp +++ b/cpp/example_code/cross-service/topics_and_queues/tests/test_main.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "gtest/gtest.h" diff --git a/cpp/example_code/cross-service/topics_and_queues/tests/topics_and_queues_gtests.cpp b/cpp/example_code/cross-service/topics_and_queues/tests/topics_and_queues_gtests.cpp index d1caac80ee7..3e20ef3a9a6 100644 --- a/cpp/example_code/cross-service/topics_and_queues/tests/topics_and_queues_gtests.cpp +++ b/cpp/example_code/cross-service/topics_and_queues/tests/topics_and_queues_gtests.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "topics_and_queues_gtests.h" #include diff --git a/cpp/example_code/cross-service/topics_and_queues/tests/topics_and_queues_gtests.h b/cpp/example_code/cross-service/topics_and_queues/tests/topics_and_queues_gtests.h index e1e7b8f4800..54b09e59dce 100644 --- a/cpp/example_code/cross-service/topics_and_queues/tests/topics_and_queues_gtests.h +++ b/cpp/example_code/cross-service/topics_and_queues/tests/topics_and_queues_gtests.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef S3_EXAMPLES_S3_GTESTS_H diff --git a/cpp/example_code/cross-service/topics_and_queues/topics_and_queues_samples.h b/cpp/example_code/cross-service/topics_and_queues/topics_and_queues_samples.h index 995c7f02d58..03dacf5d289 100644 --- a/cpp/example_code/cross-service/topics_and_queues/topics_and_queues_samples.h +++ b/cpp/example_code/cross-service/topics_and_queues/topics_and_queues_samples.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef TOPICS_AND_QUEUES_TOPICS_AND_QUEUES_SAMPLES_H diff --git a/cpp/example_code/dynamodb/batch_get_item.cpp b/cpp/example_code/dynamodb/batch_get_item.cpp index eaf81e8e7c5..7fd56536e38 100644 --- a/cpp/example_code/dynamodb/batch_get_item.cpp +++ b/cpp/example_code/dynamodb/batch_get_item.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -29,7 +27,7 @@ * This example uses the "Forum.json" and "ProductCatalog.json" sample data. */ -//snippet-start:[cpp.example_code.dynamodb.batch_get_item] +// snippet-start:[cpp.example_code.dynamodb.batch_get_item] //! Batch get items from different Amazon DynamoDB tables. /*! \sa batchGetItem() @@ -141,7 +139,7 @@ bool AwsDoc::DynamoDB::batchGetItem( return result; } -//snippet-end:[cpp.example_code.dynamodb.batch_get_item] +// snippet-end:[cpp.example_code.dynamodb.batch_get_item] /* * diff --git a/cpp/example_code/dynamodb/batch_write_item.cpp b/cpp/example_code/dynamodb/batch_write_item.cpp index 1c7dd83a342..fc04482dcfb 100644 --- a/cpp/example_code/dynamodb/batch_write_item.cpp +++ b/cpp/example_code/dynamodb/batch_write_item.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/dynamodb/create_table.cpp b/cpp/example_code/dynamodb/create_table.cpp index 3926dc85624..476bee96bf9 100644 --- a/cpp/example_code/dynamodb/create_table.cpp +++ b/cpp/example_code/dynamodb/create_table.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,7 +12,7 @@ * **/ -//snippet-start:[dynamodb.cpp.create_table.inc] +// snippet-start:[dynamodb.cpp.create_table.inc] #include #include #include @@ -23,7 +21,7 @@ #include #include #include -//snippet-end:[dynamodb.cpp.create_table.inc] +// snippet-end:[dynamodb.cpp.create_table.inc] #include "dynamodb_samples.h" // snippet-start:[dynamodb.cpp.create_table.code] diff --git a/cpp/example_code/dynamodb/create_table_composite_key.cpp b/cpp/example_code/dynamodb/create_table_composite_key.cpp index 0861013c0b7..0eac52ae837 100644 --- a/cpp/example_code/dynamodb/create_table_composite_key.cpp +++ b/cpp/example_code/dynamodb/create_table_composite_key.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,7 +12,7 @@ * **/ -//snippet-start:[dynamodb.cpp.create_table_composite_key.inc] +// snippet-start:[dynamodb.cpp.create_table_composite_key.inc] #include #include #include @@ -23,7 +21,7 @@ #include #include #include -//snippet-end:[dynamodb.cpp.create_table_composite_key.inc] +// snippet-end:[dynamodb.cpp.create_table_composite_key.inc] #include "dynamodb_samples.h" // snippet-start:[dynamodb.cpp.create_table_composite_key.code] diff --git a/cpp/example_code/dynamodb/delete_item.cpp b/cpp/example_code/dynamodb/delete_item.cpp index c23775471a8..b5183647ea1 100644 --- a/cpp/example_code/dynamodb/delete_item.cpp +++ b/cpp/example_code/dynamodb/delete_item.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -21,7 +19,7 @@ #include #include "dynamodb_samples.h" -//snippet-start:[cpp.example_code.dynamodb.delete_item] +// snippet-start:[cpp.example_code.dynamodb.delete_item] //! Delete an item from an Amazon DynamoDB table. /*! \sa deleteItem() @@ -56,7 +54,7 @@ bool AwsDoc::DynamoDB::deleteItem(const Aws::String &tableName, return outcome.IsSuccess(); } -//snippet-end:[cpp.example_code.dynamodb.delete_item] +// snippet-end:[cpp.example_code.dynamodb.delete_item] /* * diff --git a/cpp/example_code/dynamodb/delete_table.cpp b/cpp/example_code/dynamodb/delete_table.cpp index 6f25bc092fe..4d729dd3123 100644 --- a/cpp/example_code/dynamodb/delete_table.cpp +++ b/cpp/example_code/dynamodb/delete_table.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -13,12 +11,12 @@ * https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/getting-started-code-examples.html. * **/ -//snippet-start:[dynamodb.cpp.delete_table.inc] +// snippet-start:[dynamodb.cpp.delete_table.inc] #include #include #include #include -//snippet-end:[dynamodb.cpp.delete_table.inc] +// snippet-end:[dynamodb.cpp.delete_table.inc] #include "dynamodb_samples.h" diff --git a/cpp/example_code/dynamodb/describe_table.cpp b/cpp/example_code/dynamodb/describe_table.cpp index 701057bcf2d..19e93d86cb1 100644 --- a/cpp/example_code/dynamodb/describe_table.cpp +++ b/cpp/example_code/dynamodb/describe_table.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,12 +12,12 @@ * **/ -//snippet-start:[dynamodb.cpp.describe_table.inc] +// snippet-start:[dynamodb.cpp.describe_table.inc] #include #include #include #include -//snippet-end:[dynamodb.cpp.describe_table.inc] +// snippet-end:[dynamodb.cpp.describe_table.inc] #include "dynamodb_samples.h" // snippet-start:[dynamodb.cpp.describe_table.code] diff --git a/cpp/example_code/dynamodb/dynamodb_getting_started_scenario.cpp b/cpp/example_code/dynamodb/dynamodb_getting_started_scenario.cpp index 7af7fdc931e..dde488f0081 100644 --- a/cpp/example_code/dynamodb/dynamodb_getting_started_scenario.cpp +++ b/cpp/example_code/dynamodb/dynamodb_getting_started_scenario.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/dynamodb/dynamodb_partiql_batch_scenario.cpp b/cpp/example_code/dynamodb/dynamodb_partiql_batch_scenario.cpp index dcff3eb278e..fbb6a7c586e 100644 --- a/cpp/example_code/dynamodb/dynamodb_partiql_batch_scenario.cpp +++ b/cpp/example_code/dynamodb/dynamodb_partiql_batch_scenario.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/dynamodb/dynamodb_partiql_single_scenario.cpp b/cpp/example_code/dynamodb/dynamodb_partiql_single_scenario.cpp index eaae434c5dc..5b23f49e85c 100644 --- a/cpp/example_code/dynamodb/dynamodb_partiql_single_scenario.cpp +++ b/cpp/example_code/dynamodb/dynamodb_partiql_single_scenario.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/dynamodb/dynamodb_samples.h b/cpp/example_code/dynamodb/dynamodb_samples.h index c019e8d3e46..320cb65ce8b 100644 --- a/cpp/example_code/dynamodb/dynamodb_samples.h +++ b/cpp/example_code/dynamodb/dynamodb_samples.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #ifndef DYNAMODB_EXAMPLES_DYNAMODB_SAMPLES_H #define DYNAMODB_EXAMPLES_DYNAMODB_SAMPLES_H diff --git a/cpp/example_code/dynamodb/dynamodb_utils.cpp b/cpp/example_code/dynamodb/dynamodb_utils.cpp index cda3892c74e..ffa272b6696 100644 --- a/cpp/example_code/dynamodb/dynamodb_utils.cpp +++ b/cpp/example_code/dynamodb/dynamodb_utils.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * diff --git a/cpp/example_code/dynamodb/get_item.cpp b/cpp/example_code/dynamodb/get_item.cpp index d496f311e3e..12c9522bbdb 100644 --- a/cpp/example_code/dynamodb/get_item.cpp +++ b/cpp/example_code/dynamodb/get_item.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,13 +12,13 @@ * **/ -//snippet-start:[dynamodb.cpp.get_item.inc] +// snippet-start:[dynamodb.cpp.get_item.inc] #include #include #include #include #include -//snippet-end:[dynamodb.cpp.get_item.inc] +// snippet-end:[dynamodb.cpp.get_item.inc] #include "dynamodb_samples.h" // snippet-start:[dynamodb.cpp.get_item.code] diff --git a/cpp/example_code/dynamodb/hello_dynamodb/hello_dynamodb.cpp b/cpp/example_code/dynamodb/hello_dynamodb/hello_dynamodb.cpp index 167d4d6c852..b6adb4c73e8 100644 --- a/cpp/example_code/dynamodb/hello_dynamodb/hello_dynamodb.cpp +++ b/cpp/example_code/dynamodb/hello_dynamodb/hello_dynamodb.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/dynamodb/list_tables.cpp b/cpp/example_code/dynamodb/list_tables.cpp index 401787c64ea..617eec8dd5e 100644 --- a/cpp/example_code/dynamodb/list_tables.cpp +++ b/cpp/example_code/dynamodb/list_tables.cpp @@ -1,7 +1,6 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,14 +13,14 @@ SPDX-License-Identifier: Apache-2.0 * **/ -//snippet-start:[dynamodb.cpp.list_tables.inc] +// snippet-start:[dynamodb.cpp.list_tables.inc] #include #include #include #include #include #include -//snippet-end:[dynamodb.cpp.list_tables.inc] +// snippet-end:[dynamodb.cpp.list_tables.inc] #include "dynamodb_samples.h" // snippet-start:[dynamodb.cpp.list_tables.code] diff --git a/cpp/example_code/dynamodb/put_item.cpp b/cpp/example_code/dynamodb/put_item.cpp index 3574105cf99..e9ffe1245f3 100644 --- a/cpp/example_code/dynamodb/put_item.cpp +++ b/cpp/example_code/dynamodb/put_item.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,17 +12,17 @@ * **/ -//snippet-start:[dynamodb.cpp.put_item.inc] +// snippet-start:[dynamodb.cpp.put_item.inc] #include #include #include #include #include #include -//snippet-end:[dynamodb.cpp.put_item.inc] +// snippet-end:[dynamodb.cpp.put_item.inc] #include "dynamodb_samples.h" -//snippet-start:[dynamodb.cpp.put_item.code] +// snippet-start:[dynamodb.cpp.put_item.code] //! Put an item in an Amazon DynamoDB table. /*! \sa putItem() @@ -76,7 +74,7 @@ bool AwsDoc::DynamoDB::putItem(const Aws::String &tableName, return outcome.IsSuccess(); } -//snippet-end:[dynamodb.cpp.put_item.code] +// snippet-end:[dynamodb.cpp.put_item.code] /* * diff --git a/cpp/example_code/dynamodb/query_items.cpp b/cpp/example_code/dynamodb/query_items.cpp index 5cb74646e02..5b68d3d72d3 100644 --- a/cpp/example_code/dynamodb/query_items.cpp +++ b/cpp/example_code/dynamodb/query_items.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/dynamodb/scan_table.cpp b/cpp/example_code/dynamodb/scan_table.cpp index 57694550fec..5caf9c189f7 100644 --- a/cpp/example_code/dynamodb/scan_table.cpp +++ b/cpp/example_code/dynamodb/scan_table.cpp @@ -1,7 +1,6 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/dynamodb/tests/dynamodb_gtests.cpp b/cpp/example_code/dynamodb/tests/dynamodb_gtests.cpp index 9cf7b45c6b0..c5e43cad387 100644 --- a/cpp/example_code/dynamodb/tests/dynamodb_gtests.cpp +++ b/cpp/example_code/dynamodb/tests/dynamodb_gtests.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "dynamodb_gtests.h" #include diff --git a/cpp/example_code/dynamodb/tests/dynamodb_gtests.h b/cpp/example_code/dynamodb/tests/dynamodb_gtests.h index e2201238e08..2ec16064472 100644 --- a/cpp/example_code/dynamodb/tests/dynamodb_gtests.h +++ b/cpp/example_code/dynamodb/tests/dynamodb_gtests.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef S3_EXAMPLES_S3_GTESTS_H diff --git a/cpp/example_code/dynamodb/tests/gtest_batch_get_item.cpp b/cpp/example_code/dynamodb/tests/gtest_batch_get_item.cpp index 2f9c7a6f0ee..4c90a9c07a5 100644 --- a/cpp/example_code/dynamodb/tests/gtest_batch_get_item.cpp +++ b/cpp/example_code/dynamodb/tests/gtest_batch_get_item.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/dynamodb/tests/gtest_batch_write_item.cpp b/cpp/example_code/dynamodb/tests/gtest_batch_write_item.cpp index 4aa22340b6d..93bdf1e5f90 100644 --- a/cpp/example_code/dynamodb/tests/gtest_batch_write_item.cpp +++ b/cpp/example_code/dynamodb/tests/gtest_batch_write_item.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/dynamodb/tests/gtest_create_table.cpp b/cpp/example_code/dynamodb/tests/gtest_create_table.cpp index 66937bf4732..ec99ea2f0ad 100644 --- a/cpp/example_code/dynamodb/tests/gtest_create_table.cpp +++ b/cpp/example_code/dynamodb/tests/gtest_create_table.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/dynamodb/tests/gtest_create_table_composite_key.cpp b/cpp/example_code/dynamodb/tests/gtest_create_table_composite_key.cpp index a557df2f55d..21b3fb15040 100644 --- a/cpp/example_code/dynamodb/tests/gtest_create_table_composite_key.cpp +++ b/cpp/example_code/dynamodb/tests/gtest_create_table_composite_key.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/dynamodb/tests/gtest_delete_item.cpp b/cpp/example_code/dynamodb/tests/gtest_delete_item.cpp index f768c1472a7..00ac689b692 100644 --- a/cpp/example_code/dynamodb/tests/gtest_delete_item.cpp +++ b/cpp/example_code/dynamodb/tests/gtest_delete_item.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/dynamodb/tests/gtest_delete_table.cpp b/cpp/example_code/dynamodb/tests/gtest_delete_table.cpp index 531991fe79f..d46f4c0b72b 100644 --- a/cpp/example_code/dynamodb/tests/gtest_delete_table.cpp +++ b/cpp/example_code/dynamodb/tests/gtest_delete_table.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/dynamodb/tests/gtest_describe_table.cpp b/cpp/example_code/dynamodb/tests/gtest_describe_table.cpp index ce7f0fa7f0a..50dae0a5737 100644 --- a/cpp/example_code/dynamodb/tests/gtest_describe_table.cpp +++ b/cpp/example_code/dynamodb/tests/gtest_describe_table.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/dynamodb/tests/gtest_dynamodb_getting_started_scenario.cpp b/cpp/example_code/dynamodb/tests/gtest_dynamodb_getting_started_scenario.cpp index f7d6586a0e0..87679304e4a 100644 --- a/cpp/example_code/dynamodb/tests/gtest_dynamodb_getting_started_scenario.cpp +++ b/cpp/example_code/dynamodb/tests/gtest_dynamodb_getting_started_scenario.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/dynamodb/tests/gtest_dynamodb_partiql_batch_scenario.cpp b/cpp/example_code/dynamodb/tests/gtest_dynamodb_partiql_batch_scenario.cpp index 43c94bd22ed..07918158cbc 100644 --- a/cpp/example_code/dynamodb/tests/gtest_dynamodb_partiql_batch_scenario.cpp +++ b/cpp/example_code/dynamodb/tests/gtest_dynamodb_partiql_batch_scenario.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/dynamodb/tests/gtest_dynamodb_partiql_single_scenario.cpp b/cpp/example_code/dynamodb/tests/gtest_dynamodb_partiql_single_scenario.cpp index 478577a8fa6..31dd93cd4f8 100644 --- a/cpp/example_code/dynamodb/tests/gtest_dynamodb_partiql_single_scenario.cpp +++ b/cpp/example_code/dynamodb/tests/gtest_dynamodb_partiql_single_scenario.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/dynamodb/tests/gtest_get_item.cpp b/cpp/example_code/dynamodb/tests/gtest_get_item.cpp index 7efd2a442b3..2db148fa259 100644 --- a/cpp/example_code/dynamodb/tests/gtest_get_item.cpp +++ b/cpp/example_code/dynamodb/tests/gtest_get_item.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/dynamodb/tests/gtest_list_tables.cpp b/cpp/example_code/dynamodb/tests/gtest_list_tables.cpp index ce221afd4fe..fedf5f51b40 100644 --- a/cpp/example_code/dynamodb/tests/gtest_list_tables.cpp +++ b/cpp/example_code/dynamodb/tests/gtest_list_tables.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/dynamodb/tests/gtest_put_item.cpp b/cpp/example_code/dynamodb/tests/gtest_put_item.cpp index 5be898ae73e..23da7c17d6c 100644 --- a/cpp/example_code/dynamodb/tests/gtest_put_item.cpp +++ b/cpp/example_code/dynamodb/tests/gtest_put_item.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/dynamodb/tests/gtest_query_items.cpp b/cpp/example_code/dynamodb/tests/gtest_query_items.cpp index 68cb8d5db59..c177e5a3de6 100644 --- a/cpp/example_code/dynamodb/tests/gtest_query_items.cpp +++ b/cpp/example_code/dynamodb/tests/gtest_query_items.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/dynamodb/tests/gtest_scan_table.cpp b/cpp/example_code/dynamodb/tests/gtest_scan_table.cpp index 4bada42ba7b..e6eda8f6207 100644 --- a/cpp/example_code/dynamodb/tests/gtest_scan_table.cpp +++ b/cpp/example_code/dynamodb/tests/gtest_scan_table.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/dynamodb/tests/gtest_update_item.cpp b/cpp/example_code/dynamodb/tests/gtest_update_item.cpp index 170d86451d8..601f1b066bc 100644 --- a/cpp/example_code/dynamodb/tests/gtest_update_item.cpp +++ b/cpp/example_code/dynamodb/tests/gtest_update_item.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/dynamodb/tests/gtest_update_table.cpp b/cpp/example_code/dynamodb/tests/gtest_update_table.cpp index 504ba158158..b0fbbe84f90 100644 --- a/cpp/example_code/dynamodb/tests/gtest_update_table.cpp +++ b/cpp/example_code/dynamodb/tests/gtest_update_table.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/dynamodb/tests/test_main.cpp b/cpp/example_code/dynamodb/tests/test_main.cpp index afe38244895..ab6fdb7ba22 100644 --- a/cpp/example_code/dynamodb/tests/test_main.cpp +++ b/cpp/example_code/dynamodb/tests/test_main.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "gtest/gtest.h" diff --git a/cpp/example_code/dynamodb/update_item.cpp b/cpp/example_code/dynamodb/update_item.cpp index 2d441a48400..378e145224b 100644 --- a/cpp/example_code/dynamodb/update_item.cpp +++ b/cpp/example_code/dynamodb/update_item.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,13 +12,13 @@ * **/ -//snippet-start:[dynamodb.cpp.update_item.inc] +// snippet-start:[dynamodb.cpp.update_item.inc] #include #include #include #include #include -//snippet-end:[dynamodb.cpp.update_item.inc] +// snippet-end:[dynamodb.cpp.update_item.inc] #include "dynamodb_samples.h" // snippet-start:[dynamodb.cpp.update_item.code] diff --git a/cpp/example_code/dynamodb/update_table.cpp b/cpp/example_code/dynamodb/update_table.cpp index 28ea0d031dd..e66715e8343 100644 --- a/cpp/example_code/dynamodb/update_table.cpp +++ b/cpp/example_code/dynamodb/update_table.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,14 +12,14 @@ * **/ -//snippet-start:[dynamodb.cpp.update_table.inc] +// snippet-start:[dynamodb.cpp.update_table.inc] #include #include #include #include #include #include -//snippet-end:[dynamodb.cpp.update_table.inc] +// snippet-end:[dynamodb.cpp.update_table.inc] #include "dynamodb_samples.h" /** diff --git a/cpp/example_code/ebs/attach_volume.cpp b/cpp/example_code/ebs/attach_volume.cpp index d182a20d2d9..bac95e15889 100644 --- a/cpp/example_code/ebs/attach_volume.cpp +++ b/cpp/example_code/ebs/attach_volume.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[attach_volume.cpp demonstrates how to attach an Amazon Elastic Block Store volume to an Amazon EC2 instance.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Elastic Block Store] -//snippet-service:[ebs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/ebs/create_volume.cpp b/cpp/example_code/ebs/create_volume.cpp index aba8c1b46e5..fdb1977bfca 100644 --- a/cpp/example_code/ebs/create_volume.cpp +++ b/cpp/example_code/ebs/create_volume.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[create_volume.cpp demonstrates how to create an Amazon Elastic Block Store volume for an Amazon EC2 instance.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Elastic Block Store] -//snippet-service:[ebs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/ebs/delete_volume.cpp b/cpp/example_code/ebs/delete_volume.cpp index cc80a982410..744cb8ecb38 100644 --- a/cpp/example_code/ebs/delete_volume.cpp +++ b/cpp/example_code/ebs/delete_volume.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[delete_volume.cpp demonstrates how to delete an Amazon Elastic Block Store volume from an Amazon EC2 instance.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Elastic Block Store] -//snippet-service:[ebs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/ebs/describe_volumes.cpp b/cpp/example_code/ebs/describe_volumes.cpp index b4a8542e04a..d295cfa49bc 100644 --- a/cpp/example_code/ebs/describe_volumes.cpp +++ b/cpp/example_code/ebs/describe_volumes.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[describe_volumes.cpp demonstrates how to retrieve information about the Amazon Elastic Block Store volumes attached to an Amazon EC2 instance.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Elastic Block Store] -//snippet-service:[ebs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/ec2/allocate_address.cpp b/cpp/example_code/ec2/allocate_address.cpp index e4f93852440..aca4a330986 100644 --- a/cpp/example_code/ec2/allocate_address.cpp +++ b/cpp/example_code/ec2/allocate_address.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,7 +12,7 @@ * **/ -//snippet-start:[ec2.cpp.allocate_address.inc] +// snippet-start:[ec2.cpp.allocate_address.inc] #include #include #include @@ -22,7 +20,7 @@ #include #include #include -//snippet-end:[ec2.cpp.allocate_address.inc] +// snippet-end:[ec2.cpp.allocate_address.inc] #include "ec2_samples.h" //! Allocate an Elastic IP address and associate it with an Amazon Elastic Compute Cloud diff --git a/cpp/example_code/ec2/create_instance.cpp b/cpp/example_code/ec2/create_instance.cpp index 784ad6d1dc5..2ae4c9dc4c1 100644 --- a/cpp/example_code/ec2/create_instance.cpp +++ b/cpp/example_code/ec2/create_instance.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,14 +12,14 @@ * **/ -//snippet-start:[ec2.cpp.create_instance.inc] +// snippet-start:[ec2.cpp.create_instance.inc] #include #include #include #include #include #include -//snippet-end:[ec2.cpp.create_instance.inc] +// snippet-end:[ec2.cpp.create_instance.inc] #include "ec2_samples.h" //! Launch an Amazon Elastic Compute Cloud (Amazon EC2) instance. diff --git a/cpp/example_code/ec2/create_key_pair.cpp b/cpp/example_code/ec2/create_key_pair.cpp index a81732b20e5..cb0017eb464 100644 --- a/cpp/example_code/ec2/create_key_pair.cpp +++ b/cpp/example_code/ec2/create_key_pair.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,13 +12,13 @@ * **/ -//snippet-start:[ec2.cpp.create_key_pair.inc] +// snippet-start:[ec2.cpp.create_key_pair.inc] #include #include #include #include #include -//snippet-end:[ec2.cpp.create_key_pair.inc] +// snippet-end:[ec2.cpp.create_key_pair.inc] #include "ec2_samples.h" //! Create an Amazon Elastic Compute Cloud (Amazon EC2) instance key pair. diff --git a/cpp/example_code/ec2/create_security_group.cpp b/cpp/example_code/ec2/create_security_group.cpp index dcfaeab1fd3..20d487e6f48 100644 --- a/cpp/example_code/ec2/create_security_group.cpp +++ b/cpp/example_code/ec2/create_security_group.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,15 +12,15 @@ * **/ -//snippet-start:[ec2.cpp.create_security_group.inc] +// snippet-start:[ec2.cpp.create_security_group.inc] #include #include #include #include -//snippet-end:[ec2.cpp.create_security_group.inc] -//snippet-start:[ec2.cpp.configure_security_group.inc] +// snippet-end:[ec2.cpp.create_security_group.inc] +// snippet-start:[ec2.cpp.configure_security_group.inc] #include -//snippet-end:[ec2.cpp.configure_security_group.inc] +// snippet-end:[ec2.cpp.configure_security_group.inc] #include #include "ec2_samples.h" diff --git a/cpp/example_code/ec2/delete_key_pair.cpp b/cpp/example_code/ec2/delete_key_pair.cpp index 7b98d0a9c66..06b3c6f8518 100644 --- a/cpp/example_code/ec2/delete_key_pair.cpp +++ b/cpp/example_code/ec2/delete_key_pair.cpp @@ -1,7 +1,6 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -13,12 +12,12 @@ SPDX-License-Identifier: Apache-2.0 * https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/getting-started-code-examples.html. * **/ -//snippet-start:[ec2.cpp.delete_key_pair.inc] +// snippet-start:[ec2.cpp.delete_key_pair.inc] #include #include #include #include -//snippet-end:[ec2.cpp.delete_key_pair.inc] +// snippet-end:[ec2.cpp.delete_key_pair.inc] #include "ec2_samples.h" diff --git a/cpp/example_code/ec2/delete_security_group.cpp b/cpp/example_code/ec2/delete_security_group.cpp index 6e175bacc07..c3bdd1d49c0 100644 --- a/cpp/example_code/ec2/delete_security_group.cpp +++ b/cpp/example_code/ec2/delete_security_group.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,12 +12,12 @@ * **/ -//snippet-start:[ec2.cpp.delete_security_group.inc] +// snippet-start:[ec2.cpp.delete_security_group.inc] #include #include #include #include -//snippet-end:[ec2.cpp.delete_security_group.inc] +// snippet-end:[ec2.cpp.delete_security_group.inc] #include "ec2_samples.h" //! Delete a security group. @@ -31,7 +29,7 @@ */ bool AwsDoc::EC2::DeleteSecurityGroup(const Aws::String &securityGroupID, const Aws::Client::ClientConfiguration &clientConfiguration) { - //snippet-start:[ec2.cpp.delete_security_group.code] + // snippet-start:[ec2.cpp.delete_security_group.code] Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::DeleteSecurityGroupRequest request; @@ -46,7 +44,7 @@ bool AwsDoc::EC2::DeleteSecurityGroup(const Aws::String &securityGroupID, std::cout << "Successfully deleted security group " << securityGroupID << std::endl; } - //snippet-end:[ec2.cpp.delete_security_group.code] + // snippet-end:[ec2.cpp.delete_security_group.code] return outcome.IsSuccess(); } diff --git a/cpp/example_code/ec2/describe_addresses.cpp b/cpp/example_code/ec2/describe_addresses.cpp index e98184af56f..f4955a4f953 100644 --- a/cpp/example_code/ec2/describe_addresses.cpp +++ b/cpp/example_code/ec2/describe_addresses.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,14 +12,14 @@ * **/ -//snippet-start:[ec2.cpp.describe_addresses.inc] +// snippet-start:[ec2.cpp.describe_addresses.inc] #include #include #include #include #include #include -//snippet-end:[ec2.cpp.describe_addresses.inc] +// snippet-end:[ec2.cpp.describe_addresses.inc] #include "ec2_samples.h" //! Describe all Elastic IP addresses. diff --git a/cpp/example_code/ec2/describe_instances.cpp b/cpp/example_code/ec2/describe_instances.cpp index 68893732d59..23929659be6 100644 --- a/cpp/example_code/ec2/describe_instances.cpp +++ b/cpp/example_code/ec2/describe_instances.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,14 +12,14 @@ * **/ -//snippet-start:[ec2.cpp.describe_instances.inc] +// snippet-start:[ec2.cpp.describe_instances.inc] #include #include #include #include #include #include -//snippet-end:[ec2.cpp.describe_instances.inc] +// snippet-end:[ec2.cpp.describe_instances.inc] #include "ec2_samples.h" //! Describe all Amazon Elastic Compute Cloud (Amazon EC2) instances associated with an account. diff --git a/cpp/example_code/ec2/describe_key_pairs.cpp b/cpp/example_code/ec2/describe_key_pairs.cpp index db67013529f..86b57104987 100644 --- a/cpp/example_code/ec2/describe_key_pairs.cpp +++ b/cpp/example_code/ec2/describe_key_pairs.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,14 +12,14 @@ * **/ -//snippet-start:[ec2.cpp.describe_key_pairs.inc] +// snippet-start:[ec2.cpp.describe_key_pairs.inc] #include #include #include #include #include #include -//snippet-end:[ec2.cpp.describe_key_pairs.inc] +// snippet-end:[ec2.cpp.describe_key_pairs.inc] #include "ec2_samples.h" //! Describe all Amazon Elastic Compute Cloud (Amazon EC2) instance key pairs. diff --git a/cpp/example_code/ec2/describe_regions_and_zones.cpp b/cpp/example_code/ec2/describe_regions_and_zones.cpp index 856604c954a..7eddebfc5b6 100644 --- a/cpp/example_code/ec2/describe_regions_and_zones.cpp +++ b/cpp/example_code/ec2/describe_regions_and_zones.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,16 +12,16 @@ * **/ -//snippet-start:[ec2.cpp.describe_regions.inc] +// snippet-start:[ec2.cpp.describe_regions.inc] #include #include #include #include -//snippet-end:[ec2.cpp.describe_regions.inc] -//snippet-start:[ec2.cpp.describe_zones.inc] +// snippet-end:[ec2.cpp.describe_regions.inc] +// snippet-start:[ec2.cpp.describe_zones.inc] #include #include -//snippet-end:[ec2.cpp.describe_zones.inc] +// snippet-end:[ec2.cpp.describe_zones.inc] #include #include #include "ec2_samples.h" diff --git a/cpp/example_code/ec2/describe_security_groups.cpp b/cpp/example_code/ec2/describe_security_groups.cpp index 0f60b71b33e..1ab08d5bb9f 100644 --- a/cpp/example_code/ec2/describe_security_groups.cpp +++ b/cpp/example_code/ec2/describe_security_groups.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,14 +12,14 @@ * **/ -//snippet-start:[ec2.cpp.describe_security_groups.inc] +// snippet-start:[ec2.cpp.describe_security_groups.inc] #include #include #include #include #include #include -//snippet-end:[ec2.cpp.describe_security_groups.inc] +// snippet-end:[ec2.cpp.describe_security_groups.inc] #include "ec2_samples.h" //! Describe all Amazon Elastic Compute Cloud (Amazon EC2) security groups, or a specific group. diff --git a/cpp/example_code/ec2/ec2_samples.h b/cpp/example_code/ec2/ec2_samples.h index 5b03c864e79..15b8a47b4b3 100644 --- a/cpp/example_code/ec2/ec2_samples.h +++ b/cpp/example_code/ec2/ec2_samples.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef EC2_EXAMPLES_EC2_SAMPLES_H diff --git a/cpp/example_code/ec2/hello_ec2/hello_ec2.cpp b/cpp/example_code/ec2/hello_ec2/hello_ec2.cpp index 0df88cd50e0..bf0bf48200a 100644 --- a/cpp/example_code/ec2/hello_ec2/hello_ec2.cpp +++ b/cpp/example_code/ec2/hello_ec2/hello_ec2.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/ec2/monitor_instance.cpp b/cpp/example_code/ec2/monitor_instance.cpp index b2468582268..f0e06773aab 100644 --- a/cpp/example_code/ec2/monitor_instance.cpp +++ b/cpp/example_code/ec2/monitor_instance.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,14 +12,14 @@ * **/ -//snippet-start:[ec2.cpp.monitor_instance.inc] +// snippet-start:[ec2.cpp.monitor_instance.inc] #include #include #include #include #include #include -//snippet-end:[ec2.cpp.monitor_instance.inc] +// snippet-end:[ec2.cpp.monitor_instance.inc] #include "ec2_samples.h" diff --git a/cpp/example_code/ec2/reboot_instance.cpp b/cpp/example_code/ec2/reboot_instance.cpp index aa2f02a3f13..cd1ab5db3c1 100644 --- a/cpp/example_code/ec2/reboot_instance.cpp +++ b/cpp/example_code/ec2/reboot_instance.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,12 +12,12 @@ * **/ -//snippet-start:[ec2.cpp.reboot_instance.inc] +// snippet-start:[ec2.cpp.reboot_instance.inc] #include #include #include #include -//snippet-end:[ec2.cpp.reboot_instance.inc] +// snippet-end:[ec2.cpp.reboot_instance.inc] #include "ec2_samples.h" //! Reboot an Amazon Elastic Compute Cloud (Amazon EC2) instance. diff --git a/cpp/example_code/ec2/release_address.cpp b/cpp/example_code/ec2/release_address.cpp index 5f25623064e..2c41ce318fe 100644 --- a/cpp/example_code/ec2/release_address.cpp +++ b/cpp/example_code/ec2/release_address.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,12 +12,12 @@ * **/ -//snippet-start:[ec2.cpp.release_address.inc] +// snippet-start:[ec2.cpp.release_address.inc] #include #include #include #include -//snippet-end:[ec2.cpp.release_address.inc] +// snippet-end:[ec2.cpp.release_address.inc] #include "ec2_samples.h" //! Release an Elastic IP address. diff --git a/cpp/example_code/ec2/start_stop_instance.cpp b/cpp/example_code/ec2/start_stop_instance.cpp index d57980791ee..2a3aeb07b7e 100644 --- a/cpp/example_code/ec2/start_stop_instance.cpp +++ b/cpp/example_code/ec2/start_stop_instance.cpp @@ -1,7 +1,6 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,16 +13,16 @@ SPDX-License-Identifier: Apache-2.0 * **/ -//snippet-start:[ec2.cpp.start_instance.inc] +// snippet-start:[ec2.cpp.start_instance.inc] #include #include #include #include -//snippet-end:[ec2.cpp.start_instance.inc] -//snippet-start:[ec2.cpp.stop_instance.inc] +// snippet-end:[ec2.cpp.start_instance.inc] +// snippet-start:[ec2.cpp.stop_instance.inc] #include #include -//snippet-end:[ec2.cpp.stop_instance.inc] +// snippet-end:[ec2.cpp.stop_instance.inc] #include #include "ec2_samples.h" diff --git a/cpp/example_code/ec2/terminate_instances.cpp b/cpp/example_code/ec2/terminate_instances.cpp index a817dd1c079..eeccf54d55a 100644 --- a/cpp/example_code/ec2/terminate_instances.cpp +++ b/cpp/example_code/ec2/terminate_instances.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/ec2/tests/ec2_gtests.cpp b/cpp/example_code/ec2/tests/ec2_gtests.cpp index 138222d4199..d2dab9633e8 100644 --- a/cpp/example_code/ec2/tests/ec2_gtests.cpp +++ b/cpp/example_code/ec2/tests/ec2_gtests.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "ec2_gtests.h" #include diff --git a/cpp/example_code/ec2/tests/ec2_gtests.h b/cpp/example_code/ec2/tests/ec2_gtests.h index 573f2c6cb71..6ad702b0053 100644 --- a/cpp/example_code/ec2/tests/ec2_gtests.h +++ b/cpp/example_code/ec2/tests/ec2_gtests.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef S3_EXAMPLES_S3_GTESTS_H diff --git a/cpp/example_code/ec2/tests/gtest_allocate_address.cpp b/cpp/example_code/ec2/tests/gtest_allocate_address.cpp index 826b249f424..bec76c3c114 100644 --- a/cpp/example_code/ec2/tests/gtest_allocate_address.cpp +++ b/cpp/example_code/ec2/tests/gtest_allocate_address.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ec2/tests/gtest_create_instance.cpp b/cpp/example_code/ec2/tests/gtest_create_instance.cpp index ebc12486e4d..3725ff0423e 100644 --- a/cpp/example_code/ec2/tests/gtest_create_instance.cpp +++ b/cpp/example_code/ec2/tests/gtest_create_instance.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ec2/tests/gtest_create_key_pair.cpp b/cpp/example_code/ec2/tests/gtest_create_key_pair.cpp index d34d04f799a..f6594f84a14 100644 --- a/cpp/example_code/ec2/tests/gtest_create_key_pair.cpp +++ b/cpp/example_code/ec2/tests/gtest_create_key_pair.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ec2/tests/gtest_create_security_group.cpp b/cpp/example_code/ec2/tests/gtest_create_security_group.cpp index 6afc71cc3ec..8b0e073ce5d 100644 --- a/cpp/example_code/ec2/tests/gtest_create_security_group.cpp +++ b/cpp/example_code/ec2/tests/gtest_create_security_group.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ec2/tests/gtest_delete_key_pair.cpp b/cpp/example_code/ec2/tests/gtest_delete_key_pair.cpp index 204a7d642ba..856162138be 100644 --- a/cpp/example_code/ec2/tests/gtest_delete_key_pair.cpp +++ b/cpp/example_code/ec2/tests/gtest_delete_key_pair.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ec2/tests/gtest_delete_security_group.cpp b/cpp/example_code/ec2/tests/gtest_delete_security_group.cpp index bb94d050058..5c3aa0e0384 100644 --- a/cpp/example_code/ec2/tests/gtest_delete_security_group.cpp +++ b/cpp/example_code/ec2/tests/gtest_delete_security_group.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ec2/tests/gtest_describe_addresses.cpp b/cpp/example_code/ec2/tests/gtest_describe_addresses.cpp index 2784e7e7c37..68f4a576b65 100644 --- a/cpp/example_code/ec2/tests/gtest_describe_addresses.cpp +++ b/cpp/example_code/ec2/tests/gtest_describe_addresses.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ec2/tests/gtest_describe_instances.cpp b/cpp/example_code/ec2/tests/gtest_describe_instances.cpp index 2a36d3ea67b..390ecf77c45 100644 --- a/cpp/example_code/ec2/tests/gtest_describe_instances.cpp +++ b/cpp/example_code/ec2/tests/gtest_describe_instances.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ec2/tests/gtest_describe_key_pairs.cpp b/cpp/example_code/ec2/tests/gtest_describe_key_pairs.cpp index 2c311de1247..fc9fc49e6ba 100644 --- a/cpp/example_code/ec2/tests/gtest_describe_key_pairs.cpp +++ b/cpp/example_code/ec2/tests/gtest_describe_key_pairs.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ec2/tests/gtest_describe_regions_and_zones.cpp b/cpp/example_code/ec2/tests/gtest_describe_regions_and_zones.cpp index e99e35d6d5e..d4e400824fc 100644 --- a/cpp/example_code/ec2/tests/gtest_describe_regions_and_zones.cpp +++ b/cpp/example_code/ec2/tests/gtest_describe_regions_and_zones.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ec2/tests/gtest_describe_security_groups.cpp b/cpp/example_code/ec2/tests/gtest_describe_security_groups.cpp index 01348a7ec54..7a82acbdc11 100644 --- a/cpp/example_code/ec2/tests/gtest_describe_security_groups.cpp +++ b/cpp/example_code/ec2/tests/gtest_describe_security_groups.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ec2/tests/gtest_monitor_instance.cpp b/cpp/example_code/ec2/tests/gtest_monitor_instance.cpp index 1753cfac25e..36612154263 100644 --- a/cpp/example_code/ec2/tests/gtest_monitor_instance.cpp +++ b/cpp/example_code/ec2/tests/gtest_monitor_instance.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ec2/tests/gtest_reboot_instance.cpp b/cpp/example_code/ec2/tests/gtest_reboot_instance.cpp index 0fc76e8a144..6b6b91b0497 100644 --- a/cpp/example_code/ec2/tests/gtest_reboot_instance.cpp +++ b/cpp/example_code/ec2/tests/gtest_reboot_instance.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ec2/tests/gtest_release_address.cpp b/cpp/example_code/ec2/tests/gtest_release_address.cpp index ac37eb2d98b..1634fe20aee 100644 --- a/cpp/example_code/ec2/tests/gtest_release_address.cpp +++ b/cpp/example_code/ec2/tests/gtest_release_address.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ec2/tests/gtest_start_stop_instance.cpp b/cpp/example_code/ec2/tests/gtest_start_stop_instance.cpp index af04d1c88ea..0e394574f8b 100644 --- a/cpp/example_code/ec2/tests/gtest_start_stop_instance.cpp +++ b/cpp/example_code/ec2/tests/gtest_start_stop_instance.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ec2/tests/gtest_terminate_instances.cpp b/cpp/example_code/ec2/tests/gtest_terminate_instances.cpp index 95e6449bb9d..e56accbebe9 100644 --- a/cpp/example_code/ec2/tests/gtest_terminate_instances.cpp +++ b/cpp/example_code/ec2/tests/gtest_terminate_instances.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ec2/tests/test_main.cpp b/cpp/example_code/ec2/tests/test_main.cpp index 00ed3e2b055..656f92cb221 100644 --- a/cpp/example_code/ec2/tests/test_main.cpp +++ b/cpp/example_code/ec2/tests/test_main.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "gtest/gtest.h" diff --git a/cpp/example_code/efs/create_file_system.cpp b/cpp/example_code/efs/create_file_system.cpp index 05cf742350a..bd9f3da60f6 100644 --- a/cpp/example_code/efs/create_file_system.cpp +++ b/cpp/example_code/efs/create_file_system.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[create_file_system.cpp demonstrates how to create an Amazon Elastic File System.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Elastic File System] -//snippet-service:[elasticfilesystem] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/efs/create_mount_target.cpp b/cpp/example_code/efs/create_mount_target.cpp index fd26c24a616..e3598f10a76 100644 --- a/cpp/example_code/efs/create_mount_target.cpp +++ b/cpp/example_code/efs/create_mount_target.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[create_mount_target.cpp demonstrates how to create a mount target for an Amazon Elastic File System.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Elastic File System] -//snippet-service:[elasticfilesystem] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/efs/delete_file_system.cpp b/cpp/example_code/efs/delete_file_system.cpp index d41ad79c1c8..ddb4a57f388 100644 --- a/cpp/example_code/efs/delete_file_system.cpp +++ b/cpp/example_code/efs/delete_file_system.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[delete_file_system.cpp demonstrates how to delete an Amazon Elastic File System.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Elastic File System] -//snippet-service:[elasticfilesystem] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/efs/update_file_system.cpp b/cpp/example_code/efs/update_file_system.cpp index 4bf60c5af45..494a956869a 100644 --- a/cpp/example_code/efs/update_file_system.cpp +++ b/cpp/example_code/efs/update_file_system.cpp @@ -1,24 +1,5 @@ -//snippet-sourcedescription:[update_file_system.cpp demonstrates how to update the configuration of an Amazon Elastic File System.] -//snippet-service:[elasticfilesystem] -//snippet-keyword:[Amazon Elastic File System] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include #include diff --git a/cpp/example_code/elasticache/add_tags_to_resource.cpp b/cpp/example_code/elasticache/add_tags_to_resource.cpp index e64831cc120..12fdbec5a9d 100644 --- a/cpp/example_code/elasticache/add_tags_to_resource.cpp +++ b/cpp/example_code/elasticache/add_tags_to_resource.cpp @@ -1,24 +1,5 @@ -//snippet-sourcedescription:[add_tags_to_resource.cpp demonstrates how to add a cost allocation tag to an Amazon ElastiCache resource.] -//snippet-service:[elasticache] -//snippet-keyword:[Amazon ElastiCache] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include #include diff --git a/cpp/example_code/elasticache/create_cache_cluster.cpp b/cpp/example_code/elasticache/create_cache_cluster.cpp index 55802b67bc9..8a16a606cda 100644 --- a/cpp/example_code/elasticache/create_cache_cluster.cpp +++ b/cpp/example_code/elasticache/create_cache_cluster.cpp @@ -1,26 +1,5 @@ - -//snippet-sourcedescription:[create_cache_cluster.cpp demonstrates how to create an Amazon ElastiCache cluster.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon ElastiCache] -//snippet-service:[elasticache] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] - - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/elasticache/delete_cache_cluster.cpp b/cpp/example_code/elasticache/delete_cache_cluster.cpp index 127258d514d..6478fcd9b52 100644 --- a/cpp/example_code/elasticache/delete_cache_cluster.cpp +++ b/cpp/example_code/elasticache/delete_cache_cluster.cpp @@ -1,29 +1,7 @@ - -//snippet-sourcedescription:[delete_cache_cluster.cpp demonstrates how to delete an Amazon ElastiCache cluster.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon ElastiCache] -//snippet-service:[elasticache] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] - - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/elasticache/modify_cache_cluster.cpp b/cpp/example_code/elasticache/modify_cache_cluster.cpp index dff166ba72e..9af15821649 100644 --- a/cpp/example_code/elasticache/modify_cache_cluster.cpp +++ b/cpp/example_code/elasticache/modify_cache_cluster.cpp @@ -1,26 +1,5 @@ - -//snippet-sourcedescription:[modify_cache_cluster.cpp demonstrates how to modify an Amazon ElastiCache cluster.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon ElastiCache] -//snippet-service:[elasticache] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] - - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/elasticfilesystem/create_file_system_with_modeled_exceptions.cpp b/cpp/example_code/elasticfilesystem/create_file_system_with_modeled_exceptions.cpp index 1a6dc3b44c0..40c2fc8d891 100644 --- a/cpp/example_code/elasticfilesystem/create_file_system_with_modeled_exceptions.cpp +++ b/cpp/example_code/elasticfilesystem/create_file_system_with_modeled_exceptions.cpp @@ -1,17 +1,8 @@ -//snippet-sourcedescription:[Upgrade AWS SDK for C++ to version 1.8 to build create_file_system_with_modeled_exception.cpp. This example demonstrates how to get modeled exception from CreateFileSystem operation outcome.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Elastic File System] -//snippet-service:[elasticfilesystem] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/eventbridge/put_events.cpp b/cpp/example_code/eventbridge/put_events.cpp index 3af5c66d608..2b45d8b2b99 100644 --- a/cpp/example_code/eventbridge/put_events.cpp +++ b/cpp/example_code/eventbridge/put_events.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 /* //////////////////////////////////////////////////////////////////////////// * Purpose: put_events.cpp demonstrates how to post an Amazon CloudWatch event. @@ -12,14 +12,14 @@ * Outputs: * The event is posted. * ///////////////////////////////////////////////////////////////////////// */ -//snippet-start:[cw.cpp.put_events.inc] +// snippet-start:[cw.cpp.put_events.inc] #include #include #include #include #include #include -//snippet-end:[cw.cpp.put_events.inc] +// snippet-end:[cw.cpp.put_events.inc] Aws::String MakeDetails(const Aws::String &key, const Aws::String& value) { diff --git a/cpp/example_code/eventbridge/put_rule.cpp b/cpp/example_code/eventbridge/put_rule.cpp index fe69a5dae03..f4307ccab88 100644 --- a/cpp/example_code/eventbridge/put_rule.cpp +++ b/cpp/example_code/eventbridge/put_rule.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 /* //////////////////////////////////////////////////////////////////////////// * Purpose: put_rule.cpp demonstrates how to create an Amazon CloudWatch Events routing rule. @@ -11,14 +11,14 @@ * Outputs: * The routing rule is created. * ///////////////////////////////////////////////////////////////////////// */ -//snippet-start:[cw.cpp.put_rule.inc] +// snippet-start:[cw.cpp.put_rule.inc] #include #include #include #include #include #include -//snippet-end:[cw.cpp.put_rule.inc] +// snippet-end:[cw.cpp.put_rule.inc] /** * Creates a cloud watch event-routing rule, based on command line input diff --git a/cpp/example_code/eventbridge/put_targets.cpp b/cpp/example_code/eventbridge/put_targets.cpp index 8bf193f9934..37f93309830 100644 --- a/cpp/example_code/eventbridge/put_targets.cpp +++ b/cpp/example_code/eventbridge/put_targets.cpp @@ -1,7 +1,5 @@ - // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 - +// SPDX-License-Identifier: Apache-2.0 /* //////////////////////////////////////////////////////////////////////////// * Purpose: put_targets.cpp demonstrates how to create an Amazon CloudWatch Events routing rule target. * @@ -14,14 +12,14 @@ * Outputs: * The routing rule target is created. * ///////////////////////////////////////////////////////////////////////// */ -//snippet-start:[cw.cpp.put_targets.inc] +// snippet-start:[cw.cpp.put_targets.inc] #include #include #include #include #include #include -//snippet-end:[cw.cpp.put_targets.inc] +// snippet-end:[cw.cpp.put_targets.inc] /** * Creates a cloud watch event routing rule target, based on command line input diff --git a/cpp/example_code/gamelift/GameLift-Unreal-game-server.cpp b/cpp/example_code/gamelift/GameLift-Unreal-game-server.cpp index b3768bc4b31..0281dbc4097 100644 --- a/cpp/example_code/gamelift/GameLift-Unreal-game-server.cpp +++ b/cpp/example_code/gamelift/GameLift-Unreal-game-server.cpp @@ -1,31 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[GameLift-Unreal-game-server.cs demonstrates a basic integration of Amazon GameLift into a game server built with Unreal Engine.] -// snippet-service:[gamelift] -// snippet-keyword:[Amazon GameLift] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[InitSDK] -//snippet-keyword:[ActivateGameSession] -//snippet-keyword:[ProcessReady] -//snippet-keyword:[ProcessEnding] -//snippet-keyword:[] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-12-12] -// snippet-sourceauthor:[AWS] // snippet-start:[gamelift.cpp.game-server.unreal] //This is an example of a simple integration with GameLift server SDK that makes game server diff --git a/cpp/example_code/glacier/create_vault.cpp b/cpp/example_code/glacier/create_vault.cpp index 80e4c60820d..ab4c3c3d943 100644 --- a/cpp/example_code/glacier/create_vault.cpp +++ b/cpp/example_code/glacier/create_vault.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[create_vault.cpp demonstrates how to create an Amazon Glacier vault.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Glacier] -//snippet-service:[glacier] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/glacier/upload_archive.cpp b/cpp/example_code/glacier/upload_archive.cpp index 93db1c89623..2f546158271 100644 --- a/cpp/example_code/glacier/upload_archive.cpp +++ b/cpp/example_code/glacier/upload_archive.cpp @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[upload_archive.cpp demonstrates how to upload a file to Amazon S3 Glacier.] -//snippet-service:[glacier] -//snippet-keyword:[Amazon S3 Glacier] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-sourcetype:[snippet] -//snippet-sourcedate:[2019-04-26] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. diff --git a/cpp/example_code/glacier/upload_archive_multipart.cpp b/cpp/example_code/glacier/upload_archive_multipart.cpp index 8c1f5629de9..8e34e013cb4 100644 --- a/cpp/example_code/glacier/upload_archive_multipart.cpp +++ b/cpp/example_code/glacier/upload_archive_multipart.cpp @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[upload_archive_multipart.cpp demonstrates how to perform a multipart upload to Amazon S3 Glacier.] -//snippet-service:[glacier] -//snippet-keyword:[Amazon S3 Glacier] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-sourcetype:[snippet] -//snippet-sourcedate:[2019-04-26] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. diff --git a/cpp/example_code/glue/glue_getting_started_scenario.cpp b/cpp/example_code/glue/glue_getting_started_scenario.cpp index cdb1ae33563..442c34f1041 100644 --- a/cpp/example_code/glue/glue_getting_started_scenario.cpp +++ b/cpp/example_code/glue/glue_getting_started_scenario.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. diff --git a/cpp/example_code/glue/glue_samples.h b/cpp/example_code/glue/glue_samples.h index 1b1103ba0a6..112d624074e 100644 --- a/cpp/example_code/glue/glue_samples.h +++ b/cpp/example_code/glue/glue_samples.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #ifndef GLUE_EXAMPLES_GLUE_SAMPLES_H #define GLUE_EXAMPLES_GLUE_SAMPLES_H diff --git a/cpp/example_code/glue/glue_utilities.cpp b/cpp/example_code/glue/glue_utilities.cpp index 2632b995051..ca7a79659c7 100644 --- a/cpp/example_code/glue/glue_utilities.cpp +++ b/cpp/example_code/glue/glue_utilities.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/glue/hello_glue/hello_glue.cpp b/cpp/example_code/glue/hello_glue/hello_glue.cpp index b85ebfcfaba..2e8dfa1ee82 100644 --- a/cpp/example_code/glue/hello_glue/hello_glue.cpp +++ b/cpp/example_code/glue/hello_glue/hello_glue.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/glue/tests/glue_gtests.cpp b/cpp/example_code/glue/tests/glue_gtests.cpp index c4ea22a7ec9..16e7cadb407 100644 --- a/cpp/example_code/glue/tests/glue_gtests.cpp +++ b/cpp/example_code/glue/tests/glue_gtests.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "glue_gtests.h" #include diff --git a/cpp/example_code/glue/tests/glue_gtests.h b/cpp/example_code/glue/tests/glue_gtests.h index f58fe2626b0..99ba24476e4 100644 --- a/cpp/example_code/glue/tests/glue_gtests.h +++ b/cpp/example_code/glue/tests/glue_gtests.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef S3_EXAMPLES_S3_GTESTS_H diff --git a/cpp/example_code/glue/tests/gtest_glue_getting_started_scenario.cpp b/cpp/example_code/glue/tests/gtest_glue_getting_started_scenario.cpp index fa0336ecde9..6d7a5f837ed 100644 --- a/cpp/example_code/glue/tests/gtest_glue_getting_started_scenario.cpp +++ b/cpp/example_code/glue/tests/gtest_glue_getting_started_scenario.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include "glue_samples.h" diff --git a/cpp/example_code/glue/tests/test_main.cpp b/cpp/example_code/glue/tests/test_main.cpp index 00ed3e2b055..656f92cb221 100644 --- a/cpp/example_code/glue/tests/test_main.cpp +++ b/cpp/example_code/glue/tests/test_main.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "gtest/gtest.h" diff --git a/cpp/example_code/guardduty/list_detectors.cpp b/cpp/example_code/guardduty/list_detectors.cpp index acd1afe864c..5aa3ac255f1 100644 --- a/cpp/example_code/guardduty/list_detectors.cpp +++ b/cpp/example_code/guardduty/list_detectors.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[list_detectors.cpp demonstrates how to list the detector IDs of enabled Amazon GuardDuty detectors.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon GuardDuty] -//snippet-service:[guardduty] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/guardduty/list_findings_with_finding_criteria.cpp b/cpp/example_code/guardduty/list_findings_with_finding_criteria.cpp index 5e7bc66c63d..e478020533f 100644 --- a/cpp/example_code/guardduty/list_findings_with_finding_criteria.cpp +++ b/cpp/example_code/guardduty/list_findings_with_finding_criteria.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[list_findings_with_finding_criteria.cpp demonstrates how to list Amazon GuardDuty findings using finding criteria.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon GuardDuty] -//snippet-service:[guardduty] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/iam/access_key_last_used.cpp b/cpp/example_code/iam/access_key_last_used.cpp index 3996e2391a3..cfd92e07e81 100644 --- a/cpp/example_code/iam/access_key_last_used.cpp +++ b/cpp/example_code/iam/access_key_last_used.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, @@ -19,14 +17,14 @@ * */ -//snippet-start:[iam.cpp.access_key_last_used.inc] +// snippet-start:[iam.cpp.access_key_last_used.inc] #include #include #include #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.access_key_last_used.inc] +// snippet-end:[iam.cpp.access_key_last_used.inc] //! Displays the last time an access key was used. /*! diff --git a/cpp/example_code/iam/attach_role_policy.cpp b/cpp/example_code/iam/attach_role_policy.cpp index e5f44995865..34678d1cd6f 100644 --- a/cpp/example_code/iam/attach_role_policy.cpp +++ b/cpp/example_code/iam/attach_role_policy.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. @@ -18,7 +16,7 @@ * */ -//snippet-start:[iam.cpp.attach_role_policy.inc] +// snippet-start:[iam.cpp.attach_role_policy.inc] #include #include #include @@ -27,7 +25,7 @@ #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.attach_role_policy.inc] +// snippet-end:[iam.cpp.attach_role_policy.inc] //! Attaches a policy to a role. /*! diff --git a/cpp/example_code/iam/create_access_key.cpp b/cpp/example_code/iam/create_access_key.cpp index 3851e442a55..0943909d2ae 100644 --- a/cpp/example_code/iam/create_access_key.cpp +++ b/cpp/example_code/iam/create_access_key.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, @@ -19,13 +17,13 @@ * */ -//snippet-start:[iam.cpp.create_access_key.inc] +// snippet-start:[iam.cpp.create_access_key.inc] #include #include #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.create_access_key.inc] +// snippet-end:[iam.cpp.create_access_key.inc] //! Creates an access key for an IAM user. /*! diff --git a/cpp/example_code/iam/create_account_alias.cpp b/cpp/example_code/iam/create_account_alias.cpp index 4ae47cbcd31..8fcc2bb0d5a 100644 --- a/cpp/example_code/iam/create_account_alias.cpp +++ b/cpp/example_code/iam/create_account_alias.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, @@ -19,13 +17,13 @@ * */ -//snippet-start:[iam.cpp.create_account_alias.inc] +// snippet-start:[iam.cpp.create_account_alias.inc] #include #include #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.create_account_alias.inc] +// snippet-end:[iam.cpp.create_account_alias.inc] //! Creates an alias for an AWS account. /*! diff --git a/cpp/example_code/iam/create_policy.cpp b/cpp/example_code/iam/create_policy.cpp index ee994ef1d9d..d12952d4375 100644 --- a/cpp/example_code/iam/create_policy.cpp +++ b/cpp/example_code/iam/create_policy.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, @@ -19,14 +17,14 @@ * */ -//snippet-start:[iam.cpp.create_policy.inc] +// snippet-start:[iam.cpp.create_policy.inc] #include #include #include #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.create_policy.inc] +// snippet-end:[iam.cpp.create_policy.inc] namespace AwsDoc { namespace IAM { @@ -68,7 +66,7 @@ Aws::String AwsDoc::IAM::createPolicy(const Aws::String &policyName, } // snippet-end:[iam.cpp.create_policy.code] -//snippet-start:[iam.cpp.build_policy.code] +// snippet-start:[iam.cpp.build_policy.code] Aws::String AwsDoc::IAM::BuildSamplePolicyDocument(const Aws::String &rsrc_arn) { std::stringstream stringStream; stringStream << "{" @@ -99,7 +97,7 @@ Aws::String AwsDoc::IAM::BuildSamplePolicyDocument(const Aws::String &rsrc_arn) return stringStream.str(); } -//snippet-end:[iam.cpp.build_policy.code] +// snippet-end:[iam.cpp.build_policy.code] /* * diff --git a/cpp/example_code/iam/create_role.cpp b/cpp/example_code/iam/create_role.cpp index ed58ba6835c..761dd0a9aac 100644 --- a/cpp/example_code/iam/create_role.cpp +++ b/cpp/example_code/iam/create_role.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, diff --git a/cpp/example_code/iam/create_user.cpp b/cpp/example_code/iam/create_user.cpp index 5b7773ccd6d..8e132709770 100644 --- a/cpp/example_code/iam/create_user.cpp +++ b/cpp/example_code/iam/create_user.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. @@ -18,17 +16,17 @@ * */ -//snippet-start:[iam.cpp.create_user.inc] +// snippet-start:[iam.cpp.create_user.inc] #include #include #include -//snippet-start:[iam.cpp.get_user.inc] +// snippet-start:[iam.cpp.get_user.inc] #include #include -//snippet-end:[iam.cpp.get_user.inc] +// snippet-end:[iam.cpp.get_user.inc] #include #include "iam_samples.h" -//snippet-end:[iam.cpp.create_user.inc] +// snippet-end:[iam.cpp.create_user.inc] //! Creates an IAM user. /*! diff --git a/cpp/example_code/iam/delete_access_key.cpp b/cpp/example_code/iam/delete_access_key.cpp index 02991921298..bb088814263 100644 --- a/cpp/example_code/iam/delete_access_key.cpp +++ b/cpp/example_code/iam/delete_access_key.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. @@ -18,13 +16,13 @@ * */ -//snippet-start:[iam.cpp.delete_access_key.inc] +// snippet-start:[iam.cpp.delete_access_key.inc] #include #include #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.delete_access_key.inc] +// snippet-end:[iam.cpp.delete_access_key.inc] //! Deletes an access key from an IAM user. /*! diff --git a/cpp/example_code/iam/delete_account_alias.cpp b/cpp/example_code/iam/delete_account_alias.cpp index def61859428..32a1fdfb2b4 100644 --- a/cpp/example_code/iam/delete_account_alias.cpp +++ b/cpp/example_code/iam/delete_account_alias.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, @@ -19,13 +17,13 @@ * */ -//snippet-start:[iam.cpp.delete_account_alias.inc] +// snippet-start:[iam.cpp.delete_account_alias.inc] #include #include #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.delete_account_alias.inc] +// snippet-end:[iam.cpp.delete_account_alias.inc] //! Deletes an alias from an AWS account. /*! diff --git a/cpp/example_code/iam/delete_policy.cpp b/cpp/example_code/iam/delete_policy.cpp index 41ed90397d8..d0d47dbdc15 100644 --- a/cpp/example_code/iam/delete_policy.cpp +++ b/cpp/example_code/iam/delete_policy.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, @@ -22,13 +20,13 @@ * */ -//snippet-start:[iam.cpp.delete_policy.inc] +// snippet-start:[iam.cpp.delete_policy.inc] #include #include #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.delete_policy.inc] +// snippet-end:[iam.cpp.delete_policy.inc] //! Deletes an IAM policy. /*! diff --git a/cpp/example_code/iam/delete_server_certificate.cpp b/cpp/example_code/iam/delete_server_certificate.cpp index 22059059dfa..1e35068349c 100644 --- a/cpp/example_code/iam/delete_server_certificate.cpp +++ b/cpp/example_code/iam/delete_server_certificate.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. @@ -18,13 +16,13 @@ * */ -//snippet-start:[iam.cpp.delete_server_cert.inc] +// snippet-start:[iam.cpp.delete_server_cert.inc] #include #include #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.delete_server_cert.inc] +// snippet-end:[iam.cpp.delete_server_cert.inc] //! Deletes an IAM server certificate. /*! diff --git a/cpp/example_code/iam/delete_user.cpp b/cpp/example_code/iam/delete_user.cpp index 6ede7a92a3a..4a848c333c4 100644 --- a/cpp/example_code/iam/delete_user.cpp +++ b/cpp/example_code/iam/delete_user.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. @@ -21,7 +19,7 @@ * */ -//snippet-start:[iam.cpp.delete_user.inc] +// snippet-start:[iam.cpp.delete_user.inc] #include #include #include @@ -29,7 +27,7 @@ #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.delete_user.inc] +// snippet-end:[iam.cpp.delete_user.inc] //! Deletes an IAM user. /*! diff --git a/cpp/example_code/iam/detach_role_policy.cpp b/cpp/example_code/iam/detach_role_policy.cpp index 71b94602370..86e111054a3 100644 --- a/cpp/example_code/iam/detach_role_policy.cpp +++ b/cpp/example_code/iam/detach_role_policy.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. @@ -18,7 +16,7 @@ * */ -//snippet-start:[iam.cpp.detach_role_policy.inc] +// snippet-start:[iam.cpp.detach_role_policy.inc] #include #include #include @@ -26,7 +24,7 @@ #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.detach_role_policy.inc] +// snippet-end:[iam.cpp.detach_role_policy.inc] //! Detaches a policy from a role. /*! diff --git a/cpp/example_code/iam/get_policy.cpp b/cpp/example_code/iam/get_policy.cpp index e548276e20d..b09b6b78b94 100644 --- a/cpp/example_code/iam/get_policy.cpp +++ b/cpp/example_code/iam/get_policy.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. @@ -18,14 +16,14 @@ * */ -//snippet-start:[iam.cpp.get_policy.inc] +// snippet-start:[iam.cpp.get_policy.inc] #include #include #include #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.get_policy.inc] +// snippet-end:[iam.cpp.get_policy.inc] //! Gets an IAM policy's information. /*! diff --git a/cpp/example_code/iam/get_server_certificate.cpp b/cpp/example_code/iam/get_server_certificate.cpp index 987450df98e..242e5764456 100644 --- a/cpp/example_code/iam/get_server_certificate.cpp +++ b/cpp/example_code/iam/get_server_certificate.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. @@ -18,14 +16,14 @@ * */ -//snippet-start:[iam.cpp.get_server_cert.inc] +// snippet-start:[iam.cpp.get_server_cert.inc] #include #include #include #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.get_server_cert.inc] +// snippet-end:[iam.cpp.get_server_cert.inc] //! Gets a server certificate. /*! diff --git a/cpp/example_code/iam/hello_iam/hello_iam.cpp b/cpp/example_code/iam/hello_iam/hello_iam.cpp index 8d450008002..e426917d89c 100644 --- a/cpp/example_code/iam/hello_iam/hello_iam.cpp +++ b/cpp/example_code/iam/hello_iam/hello_iam.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/iam/iam_create_user_assume_role_scenario.cpp b/cpp/example_code/iam/iam_create_user_assume_role_scenario.cpp index 2742e400ab2..971a94846ed 100644 --- a/cpp/example_code/iam/iam_create_user_assume_role_scenario.cpp +++ b/cpp/example_code/iam/iam_create_user_assume_role_scenario.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. diff --git a/cpp/example_code/iam/iam_samples.h b/cpp/example_code/iam/iam_samples.h index b5884bfdbe7..e289a208bc9 100644 --- a/cpp/example_code/iam/iam_samples.h +++ b/cpp/example_code/iam/iam_samples.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once diff --git a/cpp/example_code/iam/list_access_keys.cpp b/cpp/example_code/iam/list_access_keys.cpp index 6062adf492a..2ae63d45fbc 100644 --- a/cpp/example_code/iam/list_access_keys.cpp +++ b/cpp/example_code/iam/list_access_keys.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, @@ -19,7 +17,7 @@ * */ -//snippet-start:[iam.cpp.list_access_keys.inc] +// snippet-start:[iam.cpp.list_access_keys.inc] #include #include #include @@ -27,7 +25,7 @@ #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.list_access_keys.inc] +// snippet-end:[iam.cpp.list_access_keys.inc] //! Lists all access keys associated with an IAM user. /*! diff --git a/cpp/example_code/iam/list_account_aliases.cpp b/cpp/example_code/iam/list_account_aliases.cpp index a41ffec74b8..445433ec313 100644 --- a/cpp/example_code/iam/list_account_aliases.cpp +++ b/cpp/example_code/iam/list_account_aliases.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, @@ -19,7 +17,7 @@ * */ -//snippet-start:[iam.cpp.list_account_aliases.inc] +// snippet-start:[iam.cpp.list_account_aliases.inc] #include #include #include @@ -27,7 +25,7 @@ #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.list_account_aliases.inc] +// snippet-end:[iam.cpp.list_account_aliases.inc] //! Lists all account aliases associated with an AWS account. /*! diff --git a/cpp/example_code/iam/list_policies.cpp b/cpp/example_code/iam/list_policies.cpp index 9e41d5074e3..48b548b3f4b 100644 --- a/cpp/example_code/iam/list_policies.cpp +++ b/cpp/example_code/iam/list_policies.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. @@ -18,7 +16,7 @@ * */ -//snippet-start:[iam.cpp.list_policies.inc] +// snippet-start:[iam.cpp.list_policies.inc] #include #include #include @@ -26,7 +24,7 @@ #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.list_policies.inc] +// snippet-end:[iam.cpp.list_policies.inc] // ! Lists all IAM policies. /*! diff --git a/cpp/example_code/iam/list_server_certificates.cpp b/cpp/example_code/iam/list_server_certificates.cpp index 1c1baefd529..f8f3594baae 100644 --- a/cpp/example_code/iam/list_server_certificates.cpp +++ b/cpp/example_code/iam/list_server_certificates.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, @@ -19,14 +17,14 @@ * */ -//snippet-start:[iam.cpp.list_server_certs.inc] +// snippet-start:[iam.cpp.list_server_certs.inc] #include #include #include #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.list_server_certs.inc] +// snippet-end:[iam.cpp.list_server_certs.inc] //! List all server certificates. /*! diff --git a/cpp/example_code/iam/list_users.cpp b/cpp/example_code/iam/list_users.cpp index 17a684ead12..a922988028d 100644 --- a/cpp/example_code/iam/list_users.cpp +++ b/cpp/example_code/iam/list_users.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. @@ -18,14 +16,14 @@ * */ -//snippet-start:[iam.cpp.list_users.inc] +// snippet-start:[iam.cpp.list_users.inc] #include #include #include #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.list_users.inc] +// snippet-end:[iam.cpp.list_users.inc] //! List all IAM users. /*! diff --git a/cpp/example_code/iam/put_role_policy.cpp b/cpp/example_code/iam/put_role_policy.cpp index 808eb76a312..810c694b42e 100644 --- a/cpp/example_code/iam/put_role_policy.cpp +++ b/cpp/example_code/iam/put_role_policy.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. diff --git a/cpp/example_code/iam/tests/gtest_access_key_last_used.cpp b/cpp/example_code/iam/tests/gtest_access_key_last_used.cpp index 4a1d658b6f6..3f551443b7d 100644 --- a/cpp/example_code/iam/tests/gtest_access_key_last_used.cpp +++ b/cpp/example_code/iam/tests/gtest_access_key_last_used.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_attach_role_policy.cpp b/cpp/example_code/iam/tests/gtest_attach_role_policy.cpp index b4e1357e8a7..481949d34de 100644 --- a/cpp/example_code/iam/tests/gtest_attach_role_policy.cpp +++ b/cpp/example_code/iam/tests/gtest_attach_role_policy.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_create_access_key.cpp b/cpp/example_code/iam/tests/gtest_create_access_key.cpp index 6fdb4478c89..8db8ebb86c0 100644 --- a/cpp/example_code/iam/tests/gtest_create_access_key.cpp +++ b/cpp/example_code/iam/tests/gtest_create_access_key.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_create_account_alias.cpp b/cpp/example_code/iam/tests/gtest_create_account_alias.cpp index ae9c9edafea..c2e5bb2ddfa 100644 --- a/cpp/example_code/iam/tests/gtest_create_account_alias.cpp +++ b/cpp/example_code/iam/tests/gtest_create_account_alias.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_create_policy.cpp b/cpp/example_code/iam/tests/gtest_create_policy.cpp index b8ff6225fa2..c84dc611461 100644 --- a/cpp/example_code/iam/tests/gtest_create_policy.cpp +++ b/cpp/example_code/iam/tests/gtest_create_policy.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_create_role.cpp b/cpp/example_code/iam/tests/gtest_create_role.cpp index a658f5d6306..ef686430738 100644 --- a/cpp/example_code/iam/tests/gtest_create_role.cpp +++ b/cpp/example_code/iam/tests/gtest_create_role.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_create_user.cpp b/cpp/example_code/iam/tests/gtest_create_user.cpp index 106020c705e..6dc8fe0f2ff 100644 --- a/cpp/example_code/iam/tests/gtest_create_user.cpp +++ b/cpp/example_code/iam/tests/gtest_create_user.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_delete_access_key.cpp b/cpp/example_code/iam/tests/gtest_delete_access_key.cpp index 2dc7fbb4920..2b07c7b18b9 100644 --- a/cpp/example_code/iam/tests/gtest_delete_access_key.cpp +++ b/cpp/example_code/iam/tests/gtest_delete_access_key.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_delete_account_alias.cpp b/cpp/example_code/iam/tests/gtest_delete_account_alias.cpp index 547230b7ac0..c1253b39888 100644 --- a/cpp/example_code/iam/tests/gtest_delete_account_alias.cpp +++ b/cpp/example_code/iam/tests/gtest_delete_account_alias.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_delete_policy.cpp b/cpp/example_code/iam/tests/gtest_delete_policy.cpp index bd4c6071024..0f3fb892d9c 100644 --- a/cpp/example_code/iam/tests/gtest_delete_policy.cpp +++ b/cpp/example_code/iam/tests/gtest_delete_policy.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_delete_server_certificate.cpp b/cpp/example_code/iam/tests/gtest_delete_server_certificate.cpp index 3e47ab1a573..fe3ada116c6 100644 --- a/cpp/example_code/iam/tests/gtest_delete_server_certificate.cpp +++ b/cpp/example_code/iam/tests/gtest_delete_server_certificate.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_delete_user.cpp b/cpp/example_code/iam/tests/gtest_delete_user.cpp index 8d53b7ebae9..68f8da42647 100644 --- a/cpp/example_code/iam/tests/gtest_delete_user.cpp +++ b/cpp/example_code/iam/tests/gtest_delete_user.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_detach_role_policy.cpp b/cpp/example_code/iam/tests/gtest_detach_role_policy.cpp index 1e9ceb81494..1a7170b7d32 100644 --- a/cpp/example_code/iam/tests/gtest_detach_role_policy.cpp +++ b/cpp/example_code/iam/tests/gtest_detach_role_policy.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_get_policy.cpp b/cpp/example_code/iam/tests/gtest_get_policy.cpp index aa0663813fd..945c49adac8 100644 --- a/cpp/example_code/iam/tests/gtest_get_policy.cpp +++ b/cpp/example_code/iam/tests/gtest_get_policy.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_get_server_certificate.cpp b/cpp/example_code/iam/tests/gtest_get_server_certificate.cpp index 67beb5bcd86..ee62532d5e2 100644 --- a/cpp/example_code/iam/tests/gtest_get_server_certificate.cpp +++ b/cpp/example_code/iam/tests/gtest_get_server_certificate.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_iam_create_user_assume_role_scenario.cpp b/cpp/example_code/iam/tests/gtest_iam_create_user_assume_role_scenario.cpp index a59668619b2..a1986366720 100644 --- a/cpp/example_code/iam/tests/gtest_iam_create_user_assume_role_scenario.cpp +++ b/cpp/example_code/iam/tests/gtest_iam_create_user_assume_role_scenario.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_list_access_keys.cpp b/cpp/example_code/iam/tests/gtest_list_access_keys.cpp index 2a53c37a4f9..554a44f0ca1 100644 --- a/cpp/example_code/iam/tests/gtest_list_access_keys.cpp +++ b/cpp/example_code/iam/tests/gtest_list_access_keys.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_list_account_aliases.cpp b/cpp/example_code/iam/tests/gtest_list_account_aliases.cpp index 95b17f0df30..5fb56c83222 100644 --- a/cpp/example_code/iam/tests/gtest_list_account_aliases.cpp +++ b/cpp/example_code/iam/tests/gtest_list_account_aliases.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_list_policies.cpp b/cpp/example_code/iam/tests/gtest_list_policies.cpp index 99035dfeb4a..62c2dad6a9d 100644 --- a/cpp/example_code/iam/tests/gtest_list_policies.cpp +++ b/cpp/example_code/iam/tests/gtest_list_policies.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_list_server_certificates.cpp b/cpp/example_code/iam/tests/gtest_list_server_certificates.cpp index 751bf551239..a8ff1d01e9f 100644 --- a/cpp/example_code/iam/tests/gtest_list_server_certificates.cpp +++ b/cpp/example_code/iam/tests/gtest_list_server_certificates.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_list_users.cpp b/cpp/example_code/iam/tests/gtest_list_users.cpp index b5bc21b1f0b..8ab411cd6e4 100644 --- a/cpp/example_code/iam/tests/gtest_list_users.cpp +++ b/cpp/example_code/iam/tests/gtest_list_users.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_put_role_policy.cpp b/cpp/example_code/iam/tests/gtest_put_role_policy.cpp index 201fbdede0c..2e6d382f44f 100644 --- a/cpp/example_code/iam/tests/gtest_put_role_policy.cpp +++ b/cpp/example_code/iam/tests/gtest_put_role_policy.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_update_access_key.cpp b/cpp/example_code/iam/tests/gtest_update_access_key.cpp index e99cc15f88a..5b82ce7af63 100644 --- a/cpp/example_code/iam/tests/gtest_update_access_key.cpp +++ b/cpp/example_code/iam/tests/gtest_update_access_key.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_update_server_certificate.cpp b/cpp/example_code/iam/tests/gtest_update_server_certificate.cpp index ba48e63390d..10dcd9ea645 100644 --- a/cpp/example_code/iam/tests/gtest_update_server_certificate.cpp +++ b/cpp/example_code/iam/tests/gtest_update_server_certificate.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/gtest_update_user.cpp b/cpp/example_code/iam/tests/gtest_update_user.cpp index 2220536154a..204d9d8e9fe 100644 --- a/cpp/example_code/iam/tests/gtest_update_user.cpp +++ b/cpp/example_code/iam/tests/gtest_update_user.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/iam/tests/iam_gtests.cpp b/cpp/example_code/iam/tests/iam_gtests.cpp index ce18f0a9ecf..95f04e8e619 100644 --- a/cpp/example_code/iam/tests/iam_gtests.cpp +++ b/cpp/example_code/iam/tests/iam_gtests.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "iam_gtests.h" #include diff --git a/cpp/example_code/iam/tests/iam_gtests.h b/cpp/example_code/iam/tests/iam_gtests.h index 0f6895c4fe8..8914ec7a5b7 100644 --- a/cpp/example_code/iam/tests/iam_gtests.h +++ b/cpp/example_code/iam/tests/iam_gtests.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef S3_EXAMPLES_S3_GTESTS_H diff --git a/cpp/example_code/iam/tests/test_main.cpp b/cpp/example_code/iam/tests/test_main.cpp index 00ed3e2b055..656f92cb221 100644 --- a/cpp/example_code/iam/tests/test_main.cpp +++ b/cpp/example_code/iam/tests/test_main.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "gtest/gtest.h" diff --git a/cpp/example_code/iam/update_access_key.cpp b/cpp/example_code/iam/update_access_key.cpp index 5d0b34515a7..0873f7feb3a 100644 --- a/cpp/example_code/iam/update_access_key.cpp +++ b/cpp/example_code/iam/update_access_key.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, @@ -19,13 +17,13 @@ * */ -//snippet-start:[iam.cpp.update_access_key.inc] +// snippet-start:[iam.cpp.update_access_key.inc] #include #include #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.update_access_key.inc] +// snippet-end:[iam.cpp.update_access_key.inc] static void printUsage(); diff --git a/cpp/example_code/iam/update_server_certificate.cpp b/cpp/example_code/iam/update_server_certificate.cpp index ec707dc4903..6d073bcdb9c 100644 --- a/cpp/example_code/iam/update_server_certificate.cpp +++ b/cpp/example_code/iam/update_server_certificate.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. @@ -18,13 +16,13 @@ * */ -//snippet-start:[iam.cpp.update_server_cert.inc] +// snippet-start:[iam.cpp.update_server_cert.inc] #include #include #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.update_server_cert.inc] +// snippet-end:[iam.cpp.update_server_cert.inc] //! Updates a server certificate name. /*! diff --git a/cpp/example_code/iam/update_user.cpp b/cpp/example_code/iam/update_user.cpp index 91ca1ac63b4..3a6d401bfbf 100644 --- a/cpp/example_code/iam/update_user.cpp +++ b/cpp/example_code/iam/update_user.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. @@ -18,13 +16,13 @@ * */ -//snippet-start:[iam.cpp.update_user.inc] +// snippet-start:[iam.cpp.update_user.inc] #include #include #include #include #include "iam_samples.h" -//snippet-end:[iam.cpp.update_user.inc] +// snippet-end:[iam.cpp.update_user.inc] //! Updates an IAM user's name. diff --git a/cpp/example_code/kinesis/put_get_records.cpp b/cpp/example_code/kinesis/put_get_records.cpp index dfca52720d3..8c0dfd94d22 100644 --- a/cpp/example_code/kinesis/put_get_records.cpp +++ b/cpp/example_code/kinesis/put_get_records.cpp @@ -1,28 +1,7 @@ - -//snippet-sourcedescription:[put_get_records.cpp demonstrates how to get and put records in an Amazon Kinesis data stream.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Kinesis Data Streams] -//snippet-service:[kinesis] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] - - -/* -Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -This file is 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/ - -This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -CONDITIONS OF ANY KIND, either express or implied. See the License for the -specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include #include diff --git a/cpp/example_code/lambda/cpp_lambda/calculator/main.cpp b/cpp/example_code/lambda/cpp_lambda/calculator/main.cpp index 542cb76b488..cf56091592e 100644 --- a/cpp/example_code/lambda/cpp_lambda/calculator/main.cpp +++ b/cpp/example_code/lambda/cpp_lambda/calculator/main.cpp @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include #include diff --git a/cpp/example_code/lambda/cpp_lambda/increment/main.cpp b/cpp/example_code/lambda/cpp_lambda/increment/main.cpp index ed98f861c60..49d4dce99e4 100644 --- a/cpp/example_code/lambda/cpp_lambda/increment/main.cpp +++ b/cpp/example_code/lambda/cpp_lambda/increment/main.cpp @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include #include diff --git a/cpp/example_code/lambda/get_started_with_functions_scenario.cpp b/cpp/example_code/lambda/get_started_with_functions_scenario.cpp index 6f1663dd35f..8b6940942b3 100644 --- a/cpp/example_code/lambda/get_started_with_functions_scenario.cpp +++ b/cpp/example_code/lambda/get_started_with_functions_scenario.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. diff --git a/cpp/example_code/lambda/hello_lambda/hello_lambda.cpp b/cpp/example_code/lambda/hello_lambda/hello_lambda.cpp index 1d68543e6fa..88266bb581e 100644 --- a/cpp/example_code/lambda/hello_lambda/hello_lambda.cpp +++ b/cpp/example_code/lambda/hello_lambda/hello_lambda.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/lambda/lambda_samples.h b/cpp/example_code/lambda/lambda_samples.h index 9ccd2125dec..53269fc2419 100644 --- a/cpp/example_code/lambda/lambda_samples.h +++ b/cpp/example_code/lambda/lambda_samples.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #ifndef LAMBDA_EXAMPLES_GTESTS_LAMBDA_SAMPLES_H #define LAMBDA_EXAMPLES_GTESTS_LAMBDA_SAMPLES_H diff --git a/cpp/example_code/lambda/tests/gtest_get_started_with_functions_scenario.cpp b/cpp/example_code/lambda/tests/gtest_get_started_with_functions_scenario.cpp index eb4f02b6203..d98be209682 100644 --- a/cpp/example_code/lambda/tests/gtest_get_started_with_functions_scenario.cpp +++ b/cpp/example_code/lambda/tests/gtest_get_started_with_functions_scenario.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/lambda/tests/lambda_gtests.cpp b/cpp/example_code/lambda/tests/lambda_gtests.cpp index ba546db2b1a..2db3b5f611a 100644 --- a/cpp/example_code/lambda/tests/lambda_gtests.cpp +++ b/cpp/example_code/lambda/tests/lambda_gtests.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "lambda_gtests.h" #include diff --git a/cpp/example_code/lambda/tests/lambda_gtests.h b/cpp/example_code/lambda/tests/lambda_gtests.h index 653f5e58d56..f0b501cbc03 100644 --- a/cpp/example_code/lambda/tests/lambda_gtests.h +++ b/cpp/example_code/lambda/tests/lambda_gtests.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef S3_EXAMPLES_S3_GTESTS_H diff --git a/cpp/example_code/lambda/tests/test_main.cpp b/cpp/example_code/lambda/tests/test_main.cpp index 00ed3e2b055..656f92cb221 100644 --- a/cpp/example_code/lambda/tests/test_main.cpp +++ b/cpp/example_code/lambda/tests/test_main.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "gtest/gtest.h" diff --git a/cpp/example_code/mediaconvert/create_job.cpp b/cpp/example_code/mediaconvert/create_job.cpp index 32368e1adfc..e180b0c998a 100644 --- a/cpp/example_code/mediaconvert/create_job.cpp +++ b/cpp/example_code/mediaconvert/create_job.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/mediaconvert/describe_endpoints.cpp b/cpp/example_code/mediaconvert/describe_endpoints.cpp index b26c64d7b47..28fa6d7c7fe 100644 --- a/cpp/example_code/mediaconvert/describe_endpoints.cpp +++ b/cpp/example_code/mediaconvert/describe_endpoints.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, *including your credentials. diff --git a/cpp/example_code/mediaconvert/get_job.cpp b/cpp/example_code/mediaconvert/get_job.cpp index b06d7c4c6fa..d55c10287c3 100644 --- a/cpp/example_code/mediaconvert/get_job.cpp +++ b/cpp/example_code/mediaconvert/get_job.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/mediaconvert/list_jobs.cpp b/cpp/example_code/mediaconvert/list_jobs.cpp index 7ae0cde8dd9..984a047e0d1 100644 --- a/cpp/example_code/mediaconvert/list_jobs.cpp +++ b/cpp/example_code/mediaconvert/list_jobs.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/mediaconvert/mediaconvert_samples.h b/cpp/example_code/mediaconvert/mediaconvert_samples.h index be29cfe1781..51970d82eb0 100644 --- a/cpp/example_code/mediaconvert/mediaconvert_samples.h +++ b/cpp/example_code/mediaconvert/mediaconvert_samples.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef MEDIACONVERT_EXAMPLES_MEDIACONVERT_SAMPLES_H diff --git a/cpp/example_code/mediaconvert/tests/MediaConvert_gtests.cpp b/cpp/example_code/mediaconvert/tests/MediaConvert_gtests.cpp index 7febfc9306a..33014aef930 100644 --- a/cpp/example_code/mediaconvert/tests/MediaConvert_gtests.cpp +++ b/cpp/example_code/mediaconvert/tests/MediaConvert_gtests.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "MediaConvert_gtests.h" #include diff --git a/cpp/example_code/mediaconvert/tests/MediaConvert_gtests.h b/cpp/example_code/mediaconvert/tests/MediaConvert_gtests.h index 495f0ad9a04..01b6c87b1f7 100644 --- a/cpp/example_code/mediaconvert/tests/MediaConvert_gtests.h +++ b/cpp/example_code/mediaconvert/tests/MediaConvert_gtests.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef S3_EXAMPLES_S3_GTESTS_H diff --git a/cpp/example_code/mediaconvert/tests/gtest_create_job.cpp b/cpp/example_code/mediaconvert/tests/gtest_create_job.cpp index 0a161b45322..9bab99529ae 100644 --- a/cpp/example_code/mediaconvert/tests/gtest_create_job.cpp +++ b/cpp/example_code/mediaconvert/tests/gtest_create_job.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/mediaconvert/tests/gtest_describe_endpoints.cpp b/cpp/example_code/mediaconvert/tests/gtest_describe_endpoints.cpp index eb0b16f0375..d014bb83a33 100644 --- a/cpp/example_code/mediaconvert/tests/gtest_describe_endpoints.cpp +++ b/cpp/example_code/mediaconvert/tests/gtest_describe_endpoints.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/mediaconvert/tests/gtest_get_job.cpp b/cpp/example_code/mediaconvert/tests/gtest_get_job.cpp index 47629ad43cf..8c4f85ea360 100644 --- a/cpp/example_code/mediaconvert/tests/gtest_get_job.cpp +++ b/cpp/example_code/mediaconvert/tests/gtest_get_job.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/mediaconvert/tests/gtest_list_jobs.cpp b/cpp/example_code/mediaconvert/tests/gtest_list_jobs.cpp index 1d766c4c4a0..83f1d43e9fd 100644 --- a/cpp/example_code/mediaconvert/tests/gtest_list_jobs.cpp +++ b/cpp/example_code/mediaconvert/tests/gtest_list_jobs.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/mediaconvert/tests/test_main.cpp b/cpp/example_code/mediaconvert/tests/test_main.cpp index 00ed3e2b055..656f92cb221 100644 --- a/cpp/example_code/mediaconvert/tests/test_main.cpp +++ b/cpp/example_code/mediaconvert/tests/test_main.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "gtest/gtest.h" diff --git a/cpp/example_code/mediaconvert/utils.cpp b/cpp/example_code/mediaconvert/utils.cpp index 993b610cb79..ff4952fdd1a 100644 --- a/cpp/example_code/mediaconvert/utils.cpp +++ b/cpp/example_code/mediaconvert/utils.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/medical-imaging/delete_image_set.cpp b/cpp/example_code/medical-imaging/delete_image_set.cpp index f8fe2cc2ee0..0a4da2b75bc 100644 --- a/cpp/example_code/medical-imaging/delete_image_set.cpp +++ b/cpp/example_code/medical-imaging/delete_image_set.cpp @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include diff --git a/cpp/example_code/medical-imaging/get_dicom_import_job.cpp b/cpp/example_code/medical-imaging/get_dicom_import_job.cpp index b431b7abbcb..cb849f8beb4 100644 --- a/cpp/example_code/medical-imaging/get_dicom_import_job.cpp +++ b/cpp/example_code/medical-imaging/get_dicom_import_job.cpp @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include diff --git a/cpp/example_code/medical-imaging/get_image_frame.cpp b/cpp/example_code/medical-imaging/get_image_frame.cpp index fe94f5b2fa2..5b71fb81e53 100644 --- a/cpp/example_code/medical-imaging/get_image_frame.cpp +++ b/cpp/example_code/medical-imaging/get_image_frame.cpp @@ -1,7 +1,5 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/medical-imaging/get_image_set_metadata.cpp b/cpp/example_code/medical-imaging/get_image_set_metadata.cpp index 7f5514b80f0..4b4fb570476 100644 --- a/cpp/example_code/medical-imaging/get_image_set_metadata.cpp +++ b/cpp/example_code/medical-imaging/get_image_set_metadata.cpp @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include diff --git a/cpp/example_code/medical-imaging/hello_health_imaging/hello_health_imaging.cpp b/cpp/example_code/medical-imaging/hello_health_imaging/hello_health_imaging.cpp index 5a2951af08a..f357b8d0956 100644 --- a/cpp/example_code/medical-imaging/hello_health_imaging/hello_health_imaging.cpp +++ b/cpp/example_code/medical-imaging/hello_health_imaging/hello_health_imaging.cpp @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. diff --git a/cpp/example_code/medical-imaging/imaging_set_and_frames_workflow/medical_image_sets_and_frames_workflow.cpp b/cpp/example_code/medical-imaging/imaging_set_and_frames_workflow/medical_image_sets_and_frames_workflow.cpp index 8f34c2daf93..f1b2b010dcb 100644 --- a/cpp/example_code/medical-imaging/imaging_set_and_frames_workflow/medical_image_sets_and_frames_workflow.cpp +++ b/cpp/example_code/medical-imaging/imaging_set_and_frames_workflow/medical_image_sets_and_frames_workflow.cpp @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/medical-imaging/medical-imaging_samples.h b/cpp/example_code/medical-imaging/medical-imaging_samples.h index 294a14a6341..3459c6cb027 100644 --- a/cpp/example_code/medical-imaging/medical-imaging_samples.h +++ b/cpp/example_code/medical-imaging/medical-imaging_samples.h @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once diff --git a/cpp/example_code/medical-imaging/search_image_sets.cpp b/cpp/example_code/medical-imaging/search_image_sets.cpp index 9c864722711..2a17f6d1e19 100644 --- a/cpp/example_code/medical-imaging/search_image_sets.cpp +++ b/cpp/example_code/medical-imaging/search_image_sets.cpp @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include diff --git a/cpp/example_code/medical-imaging/start_dicom_import_job.cpp b/cpp/example_code/medical-imaging/start_dicom_import_job.cpp index eed0ea35011..72b893789cd 100644 --- a/cpp/example_code/medical-imaging/start_dicom_import_job.cpp +++ b/cpp/example_code/medical-imaging/start_dicom_import_job.cpp @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include diff --git a/cpp/example_code/medical-imaging/tests/gtest_delete_image_set.cpp b/cpp/example_code/medical-imaging/tests/gtest_delete_image_set.cpp index f235618dbc1..2ebed99a172 100644 --- a/cpp/example_code/medical-imaging/tests/gtest_delete_image_set.cpp +++ b/cpp/example_code/medical-imaging/tests/gtest_delete_image_set.cpp @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. diff --git a/cpp/example_code/medical-imaging/tests/gtest_get_dicom_import_job.cpp b/cpp/example_code/medical-imaging/tests/gtest_get_dicom_import_job.cpp index ae9171ce14b..302e43f7a4f 100644 --- a/cpp/example_code/medical-imaging/tests/gtest_get_dicom_import_job.cpp +++ b/cpp/example_code/medical-imaging/tests/gtest_get_dicom_import_job.cpp @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. diff --git a/cpp/example_code/medical-imaging/tests/gtest_get_image_frame.cpp b/cpp/example_code/medical-imaging/tests/gtest_get_image_frame.cpp index 494fb8fdf14..2da9c539ada 100644 --- a/cpp/example_code/medical-imaging/tests/gtest_get_image_frame.cpp +++ b/cpp/example_code/medical-imaging/tests/gtest_get_image_frame.cpp @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. diff --git a/cpp/example_code/medical-imaging/tests/gtest_get_image_set_metadata.cpp b/cpp/example_code/medical-imaging/tests/gtest_get_image_set_metadata.cpp index 5de09ef3830..67b8b6ec697 100644 --- a/cpp/example_code/medical-imaging/tests/gtest_get_image_set_metadata.cpp +++ b/cpp/example_code/medical-imaging/tests/gtest_get_image_set_metadata.cpp @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. diff --git a/cpp/example_code/medical-imaging/tests/gtest_search_image_sets.cpp b/cpp/example_code/medical-imaging/tests/gtest_search_image_sets.cpp index f5ddc828111..fd63149392b 100644 --- a/cpp/example_code/medical-imaging/tests/gtest_search_image_sets.cpp +++ b/cpp/example_code/medical-imaging/tests/gtest_search_image_sets.cpp @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. diff --git a/cpp/example_code/medical-imaging/tests/gtest_start_dicom_import_job.cpp b/cpp/example_code/medical-imaging/tests/gtest_start_dicom_import_job.cpp index 26433fdf36e..c2115b85ad7 100644 --- a/cpp/example_code/medical-imaging/tests/gtest_start_dicom_import_job.cpp +++ b/cpp/example_code/medical-imaging/tests/gtest_start_dicom_import_job.cpp @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. diff --git a/cpp/example_code/medical-imaging/tests/medical-imaging_gtests.cpp b/cpp/example_code/medical-imaging/tests/medical-imaging_gtests.cpp index ae9bbb8d708..170707fb78d 100644 --- a/cpp/example_code/medical-imaging/tests/medical-imaging_gtests.cpp +++ b/cpp/example_code/medical-imaging/tests/medical-imaging_gtests.cpp @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "medical-imaging_gtests.h" diff --git a/cpp/example_code/medical-imaging/tests/medical-imaging_gtests.h b/cpp/example_code/medical-imaging/tests/medical-imaging_gtests.h index 0b699d69426..ced467458ce 100644 --- a/cpp/example_code/medical-imaging/tests/medical-imaging_gtests.h +++ b/cpp/example_code/medical-imaging/tests/medical-imaging_gtests.h @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once diff --git a/cpp/example_code/medical-imaging/tests/test_main.cpp b/cpp/example_code/medical-imaging/tests/test_main.cpp index 486f0f7e9e6..c7e39127094 100644 --- a/cpp/example_code/medical-imaging/tests/test_main.cpp +++ b/cpp/example_code/medical-imaging/tests/test_main.cpp @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "gtest/gtest.h" diff --git a/cpp/example_code/neptune/create_db_cluster.cpp b/cpp/example_code/neptune/create_db_cluster.cpp index 797e7579d49..ffe7464e2ff 100644 --- a/cpp/example_code/neptune/create_db_cluster.cpp +++ b/cpp/example_code/neptune/create_db_cluster.cpp @@ -1,28 +1,7 @@ - -//snippet-sourcedescription:[create_db_cluster.cpp demonstrates how to create an Amazon Neptune DB cluster.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Neptune] -//snippet-service:[neptune] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* -Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -This file is 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/ - -This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -CONDITIONS OF ANY KIND, either express or implied. See the License for the -specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include #include diff --git a/cpp/example_code/neptune/delete_db_cluster.cpp b/cpp/example_code/neptune/delete_db_cluster.cpp index 83b0e3fe83c..faae570cb91 100644 --- a/cpp/example_code/neptune/delete_db_cluster.cpp +++ b/cpp/example_code/neptune/delete_db_cluster.cpp @@ -1,28 +1,7 @@ - -//snippet-sourcedescription:[delete_db_cluster.cpp demonstrates how to delete an Amazon Neptune DB cluster.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Neptune] -//snippet-service:[neptune] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* -Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -This file is 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/ - -This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -CONDITIONS OF ANY KIND, either express or implied. See the License for the -specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include #include diff --git a/cpp/example_code/neptune/describe_db_clusters.cpp b/cpp/example_code/neptune/describe_db_clusters.cpp index 96331b316db..aac1e3330ec 100644 --- a/cpp/example_code/neptune/describe_db_clusters.cpp +++ b/cpp/example_code/neptune/describe_db_clusters.cpp @@ -1,28 +1,5 @@ - -//snippet-sourcedescription:[describe_db_clusters.cpp demonstrates how to retrieve information about Amazon Neptune provisioned DB clusters.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Neptune] -//snippet-service:[neptune] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* -Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -This file is 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/ - -This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -CONDITIONS OF ANY KIND, either express or implied. See the License for the -specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include #include diff --git a/cpp/example_code/neptune/modify_db_cluster.cpp b/cpp/example_code/neptune/modify_db_cluster.cpp index c2d64315363..64048589c20 100644 --- a/cpp/example_code/neptune/modify_db_cluster.cpp +++ b/cpp/example_code/neptune/modify_db_cluster.cpp @@ -1,28 +1,7 @@ - -//snippet-sourcedescription:[modify_db_cluster.cpp demonstrates how to modify the setting of an Amazon Neptune DB cluster.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Neptune] -//snippet-service:[neptune] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* -Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -This file is 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/ - -This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -CONDITIONS OF ANY KIND, either express or implied. See the License for the -specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include #include diff --git a/cpp/example_code/rds/getting_started_with_db_instances.cpp b/cpp/example_code/rds/getting_started_with_db_instances.cpp index 38ddf17b377..d8c94f8a792 100644 --- a/cpp/example_code/rds/getting_started_with_db_instances.cpp +++ b/cpp/example_code/rds/getting_started_with_db_instances.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. diff --git a/cpp/example_code/rds/hello_rds/hello_rds.cpp b/cpp/example_code/rds/hello_rds/hello_rds.cpp index b859aa8751f..aff84370d95 100644 --- a/cpp/example_code/rds/hello_rds/hello_rds.cpp +++ b/cpp/example_code/rds/hello_rds/hello_rds.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/rds/rds_samples.h b/cpp/example_code/rds/rds_samples.h index 9e118e25355..77c866774a1 100644 --- a/cpp/example_code/rds/rds_samples.h +++ b/cpp/example_code/rds/rds_samples.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef RDS_EXAMPLES_RDS_SAMPLES_H diff --git a/cpp/example_code/rds/tests/gtest_getting_started_with_db_instances.cpp b/cpp/example_code/rds/tests/gtest_getting_started_with_db_instances.cpp index 03c2ccf780f..bdf5d7475cf 100644 --- a/cpp/example_code/rds/tests/gtest_getting_started_with_db_instances.cpp +++ b/cpp/example_code/rds/tests/gtest_getting_started_with_db_instances.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/rds/tests/rds_gtests.cpp b/cpp/example_code/rds/tests/rds_gtests.cpp index 165d6c10af1..43a42dbcfcb 100644 --- a/cpp/example_code/rds/tests/rds_gtests.cpp +++ b/cpp/example_code/rds/tests/rds_gtests.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "rds_gtests.h" #include diff --git a/cpp/example_code/rds/tests/rds_gtests.h b/cpp/example_code/rds/tests/rds_gtests.h index 8624278b10f..e0d70b403f5 100644 --- a/cpp/example_code/rds/tests/rds_gtests.h +++ b/cpp/example_code/rds/tests/rds_gtests.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef RDS_EXAMPLES_RDS_GTESTS_H diff --git a/cpp/example_code/rds/tests/test_main.cpp b/cpp/example_code/rds/tests/test_main.cpp index 00ed3e2b055..656f92cb221 100644 --- a/cpp/example_code/rds/tests/test_main.cpp +++ b/cpp/example_code/rds/tests/test_main.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "gtest/gtest.h" diff --git a/cpp/example_code/redshift/authorize_cluster_access.cpp b/cpp/example_code/redshift/authorize_cluster_access.cpp index a57648f9208..36896feffc2 100644 --- a/cpp/example_code/redshift/authorize_cluster_access.cpp +++ b/cpp/example_code/redshift/authorize_cluster_access.cpp @@ -1,28 +1,5 @@ - -//snippet-sourcedescription:[authorize_cluster_access.cpp demonstrates how to enable access to Amazon Redshift clusters. ] -//snippet-service:[redshift] -//snippet-keyword:[Amazon Redshift] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-02-05] -//snippet-sourceauthor:[AWS] - - -/* -Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -This file is 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/ - -This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -CONDITIONS OF ANY KIND, either express or implied. See the License for the -specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include #include diff --git a/cpp/example_code/redshift/create_cluster.cpp b/cpp/example_code/redshift/create_cluster.cpp index 7dabb26909a..ed86507ac0a 100644 --- a/cpp/example_code/redshift/create_cluster.cpp +++ b/cpp/example_code/redshift/create_cluster.cpp @@ -1,27 +1,9 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -//snippet-sourcedescription:[create_cluster.cpp demonstrates how to create an Amazon Redshift cluster. ] -//snippet-service:[redshift] -//snippet-keyword:[Amazon Redshift] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-02-05] -//snippet-sourceauthor:[AWS] -/* -Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -This file is 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/ - -This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -CONDITIONS OF ANY KIND, either express or implied. See the License for the -specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/redshift/create_cluster_subnet_group.cpp b/cpp/example_code/redshift/create_cluster_subnet_group.cpp index eee6439d75d..1f8427cda31 100644 --- a/cpp/example_code/redshift/create_cluster_subnet_group.cpp +++ b/cpp/example_code/redshift/create_cluster_subnet_group.cpp @@ -1,27 +1,9 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -//snippet-sourcedescription:[create_cluster_subnet_group.cpp demonstrates how to create a subnet group for an Amazon Redshift cluster.] -//snippet-service:[redshift] -//snippet-keyword:[Amazon Redshift] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-02-05] -//snippet-sourceauthor:[AWS] -/* -Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -This file is 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/ - -This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -CONDITIONS OF ANY KIND, either express or implied. See the License for the -specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3-crt/include/awsdoc/s3-crt/s3-crt-demo.h b/cpp/example_code/s3-crt/include/awsdoc/s3-crt/s3-crt-demo.h index af28865f57d..514b97d8066 100644 --- a/cpp/example_code/s3-crt/include/awsdoc/s3-crt/s3-crt-demo.h +++ b/cpp/example_code/s3-crt/include/awsdoc/s3-crt/s3-crt-demo.h @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 // Enables test_s3-crt-demo.cpp to test the functionality in s3-crt-demo.cpp. diff --git a/cpp/example_code/s3-crt/s3-crt-demo.cpp b/cpp/example_code/s3-crt/s3-crt-demo.cpp index 557bb5f7b2b..684dabe14ec 100644 --- a/cpp/example_code/s3-crt/s3-crt-demo.cpp +++ b/cpp/example_code/s3-crt/s3-crt-demo.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 #include // snippet-start:[s3-crt.cpp.bucket_operations.list_create_delete] diff --git a/cpp/example_code/s3-crt/tests/test_s3-crt-demo.cpp b/cpp/example_code/s3-crt/tests/test_s3-crt-demo.cpp index 0e2c4e18f84..41188178f05 100644 --- a/cpp/example_code/s3-crt/tests/test_s3-crt-demo.cpp +++ b/cpp/example_code/s3-crt/tests/test_s3-crt-demo.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/copy_object.cpp b/cpp/example_code/s3/copy_object.cpp index 0383738a430..1032d693465 100644 --- a/cpp/example_code/s3/copy_object.cpp +++ b/cpp/example_code/s3/copy_object.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/create_bucket.cpp b/cpp/example_code/s3/create_bucket.cpp index 7dfadb2ac51..19b5a0e8529 100644 --- a/cpp/example_code/s3/create_bucket.cpp +++ b/cpp/example_code/s3/create_bucket.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/delete_bucket.cpp b/cpp/example_code/s3/delete_bucket.cpp index e9a3ab8a7fe..a3f5f104dd8 100644 --- a/cpp/example_code/s3/delete_bucket.cpp +++ b/cpp/example_code/s3/delete_bucket.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/delete_bucket_policy.cpp b/cpp/example_code/s3/delete_bucket_policy.cpp index f3b2774d005..91320eaca4d 100644 --- a/cpp/example_code/s3/delete_bucket_policy.cpp +++ b/cpp/example_code/s3/delete_bucket_policy.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/delete_object.cpp b/cpp/example_code/s3/delete_object.cpp index cf61fba6854..4efe2f91384 100644 --- a/cpp/example_code/s3/delete_object.cpp +++ b/cpp/example_code/s3/delete_object.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/delete_objects.cpp b/cpp/example_code/s3/delete_objects.cpp index 6a23cca4834..6c668146fdc 100644 --- a/cpp/example_code/s3/delete_objects.cpp +++ b/cpp/example_code/s3/delete_objects.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/s3/delete_website_config.cpp b/cpp/example_code/s3/delete_website_config.cpp index 67849757287..ef2d09969fd 100644 --- a/cpp/example_code/s3/delete_website_config.cpp +++ b/cpp/example_code/s3/delete_website_config.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/get_bucket_acl.cpp b/cpp/example_code/s3/get_bucket_acl.cpp index 3db63a86b5b..6c10615d5f9 100644 --- a/cpp/example_code/s3/get_bucket_acl.cpp +++ b/cpp/example_code/s3/get_bucket_acl.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/get_bucket_policy.cpp b/cpp/example_code/s3/get_bucket_policy.cpp index 0debf767698..ec09b211644 100644 --- a/cpp/example_code/s3/get_bucket_policy.cpp +++ b/cpp/example_code/s3/get_bucket_policy.cpp @@ -1,7 +1,6 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + #include diff --git a/cpp/example_code/s3/get_object.cpp b/cpp/example_code/s3/get_object.cpp index 60564be38ac..6899e847997 100644 --- a/cpp/example_code/s3/get_object.cpp +++ b/cpp/example_code/s3/get_object.cpp @@ -1,7 +1,6 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + #include #include diff --git a/cpp/example_code/s3/get_put_bucket_acl.cpp b/cpp/example_code/s3/get_put_bucket_acl.cpp index a110fdf9567..52bba82698e 100644 --- a/cpp/example_code/s3/get_put_bucket_acl.cpp +++ b/cpp/example_code/s3/get_put_bucket_acl.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/get_put_object_acl.cpp b/cpp/example_code/s3/get_put_object_acl.cpp index 7afc2a899e9..c6166b7473f 100644 --- a/cpp/example_code/s3/get_put_object_acl.cpp +++ b/cpp/example_code/s3/get_put_object_acl.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/s3/get_website_config.cpp b/cpp/example_code/s3/get_website_config.cpp index 2229cc5d8b0..721d8134046 100644 --- a/cpp/example_code/s3/get_website_config.cpp +++ b/cpp/example_code/s3/get_website_config.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/hello_s3/hello_s3.cpp b/cpp/example_code/s3/hello_s3/hello_s3.cpp index 904450ab701..91e4decd67d 100644 --- a/cpp/example_code/s3/hello_s3/hello_s3.cpp +++ b/cpp/example_code/s3/hello_s3/hello_s3.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/s3/include/awsdoc/s3/s3_demo_for_cloud9.h b/cpp/example_code/s3/include/awsdoc/s3/s3_demo_for_cloud9.h index 3cd9d44ecb8..b68147f3c1a 100644 --- a/cpp/example_code/s3/include/awsdoc/s3/s3_demo_for_cloud9.h +++ b/cpp/example_code/s3/include/awsdoc/s3/s3_demo_for_cloud9.h @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 #pragma once diff --git a/cpp/example_code/s3/include/awsdoc/s3/s3_examples.h b/cpp/example_code/s3/include/awsdoc/s3/s3_examples.h index eb6a0d062e4..246d34d2d45 100644 --- a/cpp/example_code/s3/include/awsdoc/s3/s3_examples.h +++ b/cpp/example_code/s3/include/awsdoc/s3/s3_examples.h @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 #pragma once diff --git a/cpp/example_code/s3/list_buckets.cpp b/cpp/example_code/s3/list_buckets.cpp index 481bc7c402e..769fa44487d 100644 --- a/cpp/example_code/s3/list_buckets.cpp +++ b/cpp/example_code/s3/list_buckets.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/list_buckets_disabling_dns_cache.cpp b/cpp/example_code/s3/list_buckets_disabling_dns_cache.cpp index 496b7185449..e44681a3a3e 100644 --- a/cpp/example_code/s3/list_buckets_disabling_dns_cache.cpp +++ b/cpp/example_code/s3/list_buckets_disabling_dns_cache.cpp @@ -1,9 +1,7 @@ -//NOTE!! This example only works on Linux and Mac. It does not work on Windows. +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +//NOTE!! This example only works on Linux and Mac. It does not work on Windows. #include #include diff --git a/cpp/example_code/s3/list_objects.cpp b/cpp/example_code/s3/list_objects.cpp index 8f72be1d4d8..fb1b8208805 100644 --- a/cpp/example_code/s3/list_objects.cpp +++ b/cpp/example_code/s3/list_objects.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/list_objects_with_aws_global_region.cpp b/cpp/example_code/s3/list_objects_with_aws_global_region.cpp index 51e6d6b7190..39d9f22cf18 100644 --- a/cpp/example_code/s3/list_objects_with_aws_global_region.cpp +++ b/cpp/example_code/s3/list_objects_with_aws_global_region.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/put_bucket_acl.cpp b/cpp/example_code/s3/put_bucket_acl.cpp index 917c4fbef51..a4bc7e5e4a3 100644 --- a/cpp/example_code/s3/put_bucket_acl.cpp +++ b/cpp/example_code/s3/put_bucket_acl.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/put_bucket_policy.cpp b/cpp/example_code/s3/put_bucket_policy.cpp index 1db53b1942a..c818db4f493 100644 --- a/cpp/example_code/s3/put_bucket_policy.cpp +++ b/cpp/example_code/s3/put_bucket_policy.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/put_object.cpp b/cpp/example_code/s3/put_object.cpp index 661511ee7a6..83f099a772d 100644 --- a/cpp/example_code/s3/put_object.cpp +++ b/cpp/example_code/s3/put_object.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/put_object_async.cpp b/cpp/example_code/s3/put_object_async.cpp index 1585dac8852..bb8aa9940d0 100644 --- a/cpp/example_code/s3/put_object_async.cpp +++ b/cpp/example_code/s3/put_object_async.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/put_object_buffer.cpp b/cpp/example_code/s3/put_object_buffer.cpp index 3c285487b92..ab4e0229ca3 100644 --- a/cpp/example_code/s3/put_object_buffer.cpp +++ b/cpp/example_code/s3/put_object_buffer.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/put_website_config.cpp b/cpp/example_code/s3/put_website_config.cpp index 67f4c4f6954..60beeec21ba 100644 --- a/cpp/example_code/s3/put_website_config.cpp +++ b/cpp/example_code/s3/put_website_config.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/s3_demo_for_cloud9.cpp b/cpp/example_code/s3/s3_demo_for_cloud9.cpp index ce7819c4a67..691d69e993c 100644 --- a/cpp/example_code/s3/s3_demo_for_cloud9.cpp +++ b/cpp/example_code/s3/s3_demo_for_cloud9.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. diff --git a/cpp/example_code/s3/s3_getting_started_scenario.cpp b/cpp/example_code/s3/s3_getting_started_scenario.cpp index 58c56b81a28..eb775c0611b 100644 --- a/cpp/example_code/s3/s3_getting_started_scenario.cpp +++ b/cpp/example_code/s3/s3_getting_started_scenario.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. diff --git a/cpp/example_code/s3/tests/S3_GTests.cpp b/cpp/example_code/s3/tests/S3_GTests.cpp index 6cc8bcaa50d..ef1d528239b 100644 --- a/cpp/example_code/s3/tests/S3_GTests.cpp +++ b/cpp/example_code/s3/tests/S3_GTests.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "S3_GTests.h" #include diff --git a/cpp/example_code/s3/tests/S3_GTests.h b/cpp/example_code/s3/tests/S3_GTests.h index 716c8f3665c..d278ab2835d 100644 --- a/cpp/example_code/s3/tests/S3_GTests.h +++ b/cpp/example_code/s3/tests/S3_GTests.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef S3_EXAMPLES_S3_GTESTS_H diff --git a/cpp/example_code/s3/tests/gtest_copy_object.cpp b/cpp/example_code/s3/tests/gtest_copy_object.cpp index 8bf9b364e6b..457103ba306 100644 --- a/cpp/example_code/s3/tests/gtest_copy_object.cpp +++ b/cpp/example_code/s3/tests/gtest_copy_object.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_create_bucket.cpp b/cpp/example_code/s3/tests/gtest_create_bucket.cpp index deb35fdd5e9..ba4479c1fea 100644 --- a/cpp/example_code/s3/tests/gtest_create_bucket.cpp +++ b/cpp/example_code/s3/tests/gtest_create_bucket.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_delete_bucket.cpp b/cpp/example_code/s3/tests/gtest_delete_bucket.cpp index 754bb29d50c..ce21ae65b3d 100644 --- a/cpp/example_code/s3/tests/gtest_delete_bucket.cpp +++ b/cpp/example_code/s3/tests/gtest_delete_bucket.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_delete_bucket_policy.cpp b/cpp/example_code/s3/tests/gtest_delete_bucket_policy.cpp index 69e3cb9aa74..c6b50ad2292 100644 --- a/cpp/example_code/s3/tests/gtest_delete_bucket_policy.cpp +++ b/cpp/example_code/s3/tests/gtest_delete_bucket_policy.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_delete_object.cpp b/cpp/example_code/s3/tests/gtest_delete_object.cpp index 41604f34d69..b07fb0ce550 100644 --- a/cpp/example_code/s3/tests/gtest_delete_object.cpp +++ b/cpp/example_code/s3/tests/gtest_delete_object.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_delete_objects.cpp b/cpp/example_code/s3/tests/gtest_delete_objects.cpp index cb9fc6e1438..e2a460e3ea3 100644 --- a/cpp/example_code/s3/tests/gtest_delete_objects.cpp +++ b/cpp/example_code/s3/tests/gtest_delete_objects.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_delete_website_config.cpp b/cpp/example_code/s3/tests/gtest_delete_website_config.cpp index 4dc5c1fab1f..60caa234361 100644 --- a/cpp/example_code/s3/tests/gtest_delete_website_config.cpp +++ b/cpp/example_code/s3/tests/gtest_delete_website_config.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_get_bucket_acl.cpp b/cpp/example_code/s3/tests/gtest_get_bucket_acl.cpp index cea02bfb394..f5526d47826 100644 --- a/cpp/example_code/s3/tests/gtest_get_bucket_acl.cpp +++ b/cpp/example_code/s3/tests/gtest_get_bucket_acl.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_get_bucket_policy.cpp b/cpp/example_code/s3/tests/gtest_get_bucket_policy.cpp index 9476ac412d6..6aed44ec3e3 100644 --- a/cpp/example_code/s3/tests/gtest_get_bucket_policy.cpp +++ b/cpp/example_code/s3/tests/gtest_get_bucket_policy.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_get_object.cpp b/cpp/example_code/s3/tests/gtest_get_object.cpp index 032756cf169..168535aad10 100644 --- a/cpp/example_code/s3/tests/gtest_get_object.cpp +++ b/cpp/example_code/s3/tests/gtest_get_object.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_get_put_bucket_acl.cpp b/cpp/example_code/s3/tests/gtest_get_put_bucket_acl.cpp index edfbb93c58e..d50d72b52fb 100644 --- a/cpp/example_code/s3/tests/gtest_get_put_bucket_acl.cpp +++ b/cpp/example_code/s3/tests/gtest_get_put_bucket_acl.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_get_put_object_acl.cpp b/cpp/example_code/s3/tests/gtest_get_put_object_acl.cpp index 9d5abd35b46..6b4977a00dc 100644 --- a/cpp/example_code/s3/tests/gtest_get_put_object_acl.cpp +++ b/cpp/example_code/s3/tests/gtest_get_put_object_acl.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_get_website_config.cpp b/cpp/example_code/s3/tests/gtest_get_website_config.cpp index 3710c7b0f75..6fbfde7d397 100644 --- a/cpp/example_code/s3/tests/gtest_get_website_config.cpp +++ b/cpp/example_code/s3/tests/gtest_get_website_config.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_list_buckets.cpp b/cpp/example_code/s3/tests/gtest_list_buckets.cpp index dc6c570a726..dde9752451c 100644 --- a/cpp/example_code/s3/tests/gtest_list_buckets.cpp +++ b/cpp/example_code/s3/tests/gtest_list_buckets.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_list_buckets_disabling_dns_cache.cpp b/cpp/example_code/s3/tests/gtest_list_buckets_disabling_dns_cache.cpp index 8eda2eeecd9..7cdad7b6cd2 100644 --- a/cpp/example_code/s3/tests/gtest_list_buckets_disabling_dns_cache.cpp +++ b/cpp/example_code/s3/tests/gtest_list_buckets_disabling_dns_cache.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_list_objects.cpp b/cpp/example_code/s3/tests/gtest_list_objects.cpp index 4848da32f93..8b00fd4fcec 100644 --- a/cpp/example_code/s3/tests/gtest_list_objects.cpp +++ b/cpp/example_code/s3/tests/gtest_list_objects.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_list_objects_with_aws_global_region.cpp b/cpp/example_code/s3/tests/gtest_list_objects_with_aws_global_region.cpp index 81a3aeddebb..851fae37310 100644 --- a/cpp/example_code/s3/tests/gtest_list_objects_with_aws_global_region.cpp +++ b/cpp/example_code/s3/tests/gtest_list_objects_with_aws_global_region.cpp @@ -1,7 +1,6 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_put_bucket_acl.cpp b/cpp/example_code/s3/tests/gtest_put_bucket_acl.cpp index 9f836def3c7..e3cc9b7d43c 100644 --- a/cpp/example_code/s3/tests/gtest_put_bucket_acl.cpp +++ b/cpp/example_code/s3/tests/gtest_put_bucket_acl.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_put_bucket_policy.cpp b/cpp/example_code/s3/tests/gtest_put_bucket_policy.cpp index ded99c63a29..ceeb3dbe19c 100644 --- a/cpp/example_code/s3/tests/gtest_put_bucket_policy.cpp +++ b/cpp/example_code/s3/tests/gtest_put_bucket_policy.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_put_object.cpp b/cpp/example_code/s3/tests/gtest_put_object.cpp index 0108ddde3c6..be0257bb3dd 100644 --- a/cpp/example_code/s3/tests/gtest_put_object.cpp +++ b/cpp/example_code/s3/tests/gtest_put_object.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_put_object_async.cpp b/cpp/example_code/s3/tests/gtest_put_object_async.cpp index c915e005ace..1a1614a565b 100644 --- a/cpp/example_code/s3/tests/gtest_put_object_async.cpp +++ b/cpp/example_code/s3/tests/gtest_put_object_async.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_put_object_buffer.cpp b/cpp/example_code/s3/tests/gtest_put_object_buffer.cpp index 0125c168ce6..ea485f1069c 100644 --- a/cpp/example_code/s3/tests/gtest_put_object_buffer.cpp +++ b/cpp/example_code/s3/tests/gtest_put_object_buffer.cpp @@ -1,7 +1,6 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_put_website_config.cpp b/cpp/example_code/s3/tests/gtest_put_website_config.cpp index 233f6172998..d767f193420 100644 --- a/cpp/example_code/s3/tests/gtest_put_website_config.cpp +++ b/cpp/example_code/s3/tests/gtest_put_website_config.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/s3/tests/gtest_s3_demo_for_cloud9.cpp b/cpp/example_code/s3/tests/gtest_s3_demo_for_cloud9.cpp index 4393eddf955..9b29da6f160 100644 --- a/cpp/example_code/s3/tests/gtest_s3_demo_for_cloud9.cpp +++ b/cpp/example_code/s3/tests/gtest_s3_demo_for_cloud9.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/tests/gtest_s3_getting_started_scenario.cpp b/cpp/example_code/s3/tests/gtest_s3_getting_started_scenario.cpp index c2f3e5fab48..fa0ee31d8d2 100644 --- a/cpp/example_code/s3/tests/gtest_s3_getting_started_scenario.cpp +++ b/cpp/example_code/s3/tests/gtest_s3_getting_started_scenario.cpp @@ -1,6 +1,5 @@ -// NOLINTNEXTLINE(readability-named-parameter) // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/s3/tests/test_main.cpp b/cpp/example_code/s3/tests/test_main.cpp index 00ed3e2b055..656f92cb221 100644 --- a/cpp/example_code/s3/tests/test_main.cpp +++ b/cpp/example_code/s3/tests/test_main.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "gtest/gtest.h" diff --git a/cpp/example_code/s3encryption/include/awsdoc/s3-encryption/s3_encryption_examples.h b/cpp/example_code/s3encryption/include/awsdoc/s3-encryption/s3_encryption_examples.h index 1c28b2ecb7e..18f2fe323f4 100644 --- a/cpp/example_code/s3encryption/include/awsdoc/s3-encryption/s3_encryption_examples.h +++ b/cpp/example_code/s3encryption/include/awsdoc/s3-encryption/s3_encryption_examples.h @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 #pragma once diff --git a/cpp/example_code/s3encryption/s3Encryption.cpp b/cpp/example_code/s3encryption/s3Encryption.cpp index 6571fb5e48a..9684c6769c2 100644 --- a/cpp/example_code/s3encryption/s3Encryption.cpp +++ b/cpp/example_code/s3encryption/s3Encryption.cpp @@ -1,16 +1,5 @@ -//snippet-sourcedescription:[s3Encryption.cpp demonstrates how to perform client-side encryption on an Amazon S3 bucket object using AWS KMS.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] - // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 - +// SPDX-License-Identifier: Apache-2.0 #define AWS_DISABLE_DEPRECATION #include #include diff --git a/cpp/example_code/s3encryption/tests/test_s3Encryption.cpp b/cpp/example_code/s3encryption/tests/test_s3Encryption.cpp index c35227247ed..bdf5becde95 100644 --- a/cpp/example_code/s3encryption/tests/test_s3Encryption.cpp +++ b/cpp/example_code/s3encryption/tests/test_s3Encryption.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 #define AWS_DISABLE_DEPRECATION #include diff --git a/cpp/example_code/secretsmanager/create_secret_with_string.cpp b/cpp/example_code/secretsmanager/create_secret_with_string.cpp index 15b979c6dfe..20554da0e2a 100644 --- a/cpp/example_code/secretsmanager/create_secret_with_string.cpp +++ b/cpp/example_code/secretsmanager/create_secret_with_string.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/secretsmanager/get_secret_value.cpp b/cpp/example_code/secretsmanager/get_secret_value.cpp index b2c52546328..e2bdf6a7de6 100644 --- a/cpp/example_code/secretsmanager/get_secret_value.cpp +++ b/cpp/example_code/secretsmanager/get_secret_value.cpp @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX - License - Identifier: Apache - 2.0 +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/ses/create_receipt_filter.cpp b/cpp/example_code/ses/create_receipt_filter.cpp index dad1c15722b..f7f80f2f823 100644 --- a/cpp/example_code/ses/create_receipt_filter.cpp +++ b/cpp/example_code/ses/create_receipt_filter.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/ses/create_receipt_rule.cpp b/cpp/example_code/ses/create_receipt_rule.cpp index f0d8f66aa52..54e9a1d5b8a 100644 --- a/cpp/example_code/ses/create_receipt_rule.cpp +++ b/cpp/example_code/ses/create_receipt_rule.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/ses/create_receipt_rule_set.cpp b/cpp/example_code/ses/create_receipt_rule_set.cpp index 1418e9974ae..455d0679f30 100644 --- a/cpp/example_code/ses/create_receipt_rule_set.cpp +++ b/cpp/example_code/ses/create_receipt_rule_set.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/ses/create_template.cpp b/cpp/example_code/ses/create_template.cpp index 65a2608ef2f..9a72945eb49 100644 --- a/cpp/example_code/ses/create_template.cpp +++ b/cpp/example_code/ses/create_template.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/ses/delete_identity.cpp b/cpp/example_code/ses/delete_identity.cpp index c16488c9ec9..a5b9096fa69 100644 --- a/cpp/example_code/ses/delete_identity.cpp +++ b/cpp/example_code/ses/delete_identity.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/ses/delete_receipt_filter.cpp b/cpp/example_code/ses/delete_receipt_filter.cpp index fcc26f92772..712696b7d5e 100644 --- a/cpp/example_code/ses/delete_receipt_filter.cpp +++ b/cpp/example_code/ses/delete_receipt_filter.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/ses/delete_receipt_rule.cpp b/cpp/example_code/ses/delete_receipt_rule.cpp index f65342e981a..8659c3347f5 100644 --- a/cpp/example_code/ses/delete_receipt_rule.cpp +++ b/cpp/example_code/ses/delete_receipt_rule.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/ses/delete_receipt_rule_set.cpp b/cpp/example_code/ses/delete_receipt_rule_set.cpp index 37cc06075ff..633231f8c2e 100644 --- a/cpp/example_code/ses/delete_receipt_rule_set.cpp +++ b/cpp/example_code/ses/delete_receipt_rule_set.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/ses/delete_template.cpp b/cpp/example_code/ses/delete_template.cpp index 0ca09253fcb..e1e1281df67 100644 --- a/cpp/example_code/ses/delete_template.cpp +++ b/cpp/example_code/ses/delete_template.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/ses/get_template.cpp b/cpp/example_code/ses/get_template.cpp index 5716547559b..358a5ff9047 100644 --- a/cpp/example_code/ses/get_template.cpp +++ b/cpp/example_code/ses/get_template.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/ses/list_identities.cpp b/cpp/example_code/ses/list_identities.cpp index 430bb69b6ae..ddd765a4444 100644 --- a/cpp/example_code/ses/list_identities.cpp +++ b/cpp/example_code/ses/list_identities.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/ses/list_receipt_filters.cpp b/cpp/example_code/ses/list_receipt_filters.cpp index d4cc945c996..65272059107 100644 --- a/cpp/example_code/ses/list_receipt_filters.cpp +++ b/cpp/example_code/ses/list_receipt_filters.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/ses/send_email.cpp b/cpp/example_code/ses/send_email.cpp index bfac6ecd93c..2bca807b3ef 100644 --- a/cpp/example_code/ses/send_email.cpp +++ b/cpp/example_code/ses/send_email.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/ses/send_templated_email.cpp b/cpp/example_code/ses/send_templated_email.cpp index 3c5ba36eed5..49348164f2f 100644 --- a/cpp/example_code/ses/send_templated_email.cpp +++ b/cpp/example_code/ses/send_templated_email.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/ses/ses_samples.h b/cpp/example_code/ses/ses_samples.h index f3c74124d54..844725ae647 100644 --- a/cpp/example_code/ses/ses_samples.h +++ b/cpp/example_code/ses/ses_samples.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef SES_EXAMPLES_SES_SAMPLES_H diff --git a/cpp/example_code/ses/tests/gtest_create_receipt_filter.cpp b/cpp/example_code/ses/tests/gtest_create_receipt_filter.cpp index ffb2fd5aa3b..de0203168bc 100644 --- a/cpp/example_code/ses/tests/gtest_create_receipt_filter.cpp +++ b/cpp/example_code/ses/tests/gtest_create_receipt_filter.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ses/tests/gtest_create_receipt_rule.cpp b/cpp/example_code/ses/tests/gtest_create_receipt_rule.cpp index 0de750f2cb3..ae4b458eb8c 100644 --- a/cpp/example_code/ses/tests/gtest_create_receipt_rule.cpp +++ b/cpp/example_code/ses/tests/gtest_create_receipt_rule.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ses/tests/gtest_create_receipt_rule_set.cpp b/cpp/example_code/ses/tests/gtest_create_receipt_rule_set.cpp index dfe0ffaf47c..7d07d3cd371 100644 --- a/cpp/example_code/ses/tests/gtest_create_receipt_rule_set.cpp +++ b/cpp/example_code/ses/tests/gtest_create_receipt_rule_set.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ses/tests/gtest_create_template.cpp b/cpp/example_code/ses/tests/gtest_create_template.cpp index d4ec506cc83..d50e2f0de33 100644 --- a/cpp/example_code/ses/tests/gtest_create_template.cpp +++ b/cpp/example_code/ses/tests/gtest_create_template.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ses/tests/gtest_delete_identity.cpp b/cpp/example_code/ses/tests/gtest_delete_identity.cpp index 4ee654125a1..b88760144f1 100644 --- a/cpp/example_code/ses/tests/gtest_delete_identity.cpp +++ b/cpp/example_code/ses/tests/gtest_delete_identity.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ses/tests/gtest_delete_receipt_filter.cpp b/cpp/example_code/ses/tests/gtest_delete_receipt_filter.cpp index 89b8d164799..9b89822383f 100644 --- a/cpp/example_code/ses/tests/gtest_delete_receipt_filter.cpp +++ b/cpp/example_code/ses/tests/gtest_delete_receipt_filter.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ses/tests/gtest_delete_receipt_rule.cpp b/cpp/example_code/ses/tests/gtest_delete_receipt_rule.cpp index 27ade191dbb..27e19738938 100644 --- a/cpp/example_code/ses/tests/gtest_delete_receipt_rule.cpp +++ b/cpp/example_code/ses/tests/gtest_delete_receipt_rule.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ses/tests/gtest_delete_receipt_rule_set.cpp b/cpp/example_code/ses/tests/gtest_delete_receipt_rule_set.cpp index 73e0ed7ce20..ce98b60be31 100644 --- a/cpp/example_code/ses/tests/gtest_delete_receipt_rule_set.cpp +++ b/cpp/example_code/ses/tests/gtest_delete_receipt_rule_set.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ses/tests/gtest_delete_template.cpp b/cpp/example_code/ses/tests/gtest_delete_template.cpp index 08808741a9a..82a25323c3a 100644 --- a/cpp/example_code/ses/tests/gtest_delete_template.cpp +++ b/cpp/example_code/ses/tests/gtest_delete_template.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * @@ -26,7 +24,3 @@ namespace AwsDocTest { ASSERT_TRUE(result); } } // namespace AwsDocTest -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ diff --git a/cpp/example_code/ses/tests/gtest_get_template.cpp b/cpp/example_code/ses/tests/gtest_get_template.cpp index 7167b3a2fa5..bd2f9fd8194 100644 --- a/cpp/example_code/ses/tests/gtest_get_template.cpp +++ b/cpp/example_code/ses/tests/gtest_get_template.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * @@ -26,7 +24,3 @@ namespace AwsDocTest { ASSERT_TRUE(result); } } // namespace AwsDocTest -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ diff --git a/cpp/example_code/ses/tests/gtest_list_identities.cpp b/cpp/example_code/ses/tests/gtest_list_identities.cpp index 8f4e6564e44..6ac16f676b0 100644 --- a/cpp/example_code/ses/tests/gtest_list_identities.cpp +++ b/cpp/example_code/ses/tests/gtest_list_identities.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * @@ -29,7 +27,3 @@ namespace AwsDocTest { ASSERT_FALSE(identities.empty()); } } // namespace AwsDocTest -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ diff --git a/cpp/example_code/ses/tests/gtest_list_receipt_filters.cpp b/cpp/example_code/ses/tests/gtest_list_receipt_filters.cpp index 019b7373d30..505fbc2bfc9 100644 --- a/cpp/example_code/ses/tests/gtest_list_receipt_filters.cpp +++ b/cpp/example_code/ses/tests/gtest_list_receipt_filters.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * @@ -29,7 +27,3 @@ namespace AwsDocTest { ASSERT_FALSE(filters.empty()); } } // namespace AwsDocTest -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ diff --git a/cpp/example_code/ses/tests/gtest_send_email.cpp b/cpp/example_code/ses/tests/gtest_send_email.cpp index de5ac8d3ba2..ba6845fb795 100644 --- a/cpp/example_code/ses/tests/gtest_send_email.cpp +++ b/cpp/example_code/ses/tests/gtest_send_email.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * @@ -27,7 +25,3 @@ namespace AwsDocTest { ASSERT_TRUE(result); } } // namespace AwsDocTest -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ diff --git a/cpp/example_code/ses/tests/gtest_send_templated_email.cpp b/cpp/example_code/ses/tests/gtest_send_templated_email.cpp index 360129a086a..49b3471b36b 100644 --- a/cpp/example_code/ses/tests/gtest_send_templated_email.cpp +++ b/cpp/example_code/ses/tests/gtest_send_templated_email.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * @@ -30,7 +28,3 @@ namespace AwsDocTest { ASSERT_TRUE(result); } } // namespace AwsDocTest -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ diff --git a/cpp/example_code/ses/tests/gtest_update_template.cpp b/cpp/example_code/ses/tests/gtest_update_template.cpp index 7302aa01ace..a3722cc3f19 100644 --- a/cpp/example_code/ses/tests/gtest_update_template.cpp +++ b/cpp/example_code/ses/tests/gtest_update_template.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ses/tests/gtest_verify_email_identity.cpp b/cpp/example_code/ses/tests/gtest_verify_email_identity.cpp index 65ee3b28b47..129921a86fe 100644 --- a/cpp/example_code/ses/tests/gtest_verify_email_identity.cpp +++ b/cpp/example_code/ses/tests/gtest_verify_email_identity.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/ses/tests/ses_gtests.cpp b/cpp/example_code/ses/tests/ses_gtests.cpp index d0744a565e8..f41ec10fe44 100644 --- a/cpp/example_code/ses/tests/ses_gtests.cpp +++ b/cpp/example_code/ses/tests/ses_gtests.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "ses_gtests.h" #include diff --git a/cpp/example_code/ses/tests/ses_gtests.h b/cpp/example_code/ses/tests/ses_gtests.h index 67fc447f6c8..093fa034010 100644 --- a/cpp/example_code/ses/tests/ses_gtests.h +++ b/cpp/example_code/ses/tests/ses_gtests.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef S3_EXAMPLES_S3_GTESTS_H diff --git a/cpp/example_code/ses/tests/test_main.cpp b/cpp/example_code/ses/tests/test_main.cpp index 00ed3e2b055..656f92cb221 100644 --- a/cpp/example_code/ses/tests/test_main.cpp +++ b/cpp/example_code/ses/tests/test_main.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "gtest/gtest.h" diff --git a/cpp/example_code/ses/update_template.cpp b/cpp/example_code/ses/update_template.cpp index e4a3d2e6b93..cc0f10016b4 100644 --- a/cpp/example_code/ses/update_template.cpp +++ b/cpp/example_code/ses/update_template.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/ses/verify_email_identity.cpp b/cpp/example_code/ses/verify_email_identity.cpp index 41b511755dc..79d678d8bf8 100644 --- a/cpp/example_code/ses/verify_email_identity.cpp +++ b/cpp/example_code/ses/verify_email_identity.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/sns/create_topic.cpp b/cpp/example_code/sns/create_topic.cpp index e715a38e899..356a8c7d517 100644 --- a/cpp/example_code/sns/create_topic.cpp +++ b/cpp/example_code/sns/create_topic.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/sns/delete_topic.cpp b/cpp/example_code/sns/delete_topic.cpp index 9dda70cde7d..ee151b4d8b3 100644 --- a/cpp/example_code/sns/delete_topic.cpp +++ b/cpp/example_code/sns/delete_topic.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/sns/get_sms_type.cpp b/cpp/example_code/sns/get_sms_type.cpp index dea1d31bcd1..9c68f683840 100644 --- a/cpp/example_code/sns/get_sms_type.cpp +++ b/cpp/example_code/sns/get_sms_type.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/sns/get_subscription_attributes.cpp b/cpp/example_code/sns/get_subscription_attributes.cpp index 0c2902bdd4c..b1b7d8daf63 100644 --- a/cpp/example_code/sns/get_subscription_attributes.cpp +++ b/cpp/example_code/sns/get_subscription_attributes.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/sns/get_topic_attributes.cpp b/cpp/example_code/sns/get_topic_attributes.cpp index 136c0a8f686..4b9b8a63e4a 100644 --- a/cpp/example_code/sns/get_topic_attributes.cpp +++ b/cpp/example_code/sns/get_topic_attributes.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/sns/hello_sns/hello_sns.cpp b/cpp/example_code/sns/hello_sns/hello_sns.cpp index 7ec98d7eaf2..eb5e7ca8c9a 100644 --- a/cpp/example_code/sns/hello_sns/hello_sns.cpp +++ b/cpp/example_code/sns/hello_sns/hello_sns.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/sns/list_subscriptions.cpp b/cpp/example_code/sns/list_subscriptions.cpp index 7a8d5495e56..366f632a386 100644 --- a/cpp/example_code/sns/list_subscriptions.cpp +++ b/cpp/example_code/sns/list_subscriptions.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/sns/list_topics.cpp b/cpp/example_code/sns/list_topics.cpp index 23d28c174a1..0844610b609 100644 --- a/cpp/example_code/sns/list_topics.cpp +++ b/cpp/example_code/sns/list_topics.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/sns/publish_sms.cpp b/cpp/example_code/sns/publish_sms.cpp index e8058f4bb29..920a543e946 100644 --- a/cpp/example_code/sns/publish_sms.cpp +++ b/cpp/example_code/sns/publish_sms.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/sns/publish_to_topic.cpp b/cpp/example_code/sns/publish_to_topic.cpp index 921f005a161..1e989a6b7ae 100644 --- a/cpp/example_code/sns/publish_to_topic.cpp +++ b/cpp/example_code/sns/publish_to_topic.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/sns/set_sms_type.cpp b/cpp/example_code/sns/set_sms_type.cpp index 26fc35bd721..0f8bfdef3fd 100644 --- a/cpp/example_code/sns/set_sms_type.cpp +++ b/cpp/example_code/sns/set_sms_type.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/sns/sns_samples.h b/cpp/example_code/sns/sns_samples.h index c4167da74ec..6918ac583f9 100644 --- a/cpp/example_code/sns/sns_samples.h +++ b/cpp/example_code/sns/sns_samples.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef SNS_EXAMPLES_SNS_SAMPLES_H diff --git a/cpp/example_code/sns/subscribe_app.cpp b/cpp/example_code/sns/subscribe_app.cpp index 587727b4c27..59fbba890bb 100644 --- a/cpp/example_code/sns/subscribe_app.cpp +++ b/cpp/example_code/sns/subscribe_app.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/sns/subscribe_email.cpp b/cpp/example_code/sns/subscribe_email.cpp index 6cb45c99eee..3c0ea732544 100644 --- a/cpp/example_code/sns/subscribe_email.cpp +++ b/cpp/example_code/sns/subscribe_email.cpp @@ -1,13 +1,5 @@ -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/sns/subscribe_lambda.cpp b/cpp/example_code/sns/subscribe_lambda.cpp index 90f94c28200..d8788718923 100644 --- a/cpp/example_code/sns/subscribe_lambda.cpp +++ b/cpp/example_code/sns/subscribe_lambda.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/sns/tests/gtest_create_topic.cpp b/cpp/example_code/sns/tests/gtest_create_topic.cpp index 6348870f981..059c7304f20 100644 --- a/cpp/example_code/sns/tests/gtest_create_topic.cpp +++ b/cpp/example_code/sns/tests/gtest_create_topic.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sns/tests/gtest_delete_topic.cpp b/cpp/example_code/sns/tests/gtest_delete_topic.cpp index 80bbcdd2483..18487c9632a 100644 --- a/cpp/example_code/sns/tests/gtest_delete_topic.cpp +++ b/cpp/example_code/sns/tests/gtest_delete_topic.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sns/tests/gtest_get_sms_type.cpp b/cpp/example_code/sns/tests/gtest_get_sms_type.cpp index 2fc072123f6..f5989fc06ed 100644 --- a/cpp/example_code/sns/tests/gtest_get_sms_type.cpp +++ b/cpp/example_code/sns/tests/gtest_get_sms_type.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sns/tests/gtest_get_subscription_attributes.cpp b/cpp/example_code/sns/tests/gtest_get_subscription_attributes.cpp index 575f15e38f9..bfb1b49e980 100644 --- a/cpp/example_code/sns/tests/gtest_get_subscription_attributes.cpp +++ b/cpp/example_code/sns/tests/gtest_get_subscription_attributes.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sns/tests/gtest_get_topic_attributes.cpp b/cpp/example_code/sns/tests/gtest_get_topic_attributes.cpp index 8a2797c80ac..812c67e7c8a 100644 --- a/cpp/example_code/sns/tests/gtest_get_topic_attributes.cpp +++ b/cpp/example_code/sns/tests/gtest_get_topic_attributes.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sns/tests/gtest_list_subscriptions.cpp b/cpp/example_code/sns/tests/gtest_list_subscriptions.cpp index e10f08a8a41..f0e0864bcb6 100644 --- a/cpp/example_code/sns/tests/gtest_list_subscriptions.cpp +++ b/cpp/example_code/sns/tests/gtest_list_subscriptions.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sns/tests/gtest_list_topics.cpp b/cpp/example_code/sns/tests/gtest_list_topics.cpp index 20019e28d53..6f093a19281 100644 --- a/cpp/example_code/sns/tests/gtest_list_topics.cpp +++ b/cpp/example_code/sns/tests/gtest_list_topics.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sns/tests/gtest_publish_sms.cpp b/cpp/example_code/sns/tests/gtest_publish_sms.cpp index 4b616823905..81502b28480 100644 --- a/cpp/example_code/sns/tests/gtest_publish_sms.cpp +++ b/cpp/example_code/sns/tests/gtest_publish_sms.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sns/tests/gtest_publish_to_topic.cpp b/cpp/example_code/sns/tests/gtest_publish_to_topic.cpp index a8835cd89eb..ed8cc0f67a3 100644 --- a/cpp/example_code/sns/tests/gtest_publish_to_topic.cpp +++ b/cpp/example_code/sns/tests/gtest_publish_to_topic.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sns/tests/gtest_set_sms_type.cpp b/cpp/example_code/sns/tests/gtest_set_sms_type.cpp index e0597054df1..9fc4d13f022 100644 --- a/cpp/example_code/sns/tests/gtest_set_sms_type.cpp +++ b/cpp/example_code/sns/tests/gtest_set_sms_type.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sns/tests/gtest_subscribe_app.cpp b/cpp/example_code/sns/tests/gtest_subscribe_app.cpp index 8fb6cf5b0ca..81d2c515be2 100644 --- a/cpp/example_code/sns/tests/gtest_subscribe_app.cpp +++ b/cpp/example_code/sns/tests/gtest_subscribe_app.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sns/tests/gtest_subscribe_email.cpp b/cpp/example_code/sns/tests/gtest_subscribe_email.cpp index 9814f8ed00f..11dc14cbbc7 100644 --- a/cpp/example_code/sns/tests/gtest_subscribe_email.cpp +++ b/cpp/example_code/sns/tests/gtest_subscribe_email.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sns/tests/gtest_subscribe_lambda.cpp b/cpp/example_code/sns/tests/gtest_subscribe_lambda.cpp index 2613a4f5953..23caac1ef49 100644 --- a/cpp/example_code/sns/tests/gtest_subscribe_lambda.cpp +++ b/cpp/example_code/sns/tests/gtest_subscribe_lambda.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sns/tests/gtest_unsubscribe.cpp b/cpp/example_code/sns/tests/gtest_unsubscribe.cpp index 9f535e19c52..24fa4db2978 100644 --- a/cpp/example_code/sns/tests/gtest_unsubscribe.cpp +++ b/cpp/example_code/sns/tests/gtest_unsubscribe.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sns/tests/sns_gtests.cpp b/cpp/example_code/sns/tests/sns_gtests.cpp index 7ff9c842e4a..224634db74c 100644 --- a/cpp/example_code/sns/tests/sns_gtests.cpp +++ b/cpp/example_code/sns/tests/sns_gtests.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "sns_gtests.h" #include diff --git a/cpp/example_code/sns/tests/sns_gtests.h b/cpp/example_code/sns/tests/sns_gtests.h index 4e8f8a03444..6d5967f1eb0 100644 --- a/cpp/example_code/sns/tests/sns_gtests.h +++ b/cpp/example_code/sns/tests/sns_gtests.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef S3_EXAMPLES_S3_GTESTS_H diff --git a/cpp/example_code/sns/tests/test_main.cpp b/cpp/example_code/sns/tests/test_main.cpp index 00ed3e2b055..656f92cb221 100644 --- a/cpp/example_code/sns/tests/test_main.cpp +++ b/cpp/example_code/sns/tests/test_main.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "gtest/gtest.h" diff --git a/cpp/example_code/sns/unsubscribe.cpp b/cpp/example_code/sns/unsubscribe.cpp index 3f40d5f06f2..92d5f0a15bb 100644 --- a/cpp/example_code/sns/unsubscribe.cpp +++ b/cpp/example_code/sns/unsubscribe.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/sqs/change_message_visibility.cpp b/cpp/example_code/sqs/change_message_visibility.cpp index 2ec76371aa7..81b1847a087 100644 --- a/cpp/example_code/sqs/change_message_visibility.cpp +++ b/cpp/example_code/sqs/change_message_visibility.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,13 +12,13 @@ * **/ -//snippet-start:[sqs.cpp.change_message_visibility.inc] +// snippet-start:[sqs.cpp.change_message_visibility.inc] #include #include #include #include #include -//snippet-end:[sqs.cpp.change_message_visibility.inc] +// snippet-end:[sqs.cpp.change_message_visibility.inc] #include "sqs_samples.h" // snippet-start:[cpp.example_code.sqs.ChangeMessageVisibility] diff --git a/cpp/example_code/sqs/create_queue.cpp b/cpp/example_code/sqs/create_queue.cpp index 1958797a5c3..ab7c1456248 100644 --- a/cpp/example_code/sqs/create_queue.cpp +++ b/cpp/example_code/sqs/create_queue.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,12 +12,12 @@ * **/ -//snippet-start:[sqs.cpp.create_queue.inc] +// snippet-start:[sqs.cpp.create_queue.inc] #include #include #include #include -//snippet-end:[sqs.cpp.create_queue.inc] +// snippet-end:[sqs.cpp.create_queue.inc] #include "sqs_samples.h" // snippet-start:[cpp.example_code.sqs.CreateQueue] diff --git a/cpp/example_code/sqs/dead_letter_queue.cpp b/cpp/example_code/sqs/dead_letter_queue.cpp index b40d13c9a7a..cd10a527b1f 100644 --- a/cpp/example_code/sqs/dead_letter_queue.cpp +++ b/cpp/example_code/sqs/dead_letter_queue.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,15 +12,15 @@ * **/ -//snippet-start:[sqs.cpp.make_redrive_policy.inc] +// snippet-start:[sqs.cpp.make_redrive_policy.inc] #include #include -//snippet-end:[sqs.cpp.make_redrive_policy.inc] -//snippet-start:[sqs.cpp.set_redrive_policy.inc] +// snippet-end:[sqs.cpp.make_redrive_policy.inc] +// snippet-start:[sqs.cpp.set_redrive_policy.inc] #include #include #include -//snippet-end:[sqs.cpp.set_redrive_policy.inc] +// snippet-end:[sqs.cpp.set_redrive_policy.inc] #include "sqs_samples.h" static Aws::String MakeRedrivePolicy(const Aws::String &queueArn, int maxReceiveCount); diff --git a/cpp/example_code/sqs/delete_message.cpp b/cpp/example_code/sqs/delete_message.cpp index cd62d2b9091..d7fafbb2a4d 100644 --- a/cpp/example_code/sqs/delete_message.cpp +++ b/cpp/example_code/sqs/delete_message.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,12 +12,12 @@ * **/ -//snippet-start:[sqs.cpp.delete_message.inc] +// snippet-start:[sqs.cpp.delete_message.inc] #include #include #include #include -//snippet-end:[sqs.cpp.delete_message.inc] +// snippet-end:[sqs.cpp.delete_message.inc] #include "sqs_samples.h" // snippet-start:[cpp.example_code.sqs.DeleteMessage] diff --git a/cpp/example_code/sqs/delete_queue.cpp b/cpp/example_code/sqs/delete_queue.cpp index 15281e9bd22..46f8bcd96b1 100644 --- a/cpp/example_code/sqs/delete_queue.cpp +++ b/cpp/example_code/sqs/delete_queue.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,13 +12,13 @@ * **/ -//snippet-start:[sqs.cpp.delete_queue.inc] +// snippet-start:[sqs.cpp.delete_queue.inc] #include #include #include #include #include -//snippet-end:[sqs.cpp.delete_queue.inc] +// snippet-end:[sqs.cpp.delete_queue.inc] #include "sqs_samples.h" // snippet-start:[cpp.example_code.sqs.DeleteQueue] diff --git a/cpp/example_code/sqs/get_queue_url.cpp b/cpp/example_code/sqs/get_queue_url.cpp index b37fdd782fd..dcb5ea792fd 100644 --- a/cpp/example_code/sqs/get_queue_url.cpp +++ b/cpp/example_code/sqs/get_queue_url.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,12 +12,12 @@ * **/ -//snippet-start:[sqs.cpp.get_queue_url.inc] +// snippet-start:[sqs.cpp.get_queue_url.inc] #include #include #include #include -//snippet-end:[sqs.cpp.get_queue_url.inc] +// snippet-end:[sqs.cpp.get_queue_url.inc] #include "sqs_samples.h" // snippet-start:[cpp.example_code.sqs.GetQueueUrl] diff --git a/cpp/example_code/sqs/hello_sqs/hello_sqs.cpp b/cpp/example_code/sqs/hello_sqs/hello_sqs.cpp index f2c6c62bd32..a27e308b754 100644 --- a/cpp/example_code/sqs/hello_sqs/hello_sqs.cpp +++ b/cpp/example_code/sqs/hello_sqs/hello_sqs.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/sqs/list_queues.cpp b/cpp/example_code/sqs/list_queues.cpp index b40d8b94d89..70a97d59463 100644 --- a/cpp/example_code/sqs/list_queues.cpp +++ b/cpp/example_code/sqs/list_queues.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,12 +12,12 @@ * **/ -//snippet-start:[sqs.cpp.list_queues.inc] +// snippet-start:[sqs.cpp.list_queues.inc] #include #include #include #include -//snippet-end:[sqs.cpp.list_queues.inc] +// snippet-end:[sqs.cpp.list_queues.inc] #include "sqs_samples.h" // snippet-start:[cpp.example_code.sqs.ListQueues] diff --git a/cpp/example_code/sqs/long_polling_on_create_queue.cpp b/cpp/example_code/sqs/long_polling_on_create_queue.cpp index 91c5623b0de..30b3b62d038 100644 --- a/cpp/example_code/sqs/long_polling_on_create_queue.cpp +++ b/cpp/example_code/sqs/long_polling_on_create_queue.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,12 +12,12 @@ * **/ -//snippet-start:[sqs.cpp.long_polling_on_create_queue.inc] +// snippet-start:[sqs.cpp.long_polling_on_create_queue.inc] #include #include #include #include -//snippet-end:[sqs.cpp.long_polling_on_create_queue.inc] +// snippet-end:[sqs.cpp.long_polling_on_create_queue.inc] #include "sqs_samples.h" //! Create an Amazon Simple Queue Service (Amazon SQS) queue configured for diff --git a/cpp/example_code/sqs/long_polling_on_existing_queue.cpp b/cpp/example_code/sqs/long_polling_on_existing_queue.cpp index 1c5a111ff3d..5fa6055a81d 100644 --- a/cpp/example_code/sqs/long_polling_on_existing_queue.cpp +++ b/cpp/example_code/sqs/long_polling_on_existing_queue.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,12 +12,12 @@ * **/ -//snippet-start:[sqs.cpp.long_polling_on_existing-queue.inc] +// snippet-start:[sqs.cpp.long_polling_on_existing-queue.inc] #include #include #include #include -//snippet-end:[sqs.cpp.long_polling_on_existing-queue.inc] +// snippet-end:[sqs.cpp.long_polling_on_existing-queue.inc] #include "sqs_samples.h" // snippet-start:[cpp.example_code.sqs.LongPollingAttribute] diff --git a/cpp/example_code/sqs/long_polling_on_message_receipt.cpp b/cpp/example_code/sqs/long_polling_on_message_receipt.cpp index 40adfed45d6..66e67c6a320 100644 --- a/cpp/example_code/sqs/long_polling_on_message_receipt.cpp +++ b/cpp/example_code/sqs/long_polling_on_message_receipt.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,11 +12,11 @@ * **/ -//snippet-start:[sqs.cpp.long_polling_on_message_receipt.inc] +// snippet-start:[sqs.cpp.long_polling_on_message_receipt.inc] #include #include #include -//snippet-end:[sqs.cpp.long_polling_on_message_receipt.inc] +// snippet-end:[sqs.cpp.long_polling_on_message_receipt.inc] #include #include #include "sqs_samples.h" diff --git a/cpp/example_code/sqs/purge_queue.cpp b/cpp/example_code/sqs/purge_queue.cpp index e162383ed04..8c817954528 100644 --- a/cpp/example_code/sqs/purge_queue.cpp +++ b/cpp/example_code/sqs/purge_queue.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/sqs/receive_message.cpp b/cpp/example_code/sqs/receive_message.cpp index 6a88d26f922..44c44d4cec1 100644 --- a/cpp/example_code/sqs/receive_message.cpp +++ b/cpp/example_code/sqs/receive_message.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,12 +12,12 @@ * **/ -//snippet-start:[sqs.cpp.receive_message.inc] +// snippet-start:[sqs.cpp.receive_message.inc] #include #include #include #include -//snippet-end:[sqs.cpp.receive_message.inc] +// snippet-end:[sqs.cpp.receive_message.inc] #include "sqs_samples.h" // snippet-start:[cpp.example_code.sqs.ReceiveMessage] diff --git a/cpp/example_code/sqs/send_message.cpp b/cpp/example_code/sqs/send_message.cpp index 459e3cc07b4..9defc603a14 100644 --- a/cpp/example_code/sqs/send_message.cpp +++ b/cpp/example_code/sqs/send_message.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * @@ -14,12 +12,12 @@ * **/ -//snippet-start:[sqs.cpp.send_message.inc] +// snippet-start:[sqs.cpp.send_message.inc] #include #include #include #include -//snippet-end:[sqs.cpp.send_message.inc] +// snippet-end:[sqs.cpp.send_message.inc] #include "sqs_samples.h" // snippet-start:[cpp.example_code.sqs.SendMessage] diff --git a/cpp/example_code/sqs/set_queue_attributes.cpp b/cpp/example_code/sqs/set_queue_attributes.cpp index 942591b9b0d..6a723c8d2fc 100644 --- a/cpp/example_code/sqs/set_queue_attributes.cpp +++ b/cpp/example_code/sqs/set_queue_attributes.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. * diff --git a/cpp/example_code/sqs/sqs_samples.h b/cpp/example_code/sqs/sqs_samples.h index bb24499e651..95283d20f30 100644 --- a/cpp/example_code/sqs/sqs_samples.h +++ b/cpp/example_code/sqs/sqs_samples.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef SQS_EXAMPLES_SQS_SAMPLES_H diff --git a/cpp/example_code/sqs/tests/gtest_change_message_visibility.cpp b/cpp/example_code/sqs/tests/gtest_change_message_visibility.cpp index a0728d2acb3..3f635006999 100644 --- a/cpp/example_code/sqs/tests/gtest_change_message_visibility.cpp +++ b/cpp/example_code/sqs/tests/gtest_change_message_visibility.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sqs/tests/gtest_create_queue.cpp b/cpp/example_code/sqs/tests/gtest_create_queue.cpp index bd261006b6b..2ba8531d1e6 100644 --- a/cpp/example_code/sqs/tests/gtest_create_queue.cpp +++ b/cpp/example_code/sqs/tests/gtest_create_queue.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sqs/tests/gtest_dead_letter_queue.cpp b/cpp/example_code/sqs/tests/gtest_dead_letter_queue.cpp index ccbbd91f928..012f8bf2351 100644 --- a/cpp/example_code/sqs/tests/gtest_dead_letter_queue.cpp +++ b/cpp/example_code/sqs/tests/gtest_dead_letter_queue.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sqs/tests/gtest_delete_message.cpp b/cpp/example_code/sqs/tests/gtest_delete_message.cpp index 73bdcddfb44..c35f61c296a 100644 --- a/cpp/example_code/sqs/tests/gtest_delete_message.cpp +++ b/cpp/example_code/sqs/tests/gtest_delete_message.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sqs/tests/gtest_delete_queue.cpp b/cpp/example_code/sqs/tests/gtest_delete_queue.cpp index 06cc46245a5..02889af0aea 100644 --- a/cpp/example_code/sqs/tests/gtest_delete_queue.cpp +++ b/cpp/example_code/sqs/tests/gtest_delete_queue.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sqs/tests/gtest_get_queue_url.cpp b/cpp/example_code/sqs/tests/gtest_get_queue_url.cpp index 7fae71be779..56ad83a0855 100644 --- a/cpp/example_code/sqs/tests/gtest_get_queue_url.cpp +++ b/cpp/example_code/sqs/tests/gtest_get_queue_url.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sqs/tests/gtest_list_queues.cpp b/cpp/example_code/sqs/tests/gtest_list_queues.cpp index 259e746468f..6bf0e67c7bf 100644 --- a/cpp/example_code/sqs/tests/gtest_list_queues.cpp +++ b/cpp/example_code/sqs/tests/gtest_list_queues.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sqs/tests/gtest_long_polling_on_create_queue.cpp b/cpp/example_code/sqs/tests/gtest_long_polling_on_create_queue.cpp index 6aaf8b77760..013db830046 100644 --- a/cpp/example_code/sqs/tests/gtest_long_polling_on_create_queue.cpp +++ b/cpp/example_code/sqs/tests/gtest_long_polling_on_create_queue.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sqs/tests/gtest_long_polling_on_existing_queue.cpp b/cpp/example_code/sqs/tests/gtest_long_polling_on_existing_queue.cpp index 6bde230c26a..1283ae8c0ae 100644 --- a/cpp/example_code/sqs/tests/gtest_long_polling_on_existing_queue.cpp +++ b/cpp/example_code/sqs/tests/gtest_long_polling_on_existing_queue.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sqs/tests/gtest_long_polling_on_message_receipt.cpp b/cpp/example_code/sqs/tests/gtest_long_polling_on_message_receipt.cpp index 16861a104e4..9492c42e073 100644 --- a/cpp/example_code/sqs/tests/gtest_long_polling_on_message_receipt.cpp +++ b/cpp/example_code/sqs/tests/gtest_long_polling_on_message_receipt.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sqs/tests/gtest_purge_queue.cpp b/cpp/example_code/sqs/tests/gtest_purge_queue.cpp index fa111521a11..46109654462 100644 --- a/cpp/example_code/sqs/tests/gtest_purge_queue.cpp +++ b/cpp/example_code/sqs/tests/gtest_purge_queue.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sqs/tests/gtest_receive_message.cpp b/cpp/example_code/sqs/tests/gtest_receive_message.cpp index 8db01d971f9..dd525a04c70 100644 --- a/cpp/example_code/sqs/tests/gtest_receive_message.cpp +++ b/cpp/example_code/sqs/tests/gtest_receive_message.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sqs/tests/gtest_send_message.cpp b/cpp/example_code/sqs/tests/gtest_send_message.cpp index 8fbd89f8e3e..2e4a1516131 100644 --- a/cpp/example_code/sqs/tests/gtest_send_message.cpp +++ b/cpp/example_code/sqs/tests/gtest_send_message.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sqs/tests/gtest_set_queue_attributes.cpp b/cpp/example_code/sqs/tests/gtest_set_queue_attributes.cpp index 5132471a2e4..9393adc4b9c 100644 --- a/cpp/example_code/sqs/tests/gtest_set_queue_attributes.cpp +++ b/cpp/example_code/sqs/tests/gtest_set_queue_attributes.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sqs/tests/sqs_gtests.cpp b/cpp/example_code/sqs/tests/sqs_gtests.cpp index 5ba4add4e53..a8962968c80 100644 --- a/cpp/example_code/sqs/tests/sqs_gtests.cpp +++ b/cpp/example_code/sqs/tests/sqs_gtests.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "sqs_gtests.h" #include diff --git a/cpp/example_code/sqs/tests/sqs_gtests.h b/cpp/example_code/sqs/tests/sqs_gtests.h index be98e784e0c..7cd8be0c355 100644 --- a/cpp/example_code/sqs/tests/sqs_gtests.h +++ b/cpp/example_code/sqs/tests/sqs_gtests.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef S3_EXAMPLES_S3_GTESTS_H diff --git a/cpp/example_code/sqs/tests/test_main.cpp b/cpp/example_code/sqs/tests/test_main.cpp index 00ed3e2b055..656f92cb221 100644 --- a/cpp/example_code/sqs/tests/test_main.cpp +++ b/cpp/example_code/sqs/tests/test_main.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "gtest/gtest.h" diff --git a/cpp/example_code/storage_gateway/create_nfs_file_share.cpp b/cpp/example_code/storage_gateway/create_nfs_file_share.cpp index 0ea8f1069bb..ebf77f2d28e 100644 --- a/cpp/example_code/storage_gateway/create_nfs_file_share.cpp +++ b/cpp/example_code/storage_gateway/create_nfs_file_share.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[create_nfs_file_share.cpp demonstrates how to create a Network File System (NFS) file share on an AWS Storage Gateway resource.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Storage Gateway] -//snippet-service:[storagegateway] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/storage_gateway/delete_volume.cpp b/cpp/example_code/storage_gateway/delete_volume.cpp index 094abda7ced..225033b78c5 100644 --- a/cpp/example_code/storage_gateway/delete_volume.cpp +++ b/cpp/example_code/storage_gateway/delete_volume.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[delete_volume.cpp demonstrates how to delete a volume ARN from an AWS Storage Gateway resource.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Storage Gateway] -//snippet-service:[storagegateway] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/storage_gateway/describe_gateway_information.cpp b/cpp/example_code/storage_gateway/describe_gateway_information.cpp index 0ae46dcb907..3ddd21540c2 100644 --- a/cpp/example_code/storage_gateway/describe_gateway_information.cpp +++ b/cpp/example_code/storage_gateway/describe_gateway_information.cpp @@ -1,24 +1,5 @@ -//snippet-sourcedescription:[describe_gateway_information.cpp demonstrates how to retrieve information pertaining to an AWS Storage Gateway resource.] -//snippet-service:[storagegateway] -//snippet-keyword:[AWS Storage Gateway] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include #include diff --git a/cpp/example_code/storage_gateway/describe_smb_settings.cpp b/cpp/example_code/storage_gateway/describe_smb_settings.cpp index 431426ee53f..8964bba3095 100644 --- a/cpp/example_code/storage_gateway/describe_smb_settings.cpp +++ b/cpp/example_code/storage_gateway/describe_smb_settings.cpp @@ -1,24 +1,5 @@ -//snippet-sourcedescription:[describe_smb_settings.cpp demonstrates how to retrieve information pertaining to the Server Message Block (SMB) settings for an AWS Storage Gateway resource.] -//snippet-service:[storagegateway] -//snippet-keyword:[AWS Storage Gateway] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include #include diff --git a/cpp/example_code/storage_gateway/list_file_shares.cpp b/cpp/example_code/storage_gateway/list_file_shares.cpp index 57cfb31d5d8..a2aa4184d34 100644 --- a/cpp/example_code/storage_gateway/list_file_shares.cpp +++ b/cpp/example_code/storage_gateway/list_file_shares.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[list_file_shares.cpp demonstrates how to retrieve a list of the file shares for an AWS Storage Gateway resource.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Storage Gateway] -//snippet-service:[storagegateway] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/storage_gateway/start_gateway.cpp b/cpp/example_code/storage_gateway/start_gateway.cpp index 3a76ab7412d..49dfe3eddff 100644 --- a/cpp/example_code/storage_gateway/start_gateway.cpp +++ b/cpp/example_code/storage_gateway/start_gateway.cpp @@ -1,25 +1,5 @@ - -//snippet-sourcedescription:[start_gateway.cpp demonstrates how to start an AWS Storage Gateway resource that was previously shut down.] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Storage Gateway] -//snippet-service:[storagegateway] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[tapasweni-pathak] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include diff --git a/cpp/example_code/sts/assume_role.cpp b/cpp/example_code/sts/assume_role.cpp index efb0f18c090..33ef6c11ced 100644 --- a/cpp/example_code/sts/assume_role.cpp +++ b/cpp/example_code/sts/assume_role.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Before running this C++ code example, set up your development environment, including your credentials. diff --git a/cpp/example_code/sts/sts_samples.h b/cpp/example_code/sts/sts_samples.h index 0b488eaf4de..42e2310f786 100644 --- a/cpp/example_code/sts/sts_samples.h +++ b/cpp/example_code/sts/sts_samples.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #ifndef README_MD_STS_SAMPLES_H #define README_MD_STS_SAMPLES_H diff --git a/cpp/example_code/sts/tests/gtest_assume_role.cpp b/cpp/example_code/sts/tests/gtest_assume_role.cpp index b8a2aa7190f..bd2eee8cdf0 100644 --- a/cpp/example_code/sts/tests/gtest_assume_role.cpp +++ b/cpp/example_code/sts/tests/gtest_assume_role.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Test types are indicated by the test label ending. * diff --git a/cpp/example_code/sts/tests/sts_gtests.cpp b/cpp/example_code/sts/tests/sts_gtests.cpp index 6f4592727b8..c31a505091e 100644 --- a/cpp/example_code/sts/tests/sts_gtests.cpp +++ b/cpp/example_code/sts/tests/sts_gtests.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "sts_gtests.h" #include diff --git a/cpp/example_code/sts/tests/sts_gtests.h b/cpp/example_code/sts/tests/sts_gtests.h index 25bc2e7d589..b0ddc7f0450 100644 --- a/cpp/example_code/sts/tests/sts_gtests.h +++ b/cpp/example_code/sts/tests/sts_gtests.h @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #pragma once #ifndef S3_EXAMPLES_S3_GTESTS_H diff --git a/cpp/example_code/sts/tests/test_main.cpp b/cpp/example_code/sts/tests/test_main.cpp index 00ed3e2b055..656f92cb221 100644 --- a/cpp/example_code/sts/tests/test_main.cpp +++ b/cpp/example_code/sts/tests/test_main.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include "gtest/gtest.h" diff --git a/cpp/example_code/transcribe/get_transcript.cpp b/cpp/example_code/transcribe/get_transcript.cpp index 110131a6591..a6e32f9c3af 100644 --- a/cpp/example_code/transcribe/get_transcript.cpp +++ b/cpp/example_code/transcribe/get_transcript.cpp @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 #include #include @@ -23,7 +21,7 @@ using namespace Aws::TranscribeStreamingService::Model; static const Aws::String FILE_NAME{MEDIA_DIR "/transcribe-test-file.wav"}; static const int BUFFER_SIZE = 1024; -//snippet-start:[transcribe.cpp.stream_transcription_async.code] +// snippet-start:[transcribe.cpp.stream_transcription_async.code] int main() { Aws::SDKOptions options; options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Trace; @@ -157,4 +155,4 @@ int main() { return 0; } -//snippet-end:[transcribe.cpp.stream_transcription_async.code] +// snippet-end:[transcribe.cpp.stream_transcription_async.code] diff --git a/cpp/example_code/transfer-manager/transferOnStream.cpp b/cpp/example_code/transfer-manager/transferOnStream.cpp index 4cf31dd5c9b..ba2fe50b19f 100644 --- a/cpp/example_code/transfer-manager/transferOnStream.cpp +++ b/cpp/example_code/transfer-manager/transferOnStream.cpp @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[transferOnStream.cpp demonstrates how to transfer an S3 object using stream into local memory and verify the correctness of the transfer] -//snippet-service:[s3] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[C++] -//snippet-sourcesyntax:[cpp] -//snippet-keyword:[Code Sample] -//snippet-sourcetype:[full-example] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. diff --git a/dotnetv3/.editorconfig b/dotnetv3/.editorconfig index ee74088424c..9adaa85bc47 100644 --- a/dotnetv3/.editorconfig +++ b/dotnetv3/.editorconfig @@ -128,7 +128,7 @@ csharp_space_between_square_brackets = false # Custom Rules # ############################### # File header. -file_header_template = Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. \nSPDX-License-Identifier: Apache-2.0 +file_header_template = Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. \nSPDX-License-Identifier: Apache-2.0 # SA0001: XML comment disable is allowed. dotnet_diagnostic.SA0001.severity = none # SA1600: Elements must be documented is disabled. diff --git a/dotnetv3/ACM/DescribeCertificates/DescribeCertificate/DescribeCertificate.cs b/dotnetv3/ACM/DescribeCertificates/DescribeCertificate/DescribeCertificate.cs index e44a3b4aff2..665e8c43ba5 100644 --- a/dotnetv3/ACM/DescribeCertificates/DescribeCertificate/DescribeCertificate.cs +++ b/dotnetv3/ACM/DescribeCertificates/DescribeCertificate/DescribeCertificate.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[ACM.dotnetv3.DescribeCertificate] using System; diff --git a/dotnetv3/ACM/DescribeCertificates/DescribeCertificateTest/DescribeCertificateTest.cs b/dotnetv3/ACM/DescribeCertificates/DescribeCertificateTest/DescribeCertificateTest.cs index 467b70ec9e7..258149be7e3 100644 --- a/dotnetv3/ACM/DescribeCertificates/DescribeCertificateTest/DescribeCertificateTest.cs +++ b/dotnetv3/ACM/DescribeCertificates/DescribeCertificateTest/DescribeCertificateTest.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System.Net; using System.Threading; diff --git a/dotnetv3/ACM/ListCertificates/ListCertificates/ListCertificates.cs b/dotnetv3/ACM/ListCertificates/ListCertificates/ListCertificates.cs index 6925cc2237c..e5cf3cef6c0 100644 --- a/dotnetv3/ACM/ListCertificates/ListCertificates/ListCertificates.cs +++ b/dotnetv3/ACM/ListCertificates/ListCertificates/ListCertificates.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[ACM.dotnetv3.ListCertificates] @@ -13,7 +13,7 @@ namespace ListCertificates { // The following example retrieves and displays a list of the // certificates defined for the default account using the AWS - // Certificate Manager (ACM) service. + // Certificate Manager (ACM) service. class ListCertificates { // Specify your AWS Region (an example Region is shown). diff --git a/dotnetv3/ACM/ListCertificates/ListCertificatesTest/ListCertificatesTest.cs b/dotnetv3/ACM/ListCertificates/ListCertificatesTest/ListCertificatesTest.cs index 6128c9b9933..fbce906f08b 100644 --- a/dotnetv3/ACM/ListCertificates/ListCertificatesTest/ListCertificatesTest.cs +++ b/dotnetv3/ACM/ListCertificates/ListCertificatesTest/ListCertificatesTest.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System.Net; using System.Threading; diff --git a/dotnetv3/Aurora/Actions/AuroraWrapper.cs b/dotnetv3/Aurora/Actions/AuroraWrapper.cs index 3849525c453..4633ea0d8d0 100644 --- a/dotnetv3/Aurora/Actions/AuroraWrapper.cs +++ b/dotnetv3/Aurora/Actions/AuroraWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Aurora.dotnetv3.AuroraWrapper] using Amazon.RDS; @@ -154,7 +154,7 @@ public async Task ModifyIntegerParametersInGroupAsync(string groupName, // snippet-start:[Aurora.dotnetv3.DescribeOrderableDBInstanceOptions] /// /// Get a list of orderable DB instance options for a specific - /// engine and engine version. + /// engine and engine version. /// /// Name of the engine. /// Version of the engine. diff --git a/dotnetv3/Aurora/Actions/HelloAurora.cs b/dotnetv3/Aurora/Actions/HelloAurora.cs index b6cdc5952b6..b556a406ddd 100644 --- a/dotnetv3/Aurora/Actions/HelloAurora.cs +++ b/dotnetv3/Aurora/Actions/HelloAurora.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Aurora.dotnetv3.HelloAurora] diff --git a/dotnetv3/Aurora/Scenarios/AuroraScenario.cs b/dotnetv3/Aurora/Scenarios/AuroraScenario.cs index b04ff34e2f6..dc5ea8d7f68 100644 --- a/dotnetv3/Aurora/Scenarios/AuroraScenario.cs +++ b/dotnetv3/Aurora/Scenarios/AuroraScenario.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Aurora.dotnetv3.AuroraClusterScenario] diff --git a/dotnetv3/Aurora/Tests/AuroraScenarioTests.cs b/dotnetv3/Aurora/Tests/AuroraScenarioTests.cs index e15e41fc0d7..d7aa66b2851 100644 --- a/dotnetv3/Aurora/Tests/AuroraScenarioTests.cs +++ b/dotnetv3/Aurora/Tests/AuroraScenarioTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.RDS; using Amazon.RDS.Model; diff --git a/dotnetv3/Aurora/Tests/Usings.cs b/dotnetv3/Aurora/Tests/Usings.cs index 158ebd88747..ef5ce323ba9 100644 --- a/dotnetv3/Aurora/Tests/Usings.cs +++ b/dotnetv3/Aurora/Tests/Usings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Xunit; global using Xunit.Extensions.Ordering; diff --git a/dotnetv3/AutoScaling/Actions/AutoScalingWrapper.cs b/dotnetv3/AutoScaling/Actions/AutoScalingWrapper.cs index 63e3a870875..f4b70b65baa 100644 --- a/dotnetv3/AutoScaling/Actions/AutoScalingWrapper.cs +++ b/dotnetv3/AutoScaling/Actions/AutoScalingWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[AutoScaling.dotnetv3.AutoScalingActions.AutoScalingWrapper] diff --git a/dotnetv3/AutoScaling/Actions/CloudWatchWrapper.cs b/dotnetv3/AutoScaling/Actions/CloudWatchWrapper.cs index 7861eed210f..16442e6b0a2 100644 --- a/dotnetv3/AutoScaling/Actions/CloudWatchWrapper.cs +++ b/dotnetv3/AutoScaling/Actions/CloudWatchWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[AutoScaling.dotnetv3.AutoScalingActions.CloudWatchWrapper] namespace AutoScalingActions; diff --git a/dotnetv3/AutoScaling/Actions/EC2Wrapper.cs b/dotnetv3/AutoScaling/Actions/EC2Wrapper.cs index df0f6503747..2d2791ffe8b 100644 --- a/dotnetv3/AutoScaling/Actions/EC2Wrapper.cs +++ b/dotnetv3/AutoScaling/Actions/EC2Wrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[AutoScaling.dotnetv3.AutoScalingActions.EC2Wrapper] namespace AutoScalingActions; diff --git a/dotnetv3/AutoScaling/Actions/HelloAutoScaling.cs b/dotnetv3/AutoScaling/Actions/HelloAutoScaling.cs index b8e5694fbe3..a26ce71b94f 100644 --- a/dotnetv3/AutoScaling/Actions/HelloAutoScaling.cs +++ b/dotnetv3/AutoScaling/Actions/HelloAutoScaling.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[AutoScaling.dotnetv3.AutoScalingActions.HelloAutoScaling] diff --git a/dotnetv3/AutoScaling/Scenarios/AutoScalingBasics/AutoScalingBasics.cs b/dotnetv3/AutoScaling/Scenarios/AutoScalingBasics/AutoScalingBasics.cs index dc809b39765..c50b0317be0 100644 --- a/dotnetv3/AutoScaling/Scenarios/AutoScalingBasics/AutoScalingBasics.cs +++ b/dotnetv3/AutoScaling/Scenarios/AutoScalingBasics/AutoScalingBasics.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[AutoScaling.dotnetv3.AutoScalingBasics] diff --git a/dotnetv3/AutoScaling/Scenarios/AutoScalingBasics/UIWrapper.cs b/dotnetv3/AutoScaling/Scenarios/AutoScalingBasics/UIWrapper.cs index 45dfdf2e5c0..138e85a1baf 100644 --- a/dotnetv3/AutoScaling/Scenarios/AutoScalingBasics/UIWrapper.cs +++ b/dotnetv3/AutoScaling/Scenarios/AutoScalingBasics/UIWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[AutoScaling.dotnetv3.AutoScalingBasics.UIWrapper] namespace AutoScalingBasics; diff --git a/dotnetv3/AutoScaling/Scenarios/AutoScalingBasics/Usings.cs b/dotnetv3/AutoScaling/Scenarios/AutoScalingBasics/Usings.cs index 663fb170fe0..d9f9a77dda5 100644 --- a/dotnetv3/AutoScaling/Scenarios/AutoScalingBasics/Usings.cs +++ b/dotnetv3/AutoScaling/Scenarios/AutoScalingBasics/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[AutoScaling.dotnetv3.AutoScalingBasics.Usings] global using Amazon.AutoScaling; diff --git a/dotnetv3/AutoScaling/Tests/AutoScalingWrapperTests.cs b/dotnetv3/AutoScaling/Tests/AutoScalingWrapperTests.cs index d9f3644c65e..61ed7e38502 100644 --- a/dotnetv3/AutoScaling/Tests/AutoScalingWrapperTests.cs +++ b/dotnetv3/AutoScaling/Tests/AutoScalingWrapperTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.AutoScaling; using Amazon.AutoScaling.Model; diff --git a/dotnetv3/AutoScaling/Tests/Usings.cs b/dotnetv3/AutoScaling/Tests/Usings.cs index 719b04136e3..244d4d63eea 100644 --- a/dotnetv3/AutoScaling/Tests/Usings.cs +++ b/dotnetv3/AutoScaling/Tests/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 global using Amazon.CloudWatch; global using Amazon.EC2; diff --git a/dotnetv3/Bedrock/Actions/HelloBedrock.cs b/dotnetv3/Bedrock/Actions/HelloBedrock.cs index 3c68c6d3cb5..a25ca9e0621 100644 --- a/dotnetv3/Bedrock/Actions/HelloBedrock.cs +++ b/dotnetv3/Bedrock/Actions/HelloBedrock.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Bedrock.dotnetv3.BedrockActions.HelloBedrock] using Amazon; diff --git a/dotnetv3/Bedrock/Tests/BedrockTest.cs b/dotnetv3/Bedrock/Tests/BedrockTest.cs index c8b90ca2e64..8498c219276 100644 --- a/dotnetv3/Bedrock/Tests/BedrockTest.cs +++ b/dotnetv3/Bedrock/Tests/BedrockTest.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon.Bedrock; using Amazon.Bedrock.Model; diff --git a/dotnetv3/Bedrock/Tests/GlobalUsings.cs b/dotnetv3/Bedrock/Tests/GlobalUsings.cs index 158ebd88747..ef5ce323ba9 100644 --- a/dotnetv3/Bedrock/Tests/GlobalUsings.cs +++ b/dotnetv3/Bedrock/Tests/GlobalUsings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Xunit; global using Xunit.Extensions.Ordering; diff --git a/dotnetv3/BedrockRuntime/Actions/HelloBedrockRuntime.cs b/dotnetv3/BedrockRuntime/Actions/HelloBedrockRuntime.cs index c966096b48e..1ee5a0bf9ea 100644 --- a/dotnetv3/BedrockRuntime/Actions/HelloBedrockRuntime.cs +++ b/dotnetv3/BedrockRuntime/Actions/HelloBedrockRuntime.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 namespace BedrockRuntimeActions { diff --git a/dotnetv3/BedrockRuntime/Actions/InvokeModelAsync.cs b/dotnetv3/BedrockRuntime/Actions/InvokeModelAsync.cs index ab31122c590..e0344079974 100644 --- a/dotnetv3/BedrockRuntime/Actions/InvokeModelAsync.cs +++ b/dotnetv3/BedrockRuntime/Actions/InvokeModelAsync.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System.Text.Json.Nodes; using Amazon; diff --git a/dotnetv3/BedrockRuntime/Tests/GlobalUsings.cs b/dotnetv3/BedrockRuntime/Tests/GlobalUsings.cs index 158ebd88747..ef5ce323ba9 100644 --- a/dotnetv3/BedrockRuntime/Tests/GlobalUsings.cs +++ b/dotnetv3/BedrockRuntime/Tests/GlobalUsings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Xunit; global using Xunit.Extensions.Ordering; diff --git a/dotnetv3/BedrockRuntime/Tests/TextToTextAsyncTest.cs b/dotnetv3/BedrockRuntime/Tests/TextToTextAsyncTest.cs index 8ff1105a420..7820facb307 100644 --- a/dotnetv3/BedrockRuntime/Tests/TextToTextAsyncTest.cs +++ b/dotnetv3/BedrockRuntime/Tests/TextToTextAsyncTest.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using BedrockRuntimeActions; namespace BedrockRuntimeTests; diff --git a/dotnetv3/CloudWatch/Actions/CloudWatchClasses.cs b/dotnetv3/CloudWatch/Actions/CloudWatchClasses.cs index cbba6ed8a8c..04a94333f66 100644 --- a/dotnetv3/CloudWatch/Actions/CloudWatchClasses.cs +++ b/dotnetv3/CloudWatch/Actions/CloudWatchClasses.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Text.Json.Serialization; diff --git a/dotnetv3/CloudWatch/Actions/CloudWatchWrapper.cs b/dotnetv3/CloudWatch/Actions/CloudWatchWrapper.cs index d78188bc8fe..ac7d9c24ef2 100644 --- a/dotnetv3/CloudWatch/Actions/CloudWatchWrapper.cs +++ b/dotnetv3/CloudWatch/Actions/CloudWatchWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Net; using System.Text.Json; diff --git a/dotnetv3/CloudWatch/Actions/HelloCloudWatch.cs b/dotnetv3/CloudWatch/Actions/HelloCloudWatch.cs index 614f26be6b4..4c098334dd0 100644 --- a/dotnetv3/CloudWatch/Actions/HelloCloudWatch.cs +++ b/dotnetv3/CloudWatch/Actions/HelloCloudWatch.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[CloudWatch.dotnetv3.HelloCloudWatch] using Amazon.CloudWatch; diff --git a/dotnetv3/CloudWatch/Scenarios/CloudWatchScenario.cs b/dotnetv3/CloudWatch/Scenarios/CloudWatchScenario.cs index de3a9a83393..0b1cbb1f65c 100644 --- a/dotnetv3/CloudWatch/Scenarios/CloudWatchScenario.cs +++ b/dotnetv3/CloudWatch/Scenarios/CloudWatchScenario.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Diagnostics; using System.Text.Json; diff --git a/dotnetv3/CloudWatch/Tests/CloudWatchTests.cs b/dotnetv3/CloudWatch/Tests/CloudWatchTests.cs index ff0da42127b..4790b98cd1e 100644 --- a/dotnetv3/CloudWatch/Tests/CloudWatchTests.cs +++ b/dotnetv3/CloudWatch/Tests/CloudWatchTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Text; using System.Text.Json; diff --git a/dotnetv3/CloudWatch/Tests/Usings.cs b/dotnetv3/CloudWatch/Tests/Usings.cs index 158ebd88747..ef5ce323ba9 100644 --- a/dotnetv3/CloudWatch/Tests/Usings.cs +++ b/dotnetv3/CloudWatch/Tests/Usings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Xunit; global using Xunit.Extensions.Ordering; diff --git a/dotnetv3/CloudWatchLogs/AssociateKmsKeyExample/AssociateKmsKey.cs b/dotnetv3/CloudWatchLogs/AssociateKmsKeyExample/AssociateKmsKey.cs index b45ea127c24..70e49fbc9fe 100644 --- a/dotnetv3/CloudWatchLogs/AssociateKmsKeyExample/AssociateKmsKey.cs +++ b/dotnetv3/CloudWatchLogs/AssociateKmsKeyExample/AssociateKmsKey.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace AssociateKmsKeyExample { diff --git a/dotnetv3/CloudWatchLogs/CancelExportTaskExample/CancelExportTask.cs b/dotnetv3/CloudWatchLogs/CancelExportTaskExample/CancelExportTask.cs index 63875bb3152..5fc6b6a1bc6 100644 --- a/dotnetv3/CloudWatchLogs/CancelExportTaskExample/CancelExportTask.cs +++ b/dotnetv3/CloudWatchLogs/CancelExportTaskExample/CancelExportTask.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace CancelExportTaskExample { diff --git a/dotnetv3/CloudWatchLogs/CreateExportTaskExample/CreateExportTask.cs b/dotnetv3/CloudWatchLogs/CreateExportTaskExample/CreateExportTask.cs index dec98cac236..f093c31e4f5 100644 --- a/dotnetv3/CloudWatchLogs/CreateExportTaskExample/CreateExportTask.cs +++ b/dotnetv3/CloudWatchLogs/CreateExportTaskExample/CreateExportTask.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace CreateExportTaskExample { diff --git a/dotnetv3/CloudWatchLogs/CreateLogGroupExample/CreateLogGroup.cs b/dotnetv3/CloudWatchLogs/CreateLogGroupExample/CreateLogGroup.cs index 8083be7680a..02831906522 100644 --- a/dotnetv3/CloudWatchLogs/CreateLogGroupExample/CreateLogGroup.cs +++ b/dotnetv3/CloudWatchLogs/CreateLogGroupExample/CreateLogGroup.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace CreateLogGroupExample { diff --git a/dotnetv3/CloudWatchLogs/CreateLogStreamExample/CreateLogStream.cs b/dotnetv3/CloudWatchLogs/CreateLogStreamExample/CreateLogStream.cs index 31ee442de20..28e36ee6e32 100644 --- a/dotnetv3/CloudWatchLogs/CreateLogStreamExample/CreateLogStream.cs +++ b/dotnetv3/CloudWatchLogs/CreateLogStreamExample/CreateLogStream.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace CreateLogStreamExample { diff --git a/dotnetv3/CloudWatchLogs/DeleteLogGroupExample/DeleteLogGroup.cs b/dotnetv3/CloudWatchLogs/DeleteLogGroupExample/DeleteLogGroup.cs index 0581c0169d8..c203b87f3e2 100644 --- a/dotnetv3/CloudWatchLogs/DeleteLogGroupExample/DeleteLogGroup.cs +++ b/dotnetv3/CloudWatchLogs/DeleteLogGroupExample/DeleteLogGroup.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DeleteLogGroupExample { diff --git a/dotnetv3/CloudWatchLogs/DescribeExportTasksExample/DescribeExportTasks.cs b/dotnetv3/CloudWatchLogs/DescribeExportTasksExample/DescribeExportTasks.cs index d8ab508fffb..8b206190f16 100644 --- a/dotnetv3/CloudWatchLogs/DescribeExportTasksExample/DescribeExportTasks.cs +++ b/dotnetv3/CloudWatchLogs/DescribeExportTasksExample/DescribeExportTasks.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DescribeExportTasksExample { diff --git a/dotnetv3/CloudWatchLogs/DescribeLogGroupsExample/DescribeLogGroups.cs b/dotnetv3/CloudWatchLogs/DescribeLogGroupsExample/DescribeLogGroups.cs index accf6d01ae4..5cd98bb90de 100644 --- a/dotnetv3/CloudWatchLogs/DescribeLogGroupsExample/DescribeLogGroups.cs +++ b/dotnetv3/CloudWatchLogs/DescribeLogGroupsExample/DescribeLogGroups.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DescribeLogGroupsExample { diff --git a/dotnetv3/Cognito/Actions/CognitoWrapper.cs b/dotnetv3/Cognito/Actions/CognitoWrapper.cs index 348cb90766a..5ed4e8d313b 100644 --- a/dotnetv3/Cognito/Actions/CognitoWrapper.cs +++ b/dotnetv3/Cognito/Actions/CognitoWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Cognito.dotnetv3.CognitoWrapper] using System.Net; diff --git a/dotnetv3/Cognito/Actions/HelloCognito.cs b/dotnetv3/Cognito/Actions/HelloCognito.cs index 31586e42ef6..4c1544d2b4e 100644 --- a/dotnetv3/Cognito/Actions/HelloCognito.cs +++ b/dotnetv3/Cognito/Actions/HelloCognito.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Cognito.dotnetv3.HelloCognito] diff --git a/dotnetv3/Cognito/Actions/Usings.cs b/dotnetv3/Cognito/Actions/Usings.cs index a5f8f185974..5b7cea27136 100644 --- a/dotnetv3/Cognito/Actions/Usings.cs +++ b/dotnetv3/Cognito/Actions/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Cognito.dotnetv3.Usings] global using Amazon.CognitoIdentityProvider; diff --git a/dotnetv3/Cognito/Scenarios/Cognito_Basics/CognitoBasics.cs b/dotnetv3/Cognito/Scenarios/Cognito_Basics/CognitoBasics.cs index 75ade90fa19..d6325295ab8 100644 --- a/dotnetv3/Cognito/Scenarios/Cognito_Basics/CognitoBasics.cs +++ b/dotnetv3/Cognito/Scenarios/Cognito_Basics/CognitoBasics.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Cognito.dotnetv3.Main] namespace CognitoBasics; diff --git a/dotnetv3/Cognito/Scenarios/Cognito_Basics/UIMethods.cs b/dotnetv3/Cognito/Scenarios/Cognito_Basics/UIMethods.cs index 379ea9c5bbb..a47ff135f3a 100644 --- a/dotnetv3/Cognito/Scenarios/Cognito_Basics/UIMethods.cs +++ b/dotnetv3/Cognito/Scenarios/Cognito_Basics/UIMethods.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Cognito.dotnetv3.UIMethods] namespace CognitoBasics; diff --git a/dotnetv3/Cognito/Scenarios/Cognito_Basics/Usings.cs b/dotnetv3/Cognito/Scenarios/Cognito_Basics/Usings.cs index f264a8837d0..4c437bc4948 100644 --- a/dotnetv3/Cognito/Scenarios/Cognito_Basics/Usings.cs +++ b/dotnetv3/Cognito/Scenarios/Cognito_Basics/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Cognito.dotnetv3.CognitoBasics.Usings] global using Amazon.CognitoIdentityProvider; diff --git a/dotnetv3/Cognito/Tests/CognitoWrapperTests.cs b/dotnetv3/Cognito/Tests/CognitoWrapperTests.cs index 0ecf65211c3..3c8d5201a01 100644 --- a/dotnetv3/Cognito/Tests/CognitoWrapperTests.cs +++ b/dotnetv3/Cognito/Tests/CognitoWrapperTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.CognitoIdentityProvider; using Microsoft.Extensions.Configuration; diff --git a/dotnetv3/Cognito/Tests/Usings.cs b/dotnetv3/Cognito/Tests/Usings.cs index c8c3aaf303c..1e20d1f76ce 100644 --- a/dotnetv3/Cognito/Tests/Usings.cs +++ b/dotnetv3/Cognito/Tests/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 global using CognitoActions; global using Xunit; diff --git a/dotnetv3/Comprehend/DetectDominantLanguageExample/DetectDominantLanguageExample/DetectDominantLanguage.cs b/dotnetv3/Comprehend/DetectDominantLanguageExample/DetectDominantLanguageExample/DetectDominantLanguage.cs index e1b2eac7615..ec75feeb810 100644 --- a/dotnetv3/Comprehend/DetectDominantLanguageExample/DetectDominantLanguageExample/DetectDominantLanguage.cs +++ b/dotnetv3/Comprehend/DetectDominantLanguageExample/DetectDominantLanguageExample/DetectDominantLanguage.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DetectDominantLanguageExample { diff --git a/dotnetv3/Comprehend/DetectEntitiesExample/DetectEntitiesExample/DetectEntities.cs b/dotnetv3/Comprehend/DetectEntitiesExample/DetectEntitiesExample/DetectEntities.cs index c7a4075d046..77a30ef6dd0 100644 --- a/dotnetv3/Comprehend/DetectEntitiesExample/DetectEntitiesExample/DetectEntities.cs +++ b/dotnetv3/Comprehend/DetectEntitiesExample/DetectEntitiesExample/DetectEntities.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DetectEntitiesExample { diff --git a/dotnetv3/Comprehend/DetectKeyPhraseExample/DetectKeyPhraseExample/DetectKeyPhrase.cs b/dotnetv3/Comprehend/DetectKeyPhraseExample/DetectKeyPhraseExample/DetectKeyPhrase.cs index bfa4d177eaf..82cca0f943d 100644 --- a/dotnetv3/Comprehend/DetectKeyPhraseExample/DetectKeyPhraseExample/DetectKeyPhrase.cs +++ b/dotnetv3/Comprehend/DetectKeyPhraseExample/DetectKeyPhraseExample/DetectKeyPhrase.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DetectKeyPhraseExample { diff --git a/dotnetv3/Comprehend/DetectSentimentExample/DetectSentimentExample/DetectSentiment.cs b/dotnetv3/Comprehend/DetectSentimentExample/DetectSentimentExample/DetectSentiment.cs index f37e0c5421c..371ee4d2d86 100644 --- a/dotnetv3/Comprehend/DetectSentimentExample/DetectSentimentExample/DetectSentiment.cs +++ b/dotnetv3/Comprehend/DetectSentimentExample/DetectSentimentExample/DetectSentiment.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DetectSentimentExample { diff --git a/dotnetv3/Comprehend/DetectingPIIExample/DetectingPIIExample/DetectingPII.cs b/dotnetv3/Comprehend/DetectingPIIExample/DetectingPIIExample/DetectingPII.cs index 074a1db7ae2..ccca3cd298c 100644 --- a/dotnetv3/Comprehend/DetectingPIIExample/DetectingPIIExample/DetectingPII.cs +++ b/dotnetv3/Comprehend/DetectingPIIExample/DetectingPIIExample/DetectingPII.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DetectingPIIExample { diff --git a/dotnetv3/Comprehend/DetectingSyntaxExample/DetectingSyntaxExample/DetectingSyntax.cs b/dotnetv3/Comprehend/DetectingSyntaxExample/DetectingSyntaxExample/DetectingSyntax.cs index 4927bd2d8ff..d4fcef26d96 100644 --- a/dotnetv3/Comprehend/DetectingSyntaxExample/DetectingSyntaxExample/DetectingSyntax.cs +++ b/dotnetv3/Comprehend/DetectingSyntaxExample/DetectingSyntaxExample/DetectingSyntax.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DetectingSyntaxExample { diff --git a/dotnetv3/Comprehend/TopicModelingExample/TopicModelingExample/TopicModeling.cs b/dotnetv3/Comprehend/TopicModelingExample/TopicModelingExample/TopicModeling.cs index 654005a4946..f87b243e763 100644 --- a/dotnetv3/Comprehend/TopicModelingExample/TopicModelingExample/TopicModeling.cs +++ b/dotnetv3/Comprehend/TopicModelingExample/TopicModelingExample/TopicModeling.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace TopicModelingExample { diff --git a/dotnetv3/EC2/Actions/EC2Wrapper.cs b/dotnetv3/EC2/Actions/EC2Wrapper.cs index 6b1ea77a3f6..9dd1cbb9ac8 100644 --- a/dotnetv3/EC2/Actions/EC2Wrapper.cs +++ b/dotnetv3/EC2/Actions/EC2Wrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace EC2Actions; @@ -675,7 +675,7 @@ public async Task StopInstances(string ec2InstanceId) }); } } - //snippet-end:[EC2.dotnetv3.StopInstances] + // snippet-end:[EC2.dotnetv3.StopInstances] // snippet-start:[EC2.dotnetv3.TerminateInstances] /// diff --git a/dotnetv3/EC2/Actions/HelloEC2.cs b/dotnetv3/EC2/Actions/HelloEC2.cs index 5cd0a630d5f..3c92a63d1d6 100644 --- a/dotnetv3/EC2/Actions/HelloEC2.cs +++ b/dotnetv3/EC2/Actions/HelloEC2.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[EC2.dotnetv3.HelloEc2] diff --git a/dotnetv3/EC2/Actions/SsmWrapper.cs b/dotnetv3/EC2/Actions/SsmWrapper.cs index fc77ff15626..d0917e2fdb7 100644 --- a/dotnetv3/EC2/Actions/SsmWrapper.cs +++ b/dotnetv3/EC2/Actions/SsmWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace EC2Actions; diff --git a/dotnetv3/EC2/Actions/Usings.cs b/dotnetv3/EC2/Actions/Usings.cs index a071fe162ce..3125ba51a46 100644 --- a/dotnetv3/EC2/Actions/Usings.cs +++ b/dotnetv3/EC2/Actions/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 global using System.Net; global using Amazon.EC2; diff --git a/dotnetv3/EC2/Scenarios/EC2_Basics/EC2Basics.cs b/dotnetv3/EC2/Scenarios/EC2_Basics/EC2Basics.cs index 644d5b9dd71..e345a79501e 100644 --- a/dotnetv3/EC2/Scenarios/EC2_Basics/EC2Basics.cs +++ b/dotnetv3/EC2/Scenarios/EC2_Basics/EC2Basics.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace Ec2_Basics; diff --git a/dotnetv3/EC2/Scenarios/EC2_Basics/UIMethods.cs b/dotnetv3/EC2/Scenarios/EC2_Basics/UIMethods.cs index 909d5d32b7d..cdfdd3c9d49 100644 --- a/dotnetv3/EC2/Scenarios/EC2_Basics/UIMethods.cs +++ b/dotnetv3/EC2/Scenarios/EC2_Basics/UIMethods.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace Ec2_Basics; diff --git a/dotnetv3/EC2/Scenarios/EC2_Basics/Usings.cs b/dotnetv3/EC2/Scenarios/EC2_Basics/Usings.cs index e636db8e0f8..900533b5c09 100644 --- a/dotnetv3/EC2/Scenarios/EC2_Basics/Usings.cs +++ b/dotnetv3/EC2/Scenarios/EC2_Basics/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 global using Amazon.EC2; global using Amazon.SimpleSystemsManagement; diff --git a/dotnetv3/EC2/Tests/EC2WrapperTests.cs b/dotnetv3/EC2/Tests/EC2WrapperTests.cs index e0631f89684..346940e0046 100644 --- a/dotnetv3/EC2/Tests/EC2WrapperTests.cs +++ b/dotnetv3/EC2/Tests/EC2WrapperTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace EC2Tests; /// diff --git a/dotnetv3/EC2/Tests/Usings.cs b/dotnetv3/EC2/Tests/Usings.cs index 203252c2af4..3556203b6fc 100644 --- a/dotnetv3/EC2/Tests/Usings.cs +++ b/dotnetv3/EC2/Tests/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 global using Amazon.EC2; global using Amazon.EC2.Model; diff --git a/dotnetv3/EC2/VirtualPrivateCloudExamples/CreateVPCExample/CreateVPC.cs b/dotnetv3/EC2/VirtualPrivateCloudExamples/CreateVPCExample/CreateVPC.cs index 0c754f103a8..59c3d6365f3 100644 --- a/dotnetv3/EC2/VirtualPrivateCloudExamples/CreateVPCExample/CreateVPC.cs +++ b/dotnetv3/EC2/VirtualPrivateCloudExamples/CreateVPCExample/CreateVPC.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace CreateVPCExample { diff --git a/dotnetv3/EC2/VirtualPrivateCloudExamples/CreateVPCTests/CreateVPCforS3Tests.cs b/dotnetv3/EC2/VirtualPrivateCloudExamples/CreateVPCTests/CreateVPCforS3Tests.cs index cf9ce668421..71b15c02b88 100644 --- a/dotnetv3/EC2/VirtualPrivateCloudExamples/CreateVPCTests/CreateVPCforS3Tests.cs +++ b/dotnetv3/EC2/VirtualPrivateCloudExamples/CreateVPCTests/CreateVPCforS3Tests.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon.EC2; using CreateVPCforS3Example; diff --git a/dotnetv3/EC2/VirtualPrivateCloudExamples/CreateVPCTests/Usings.cs b/dotnetv3/EC2/VirtualPrivateCloudExamples/CreateVPCTests/Usings.cs index 92fe41799a7..24f9d54e547 100644 --- a/dotnetv3/EC2/VirtualPrivateCloudExamples/CreateVPCTests/Usings.cs +++ b/dotnetv3/EC2/VirtualPrivateCloudExamples/CreateVPCTests/Usings.cs @@ -1,4 +1,4 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Xunit; \ No newline at end of file diff --git a/dotnetv3/EC2/VirtualPrivateCloudExamples/CreateVPCforS3Example/CreateVPCforS3.cs b/dotnetv3/EC2/VirtualPrivateCloudExamples/CreateVPCforS3Example/CreateVPCforS3.cs index ee36c7995d4..cc0776d7160 100644 --- a/dotnetv3/EC2/VirtualPrivateCloudExamples/CreateVPCforS3Example/CreateVPCforS3.cs +++ b/dotnetv3/EC2/VirtualPrivateCloudExamples/CreateVPCforS3Example/CreateVPCforS3.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.EC2; diff --git a/dotnetv3/ECS/ECSActions/ECSWrapper.cs b/dotnetv3/ECS/ECSActions/ECSWrapper.cs index d6e89ac1168..c9f5cc87609 100644 --- a/dotnetv3/ECS/ECSActions/ECSWrapper.cs +++ b/dotnetv3/ECS/ECSActions/ECSWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[ECS.dotnetv3.ECSActions.ECSWrapper] using Amazon.ECS; diff --git a/dotnetv3/ECS/ECSActions/HelloECS.cs b/dotnetv3/ECS/ECSActions/HelloECS.cs index da4729e6288..551baaad333 100644 --- a/dotnetv3/ECS/ECSActions/HelloECS.cs +++ b/dotnetv3/ECS/ECSActions/HelloECS.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[ECS.dotnetv3.ECSActions.HelloECS] using Amazon.ECS; diff --git a/dotnetv3/ECS/ECSScenario/ECSScenario.cs b/dotnetv3/ECS/ECSScenario/ECSScenario.cs index 5b5316fea4f..d73829adfb4 100644 --- a/dotnetv3/ECS/ECSScenario/ECSScenario.cs +++ b/dotnetv3/ECS/ECSScenario/ECSScenario.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[ECS.dotnetv3.ECSScenario.ECSScenario] using Amazon.ECS; diff --git a/dotnetv3/ECS/ECSTests/ECSTests.cs b/dotnetv3/ECS/ECSTests/ECSTests.cs index b1ce5e927c0..811b0f2ef01 100644 --- a/dotnetv3/ECS/ECSTests/ECSTests.cs +++ b/dotnetv3/ECS/ECSTests/ECSTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.ECS; using ECSActions; diff --git a/dotnetv3/ECS/ECSTests/Usings.cs b/dotnetv3/ECS/ECSTests/Usings.cs index 12de9bcff4d..c7faaf02f74 100644 --- a/dotnetv3/ECS/ECSTests/Usings.cs +++ b/dotnetv3/ECS/ECSTests/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 global using Xunit; global using Xunit.Extensions.Ordering; diff --git a/dotnetv3/EventBridge/Actions/EventBridgeWrapper.cs b/dotnetv3/EventBridge/Actions/EventBridgeWrapper.cs index 69d0ca2b0ee..46300b6f986 100644 --- a/dotnetv3/EventBridge/Actions/EventBridgeWrapper.cs +++ b/dotnetv3/EventBridge/Actions/EventBridgeWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Net; using System.Text.Json; diff --git a/dotnetv3/EventBridge/Actions/HelloEventBridge.cs b/dotnetv3/EventBridge/Actions/HelloEventBridge.cs index 1f6188289be..6c16980b686 100644 --- a/dotnetv3/EventBridge/Actions/HelloEventBridge.cs +++ b/dotnetv3/EventBridge/Actions/HelloEventBridge.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[EventBridge.dotnetv3.HelloEventBridge] diff --git a/dotnetv3/EventBridge/CreateRule/Program.cs b/dotnetv3/EventBridge/CreateRule/Program.cs index f2ba45768f0..46f5f2cbc7c 100644 --- a/dotnetv3/EventBridge/CreateRule/Program.cs +++ b/dotnetv3/EventBridge/CreateRule/Program.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.EventBridge; using Amazon.EventBridge.Model; diff --git a/dotnetv3/EventBridge/Scenarios/EventBridgeScenario.cs b/dotnetv3/EventBridge/Scenarios/EventBridgeScenario.cs index 60a8b308212..6dfe711ca74 100644 --- a/dotnetv3/EventBridge/Scenarios/EventBridgeScenario.cs +++ b/dotnetv3/EventBridge/Scenarios/EventBridgeScenario.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.EventBridge; using Amazon.IdentityManagement; diff --git a/dotnetv3/EventBridge/Tests/EventBridgeTests.cs b/dotnetv3/EventBridge/Tests/EventBridgeTests.cs index 2da52157451..5fb30343db2 100644 --- a/dotnetv3/EventBridge/Tests/EventBridgeTests.cs +++ b/dotnetv3/EventBridge/Tests/EventBridgeTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.EventBridge; using EventBridgeActions; diff --git a/dotnetv3/EventBridge/Tests/Usings.cs b/dotnetv3/EventBridge/Tests/Usings.cs index 158ebd88747..ef5ce323ba9 100644 --- a/dotnetv3/EventBridge/Tests/Usings.cs +++ b/dotnetv3/EventBridge/Tests/Usings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Xunit; global using Xunit.Extensions.Ordering; diff --git a/dotnetv3/Glacier/Actions/GlacierWrapper.cs b/dotnetv3/Glacier/Actions/GlacierWrapper.cs index 8839bc115d5..fee7fd2ec8b 100644 --- a/dotnetv3/Glacier/Actions/GlacierWrapper.cs +++ b/dotnetv3/Glacier/Actions/GlacierWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Glacier.dotnetv3.GlacierActions] diff --git a/dotnetv3/Glacier/Actions/HelloGlacier.cs b/dotnetv3/Glacier/Actions/HelloGlacier.cs index 4f26e423c24..fd53c49e338 100644 --- a/dotnetv3/Glacier/Actions/HelloGlacier.cs +++ b/dotnetv3/Glacier/Actions/HelloGlacier.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Glacier.dotnetv3.HelloGlacier] diff --git a/dotnetv3/Glacier/Tests/GlacierWrapperTests.cs b/dotnetv3/Glacier/Tests/GlacierWrapperTests.cs index 8d6f81cac7b..159e4e05197 100644 --- a/dotnetv3/Glacier/Tests/GlacierWrapperTests.cs +++ b/dotnetv3/Glacier/Tests/GlacierWrapperTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.Glacier; using GlacierActions; diff --git a/dotnetv3/Glacier/Tests/Usings.cs b/dotnetv3/Glacier/Tests/Usings.cs index 158ebd88747..ef5ce323ba9 100644 --- a/dotnetv3/Glacier/Tests/Usings.cs +++ b/dotnetv3/Glacier/Tests/Usings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Xunit; global using Xunit.Extensions.Ordering; diff --git a/dotnetv3/Glue/Actions/GlueWrapper.cs b/dotnetv3/Glue/Actions/GlueWrapper.cs index f984dcb3c3a..64fcfa8e567 100644 --- a/dotnetv3/Glue/Actions/GlueWrapper.cs +++ b/dotnetv3/Glue/Actions/GlueWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Glue.dotnetv3.GlueWrapper] @@ -305,7 +305,7 @@ public async Task> GetTablesAsync(string dbName) // snippet-end:[Glue.dotnetv3.GetTables] - //snippet-start:[Glue.dotnetv3.ListJobs] + // snippet-start:[Glue.dotnetv3.ListJobs] /// /// List AWS Glue jobs using a paginator. /// @@ -323,9 +323,9 @@ public async Task> ListJobsAsync() return jobNames; } - //snippet-end:[Glue.dotnetv3.ListJobs] + // snippet-end:[Glue.dotnetv3.ListJobs] - //snippet-start:[Glue.dotnetv3.StartCrawler] + // snippet-start:[Glue.dotnetv3.StartCrawler] /// /// Start an AWS Glue crawler. /// diff --git a/dotnetv3/Glue/Actions/HelloGlue.cs b/dotnetv3/Glue/Actions/HelloGlue.cs index 093d78d1c9d..986856da67b 100644 --- a/dotnetv3/Glue/Actions/HelloGlue.cs +++ b/dotnetv3/Glue/Actions/HelloGlue.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Glue.dotnetv3.HelloGlue] namespace GlueActions; diff --git a/dotnetv3/Glue/Actions/Usings.cs b/dotnetv3/Glue/Actions/Usings.cs index d08c9dc42e9..4c16f1abe74 100644 --- a/dotnetv3/Glue/Actions/Usings.cs +++ b/dotnetv3/Glue/Actions/Usings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Amazon.Glue; global using Amazon.Glue.Model; diff --git a/dotnetv3/Glue/Scenarios/Glue_Basics/GlueBasics.cs b/dotnetv3/Glue/Scenarios/Glue_Basics/GlueBasics.cs index e23fce8226f..a7afe2009a9 100644 --- a/dotnetv3/Glue/Scenarios/Glue_Basics/GlueBasics.cs +++ b/dotnetv3/Glue/Scenarios/Glue_Basics/GlueBasics.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Glue.dotnetv3.GlueBasics.Main] diff --git a/dotnetv3/Glue/Scenarios/Glue_Basics/UIWrapper.cs b/dotnetv3/Glue/Scenarios/Glue_Basics/UIWrapper.cs index 8e9b6dd54a0..b3cd1236f7b 100644 --- a/dotnetv3/Glue/Scenarios/Glue_Basics/UIWrapper.cs +++ b/dotnetv3/Glue/Scenarios/Glue_Basics/UIWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Glue.dotnetv3.GlueBasics.UiWrapper] namespace GlueBasics; diff --git a/dotnetv3/Glue/Scenarios/Glue_Basics/Usings.cs b/dotnetv3/Glue/Scenarios/Glue_Basics/Usings.cs index c761db3f21a..96b326620b0 100644 --- a/dotnetv3/Glue/Scenarios/Glue_Basics/Usings.cs +++ b/dotnetv3/Glue/Scenarios/Glue_Basics/Usings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Glue.dotnetv3.GlueBasics.GlobalUsings] global using Amazon.Glue; diff --git a/dotnetv3/Glue/Tests/GlueTests.cs b/dotnetv3/Glue/Tests/GlueTests.cs index a13f3cb0c7b..34ac5344c5b 100644 --- a/dotnetv3/Glue/Tests/GlueTests.cs +++ b/dotnetv3/Glue/Tests/GlueTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.Glue; using Amazon.Glue.Model; diff --git a/dotnetv3/Glue/Tests/Usings.cs b/dotnetv3/Glue/Tests/Usings.cs index 158ebd88747..ef5ce323ba9 100644 --- a/dotnetv3/Glue/Tests/Usings.cs +++ b/dotnetv3/Glue/Tests/Usings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Xunit; global using Xunit.Extensions.Ordering; diff --git a/dotnetv3/IAM/Actions/HelloIAM.cs b/dotnetv3/IAM/Actions/HelloIAM.cs index 63d1c13862e..0cf62b7bc84 100644 --- a/dotnetv3/IAM/Actions/HelloIAM.cs +++ b/dotnetv3/IAM/Actions/HelloIAM.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[IAM.dotnetv3.HelloIAM] namespace IAMActions; diff --git a/dotnetv3/IAM/Actions/IAMWrapper.cs b/dotnetv3/IAM/Actions/IAMWrapper.cs index e884944809c..d68783436a4 100644 --- a/dotnetv3/IAM/Actions/IAMWrapper.cs +++ b/dotnetv3/IAM/Actions/IAMWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Net; @@ -543,7 +543,7 @@ public async Task RemoveUserFromGroupAsync(string userName, string groupNa return response.HttpStatusCode == HttpStatusCode.OK; } - //snippet-end:[IAM.dotnetv3.RemoveUserFromGroup] + // snippet-end:[IAM.dotnetv3.RemoveUserFromGroup] // snippet-start:[IAM.dotnetv3.PutGroupPolicy] /// diff --git a/dotnetv3/IAM/Actions/Usings.cs b/dotnetv3/IAM/Actions/Usings.cs index 98c857e0329..fdb5909c91e 100644 --- a/dotnetv3/IAM/Actions/Usings.cs +++ b/dotnetv3/IAM/Actions/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[IAM.dotnetv3.Actions.Usings] global using Amazon.IdentityManagement; diff --git a/dotnetv3/IAM/Scenarios/IAMBasics/IAMBasics.cs b/dotnetv3/IAM/Scenarios/IAMBasics/IAMBasics.cs index 501e08177d6..6f18fd2cbe8 100644 --- a/dotnetv3/IAM/Scenarios/IAMBasics/IAMBasics.cs +++ b/dotnetv3/IAM/Scenarios/IAMBasics/IAMBasics.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[IAM.dotnetv3.IAMBasics] diff --git a/dotnetv3/IAM/Scenarios/IAMBasics/Usings.cs b/dotnetv3/IAM/Scenarios/IAMBasics/Usings.cs index db8fc625126..54119213d62 100644 --- a/dotnetv3/IAM/Scenarios/IAMBasics/Usings.cs +++ b/dotnetv3/IAM/Scenarios/IAMBasics/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[IAM.dotnetv3.IAMBasics.Usings] global using Amazon.IdentityManagement; diff --git a/dotnetv3/IAM/Scenarios/IAMGroups/IAMGroups.cs b/dotnetv3/IAM/Scenarios/IAMGroups/IAMGroups.cs index 55f216ff618..9458dcd51dc 100644 --- a/dotnetv3/IAM/Scenarios/IAMGroups/IAMGroups.cs +++ b/dotnetv3/IAM/Scenarios/IAMGroups/IAMGroups.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[IAM.dotnetv3.IAMGroups] using Microsoft.Extensions.Configuration; diff --git a/dotnetv3/IAM/Scenarios/IAMGroups/Usings.cs b/dotnetv3/IAM/Scenarios/IAMGroups/Usings.cs index 8a472e0217b..20f136dca54 100644 --- a/dotnetv3/IAM/Scenarios/IAMGroups/Usings.cs +++ b/dotnetv3/IAM/Scenarios/IAMGroups/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[IAM.dotnetv3.IAMGroups.Usings] global using Amazon.IdentityManagement; diff --git a/dotnetv3/IAM/Scenarios/IamScenariosCommon/S3Wrapper.cs b/dotnetv3/IAM/Scenarios/IamScenariosCommon/S3Wrapper.cs index a102cdf0a6f..919d8a97b3b 100644 --- a/dotnetv3/IAM/Scenarios/IamScenariosCommon/S3Wrapper.cs +++ b/dotnetv3/IAM/Scenarios/IamScenariosCommon/S3Wrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[IAM.dotnetv3.IAMCommon.S3Wrapper] namespace IamScenariosCommon; @@ -27,8 +27,7 @@ public S3Wrapper(IAmazonS3 s3Service, IAmazonSecurityTokenService stsService) _stsService = stsService; } - // snippet.start:[STS.dotnetv3.AssumeS3Role] - /// + /// /// Assumes an AWS Identity and Access Management (IAM) role that allows /// Amazon S3 access for the current session. /// @@ -49,7 +48,6 @@ public async Task AssumeS3RoleAsync(string roleSession, string role return response.Credentials; } - // snippet.end:[STS.dotnetv3.AssumeS3Role] /// /// Delete an S3 bucket. diff --git a/dotnetv3/IAM/Scenarios/IamScenariosCommon/UIWrapper.cs b/dotnetv3/IAM/Scenarios/IamScenariosCommon/UIWrapper.cs index 4457e3ee96a..3b731d260f8 100644 --- a/dotnetv3/IAM/Scenarios/IamScenariosCommon/UIWrapper.cs +++ b/dotnetv3/IAM/Scenarios/IamScenariosCommon/UIWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[IAM.dotnetv3.IAMCommon.UIWrapper] namespace IamScenariosCommon; diff --git a/dotnetv3/IAM/Scenarios/IamScenariosCommon/Usings.cs b/dotnetv3/IAM/Scenarios/IamScenariosCommon/Usings.cs index 1d334c891ad..0894bd2d293 100644 --- a/dotnetv3/IAM/Scenarios/IamScenariosCommon/Usings.cs +++ b/dotnetv3/IAM/Scenarios/IamScenariosCommon/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[IAM.dotnetv3.IamScenariosCommon.Usings] global using Amazon.S3; diff --git a/dotnetv3/IAM/Tests/IamWrapperTests.cs b/dotnetv3/IAM/Tests/IamWrapperTests.cs index b832eb7daf5..b802eaac3ce 100644 --- a/dotnetv3/IAM/Tests/IamWrapperTests.cs +++ b/dotnetv3/IAM/Tests/IamWrapperTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; diff --git a/dotnetv3/IAM/Tests/S3WrapperTests.cs b/dotnetv3/IAM/Tests/S3WrapperTests.cs index 13e8873d1a6..f7682eaa62f 100644 --- a/dotnetv3/IAM/Tests/S3WrapperTests.cs +++ b/dotnetv3/IAM/Tests/S3WrapperTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.S3; using Amazon.S3.Util; diff --git a/dotnetv3/IAM/Tests/Usings.cs b/dotnetv3/IAM/Tests/Usings.cs index 12e7799c14f..8f0a5a2311c 100644 --- a/dotnetv3/IAM/Tests/Usings.cs +++ b/dotnetv3/IAM/Tests/Usings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using IamScenariosCommon; global using Microsoft.Extensions.Configuration; diff --git a/dotnetv3/KMS/CreateAliasExample/CreateAlias.cs b/dotnetv3/KMS/CreateAliasExample/CreateAlias.cs index 611e5e2abbe..2fea8426c56 100644 --- a/dotnetv3/KMS/CreateAliasExample/CreateAlias.cs +++ b/dotnetv3/KMS/CreateAliasExample/CreateAlias.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace CreateAliasExample { diff --git a/dotnetv3/KMS/CreateGrantExample/CreateGrant.cs b/dotnetv3/KMS/CreateGrantExample/CreateGrant.cs index 77937e919ec..574d9235db9 100644 --- a/dotnetv3/KMS/CreateGrantExample/CreateGrant.cs +++ b/dotnetv3/KMS/CreateGrantExample/CreateGrant.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace CreateGrantExample { diff --git a/dotnetv3/KMS/CreateKeyExample/CreateKey.cs b/dotnetv3/KMS/CreateKeyExample/CreateKey.cs index 1f874b1958b..449802e7a95 100644 --- a/dotnetv3/KMS/CreateKeyExample/CreateKey.cs +++ b/dotnetv3/KMS/CreateKeyExample/CreateKey.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace CreateKeyExample { diff --git a/dotnetv3/KMS/DescribeKeyExample/DescribeKey.cs b/dotnetv3/KMS/DescribeKeyExample/DescribeKey.cs index d3ea2f6f19c..5b7c2330b1c 100644 --- a/dotnetv3/KMS/DescribeKeyExample/DescribeKey.cs +++ b/dotnetv3/KMS/DescribeKeyExample/DescribeKey.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DescribeKeyExample { diff --git a/dotnetv3/KMS/DisableKeyExample/DisableKey.cs b/dotnetv3/KMS/DisableKeyExample/DisableKey.cs index f5e29a22853..3832fad1c35 100644 --- a/dotnetv3/KMS/DisableKeyExample/DisableKey.cs +++ b/dotnetv3/KMS/DisableKeyExample/DisableKey.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DisableKeyExample { diff --git a/dotnetv3/KMS/EnableKeyExample/EnableKey.cs b/dotnetv3/KMS/EnableKeyExample/EnableKey.cs index 588e2fd7ecf..d3306e0a85b 100644 --- a/dotnetv3/KMS/EnableKeyExample/EnableKey.cs +++ b/dotnetv3/KMS/EnableKeyExample/EnableKey.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace EnableKeyExample { diff --git a/dotnetv3/KMS/ListAliasesExample/ListAliases.cs b/dotnetv3/KMS/ListAliasesExample/ListAliases.cs index cb4a6bcfac7..c2e1b45540b 100644 --- a/dotnetv3/KMS/ListAliasesExample/ListAliases.cs +++ b/dotnetv3/KMS/ListAliasesExample/ListAliases.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ListAliasesExample { diff --git a/dotnetv3/KMS/ListGrantsExample/ListGrants.cs b/dotnetv3/KMS/ListGrantsExample/ListGrants.cs index a9a9f6314a7..c002e816e13 100644 --- a/dotnetv3/KMS/ListGrantsExample/ListGrants.cs +++ b/dotnetv3/KMS/ListGrantsExample/ListGrants.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ListGrantsExample { diff --git a/dotnetv3/KMS/ListKeysExample/ListKeys.cs b/dotnetv3/KMS/ListKeysExample/ListKeys.cs index 914da7021f6..3e72934258a 100644 --- a/dotnetv3/KMS/ListKeysExample/ListKeys.cs +++ b/dotnetv3/KMS/ListKeysExample/ListKeys.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ListKeysExample { diff --git a/dotnetv3/Keyspaces/Actions/HelloKeyspaces.cs b/dotnetv3/Keyspaces/Actions/HelloKeyspaces.cs index 42e7df52a98..0bea791e350 100644 --- a/dotnetv3/Keyspaces/Actions/HelloKeyspaces.cs +++ b/dotnetv3/Keyspaces/Actions/HelloKeyspaces.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Keyspaces.dotnetv3.HelloKeyspaces] namespace KeyspacesActions; diff --git a/dotnetv3/Keyspaces/Actions/KeyspacesWrapper.cs b/dotnetv3/Keyspaces/Actions/KeyspacesWrapper.cs index 2c551d029de..a0bf3457e6e 100644 --- a/dotnetv3/Keyspaces/Actions/KeyspacesWrapper.cs +++ b/dotnetv3/Keyspaces/Actions/KeyspacesWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Keyspaces.dotnetv3.KeyspacesWrapper] namespace KeyspacesActions; diff --git a/dotnetv3/Keyspaces/Actions/Usings.cs b/dotnetv3/Keyspaces/Actions/Usings.cs index 3d2e39e8da0..253bf15fae8 100644 --- a/dotnetv3/Keyspaces/Actions/Usings.cs +++ b/dotnetv3/Keyspaces/Actions/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Keyspaces.dotnetv3.GlobalUsings] global using System.Net; diff --git a/dotnetv3/Keyspaces/Scenarios/CassandraWrapper.cs b/dotnetv3/Keyspaces/Scenarios/CassandraWrapper.cs index ceb5b5557c9..7fefe98b15a 100644 --- a/dotnetv3/Keyspaces/Scenarios/CassandraWrapper.cs +++ b/dotnetv3/Keyspaces/Scenarios/CassandraWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Keyspaces.dotnetv3.CassandraWrapper] using System.Net; diff --git a/dotnetv3/Keyspaces/Scenarios/KeyspacesBasics.cs b/dotnetv3/Keyspaces/Scenarios/KeyspacesBasics.cs index ab31588bd88..3193d885d1d 100644 --- a/dotnetv3/Keyspaces/Scenarios/KeyspacesBasics.cs +++ b/dotnetv3/Keyspaces/Scenarios/KeyspacesBasics.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Keyspaces.dotnetv3.KeyspacesScenario] namespace KeyspacesBasics; diff --git a/dotnetv3/Keyspaces/Scenarios/Movie.cs b/dotnetv3/Keyspaces/Scenarios/Movie.cs index 4da517793b7..f53715e3179 100644 --- a/dotnetv3/Keyspaces/Scenarios/Movie.cs +++ b/dotnetv3/Keyspaces/Scenarios/Movie.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace KeyspacesScenario; /// diff --git a/dotnetv3/Keyspaces/Scenarios/MovieInfo.cs b/dotnetv3/Keyspaces/Scenarios/MovieInfo.cs index 278f1de6fb8..4d2458e43c3 100644 --- a/dotnetv3/Keyspaces/Scenarios/MovieInfo.cs +++ b/dotnetv3/Keyspaces/Scenarios/MovieInfo.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace KeyspacesScenario; diff --git a/dotnetv3/Keyspaces/Scenarios/UIMethods.cs b/dotnetv3/Keyspaces/Scenarios/UIMethods.cs index b89caa1680f..0b3effae06b 100644 --- a/dotnetv3/Keyspaces/Scenarios/UIMethods.cs +++ b/dotnetv3/Keyspaces/Scenarios/UIMethods.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace KeyspacesBasics; diff --git a/dotnetv3/Keyspaces/Scenarios/Usings.cs b/dotnetv3/Keyspaces/Scenarios/Usings.cs index 5d3d55e7b8e..05a7c4ef7ab 100644 --- a/dotnetv3/Keyspaces/Scenarios/Usings.cs +++ b/dotnetv3/Keyspaces/Scenarios/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Keyspaces.dotnetv3.KeyspacesBasicsGlobalUsings] global using System.Security.Cryptography.X509Certificates; diff --git a/dotnetv3/Keyspaces/Tests/CassandraWrapperTests.cs b/dotnetv3/Keyspaces/Tests/CassandraWrapperTests.cs index f6aa086f102..c795f13e9dc 100644 --- a/dotnetv3/Keyspaces/Tests/CassandraWrapperTests.cs +++ b/dotnetv3/Keyspaces/Tests/CassandraWrapperTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace KeyspacesTests { diff --git a/dotnetv3/Keyspaces/Tests/KeyspacesWrapperTests.cs b/dotnetv3/Keyspaces/Tests/KeyspacesWrapperTests.cs index 1d92891b278..d819d56244b 100644 --- a/dotnetv3/Keyspaces/Tests/KeyspacesWrapperTests.cs +++ b/dotnetv3/Keyspaces/Tests/KeyspacesWrapperTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace KeyspacesTests { diff --git a/dotnetv3/Keyspaces/Tests/Usings.cs b/dotnetv3/Keyspaces/Tests/Usings.cs index 8de0367ef87..64e17d8d21e 100644 --- a/dotnetv3/Keyspaces/Tests/Usings.cs +++ b/dotnetv3/Keyspaces/Tests/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 global using Amazon.Keyspaces; global using Amazon.Keyspaces.Model; diff --git a/dotnetv3/Kinesis/CreateStreamExample/CreateStreamExample/CreateStream.cs b/dotnetv3/Kinesis/CreateStreamExample/CreateStreamExample/CreateStream.cs index d5c818226b3..6bf095a5fe0 100644 --- a/dotnetv3/Kinesis/CreateStreamExample/CreateStreamExample/CreateStream.cs +++ b/dotnetv3/Kinesis/CreateStreamExample/CreateStreamExample/CreateStream.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace CreateStreamExample { diff --git a/dotnetv3/Kinesis/DeleteStreamExample/DeleteStreamExample/DeleteStream.cs b/dotnetv3/Kinesis/DeleteStreamExample/DeleteStreamExample/DeleteStream.cs index cd0b8e28ce8..674b2410aa8 100644 --- a/dotnetv3/Kinesis/DeleteStreamExample/DeleteStreamExample/DeleteStream.cs +++ b/dotnetv3/Kinesis/DeleteStreamExample/DeleteStreamExample/DeleteStream.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DeleteStreamExample { diff --git a/dotnetv3/Kinesis/DeregisterConsumerExample/DeregisterConsumerExample/DeregisterConsumer.cs b/dotnetv3/Kinesis/DeregisterConsumerExample/DeregisterConsumerExample/DeregisterConsumer.cs index c941f97976d..3fd447ae995 100644 --- a/dotnetv3/Kinesis/DeregisterConsumerExample/DeregisterConsumerExample/DeregisterConsumer.cs +++ b/dotnetv3/Kinesis/DeregisterConsumerExample/DeregisterConsumerExample/DeregisterConsumer.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DeregisterConsumerExample { diff --git a/dotnetv3/Kinesis/ListConsumersExample/ListConsumersExample/ListConsumers.cs b/dotnetv3/Kinesis/ListConsumersExample/ListConsumersExample/ListConsumers.cs index 0bb9afc44ab..82088742a05 100644 --- a/dotnetv3/Kinesis/ListConsumersExample/ListConsumersExample/ListConsumers.cs +++ b/dotnetv3/Kinesis/ListConsumersExample/ListConsumersExample/ListConsumers.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ListConsumersExample { diff --git a/dotnetv3/Kinesis/ListStreamsExample/ListStreamsExample/ListStreams.cs b/dotnetv3/Kinesis/ListStreamsExample/ListStreamsExample/ListStreams.cs index ffb8c5da2e3..bb3badbbd7e 100644 --- a/dotnetv3/Kinesis/ListStreamsExample/ListStreamsExample/ListStreams.cs +++ b/dotnetv3/Kinesis/ListStreamsExample/ListStreamsExample/ListStreams.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ListStreamsExample { diff --git a/dotnetv3/Kinesis/ListTagsExample/ListTagsExample/ListTags.cs b/dotnetv3/Kinesis/ListTagsExample/ListTagsExample/ListTags.cs index 0df873ecd2e..36fbfc4d97b 100644 --- a/dotnetv3/Kinesis/ListTagsExample/ListTagsExample/ListTags.cs +++ b/dotnetv3/Kinesis/ListTagsExample/ListTagsExample/ListTags.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ListTagsExample { diff --git a/dotnetv3/Kinesis/RegisterConsumerExample/RegisterConsumerExample/RegisterConsumer.cs b/dotnetv3/Kinesis/RegisterConsumerExample/RegisterConsumerExample/RegisterConsumer.cs index 7c0eb08f07b..0136ec2377d 100644 --- a/dotnetv3/Kinesis/RegisterConsumerExample/RegisterConsumerExample/RegisterConsumer.cs +++ b/dotnetv3/Kinesis/RegisterConsumerExample/RegisterConsumerExample/RegisterConsumer.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace RegisterConsumerExample { diff --git a/dotnetv3/Kinesis/TagStreamExample/TagStreamExample/TagStream.cs b/dotnetv3/Kinesis/TagStreamExample/TagStreamExample/TagStream.cs index c841e861f92..4ab772f0cfc 100644 --- a/dotnetv3/Kinesis/TagStreamExample/TagStreamExample/TagStream.cs +++ b/dotnetv3/Kinesis/TagStreamExample/TagStreamExample/TagStream.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace TagStreamExample { diff --git a/dotnetv3/Lambda/Actions/HelloLambda.cs b/dotnetv3/Lambda/Actions/HelloLambda.cs index 13f042fe712..ab165b973d0 100644 --- a/dotnetv3/Lambda/Actions/HelloLambda.cs +++ b/dotnetv3/Lambda/Actions/HelloLambda.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Lambda.dotnetv3.LambdaActions.HelloLambda] namespace LambdaActions; diff --git a/dotnetv3/Lambda/Actions/LambdaRoleWrapper.cs b/dotnetv3/Lambda/Actions/LambdaRoleWrapper.cs index 6365cee730d..9cb37d6ec3f 100644 --- a/dotnetv3/Lambda/Actions/LambdaRoleWrapper.cs +++ b/dotnetv3/Lambda/Actions/LambdaRoleWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Lambda.dotnetv3.LambdaActions.LambdaRoleWrapper] namespace LambdaActions; diff --git a/dotnetv3/Lambda/Actions/LambdaWrapper.cs b/dotnetv3/Lambda/Actions/LambdaWrapper.cs index 0cf9d152a19..4e3bc0f6641 100644 --- a/dotnetv3/Lambda/Actions/LambdaWrapper.cs +++ b/dotnetv3/Lambda/Actions/LambdaWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Lambda.dotnetv3.LambdaActions.LambdaWrapper] namespace LambdaActions; diff --git a/dotnetv3/Lambda/LambdaCalculator/LambdaCalculator/Function.cs b/dotnetv3/Lambda/LambdaCalculator/LambdaCalculator/Function.cs index 12159eb6cab..d6cfa856ac1 100644 --- a/dotnetv3/Lambda/LambdaCalculator/LambdaCalculator/Function.cs +++ b/dotnetv3/Lambda/LambdaCalculator/LambdaCalculator/Function.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lambda.dotnetv3.handler.arithmetic] using Amazon.Lambda.Core; diff --git a/dotnetv3/Lambda/LambdaIncrement/src/LambdaIncrement/Function.cs b/dotnetv3/Lambda/LambdaIncrement/src/LambdaIncrement/Function.cs index 499a0800856..0d961b8acd1 100644 --- a/dotnetv3/Lambda/LambdaIncrement/src/LambdaIncrement/Function.cs +++ b/dotnetv3/Lambda/LambdaIncrement/src/LambdaIncrement/Function.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lambda.dotnetv3.handler.increment] using Amazon.Lambda.Core; diff --git a/dotnetv3/Lambda/Scenarios/LambdaBasics/LambdaBasics.cs b/dotnetv3/Lambda/Scenarios/LambdaBasics/LambdaBasics.cs index 1573be7c141..a1e7d4aee94 100644 --- a/dotnetv3/Lambda/Scenarios/LambdaBasics/LambdaBasics.cs +++ b/dotnetv3/Lambda/Scenarios/LambdaBasics/LambdaBasics.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Lambda.dotnetv3.LambdaBasics] using Amazon.Lambda.Model; diff --git a/dotnetv3/Lambda/Scenarios/LambdaBasics/Usings.cs b/dotnetv3/Lambda/Scenarios/LambdaBasics/Usings.cs index 6e0b5ee6409..2cf917cde49 100644 --- a/dotnetv3/Lambda/Scenarios/LambdaBasics/Usings.cs +++ b/dotnetv3/Lambda/Scenarios/LambdaBasics/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Lambda.dotnetv3.LambdaBasics.Usings] global using System.Threading.Tasks; diff --git a/dotnetv3/Lambda/Scenarios/LambdaScenarioCommon/UIWrapper.cs b/dotnetv3/Lambda/Scenarios/LambdaScenarioCommon/UIWrapper.cs index b51af161810..aa908646cb4 100644 --- a/dotnetv3/Lambda/Scenarios/LambdaScenarioCommon/UIWrapper.cs +++ b/dotnetv3/Lambda/Scenarios/LambdaScenarioCommon/UIWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[Lambda.dotnetv3.LambdaScenarioCommon.UIWrapper] namespace LambdaScenarioCommon; diff --git a/dotnetv3/Lambda/Tests/LambdaTests.cs b/dotnetv3/Lambda/Tests/LambdaTests.cs index 39b1433433e..2bbc5b6e5ef 100644 --- a/dotnetv3/Lambda/Tests/LambdaTests.cs +++ b/dotnetv3/Lambda/Tests/LambdaTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; diff --git a/dotnetv3/Lambda/Tests/Usings.cs b/dotnetv3/Lambda/Tests/Usings.cs index 219ed694921..daa9eb8e690 100644 --- a/dotnetv3/Lambda/Tests/Usings.cs +++ b/dotnetv3/Lambda/Tests/Usings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using LambdaActions; global using Xunit; diff --git a/dotnetv3/MediaConvert/Actions/HelloMediaConvert.cs b/dotnetv3/MediaConvert/Actions/HelloMediaConvert.cs index 8d747e79ff8..242d56bf0aa 100644 --- a/dotnetv3/MediaConvert/Actions/HelloMediaConvert.cs +++ b/dotnetv3/MediaConvert/Actions/HelloMediaConvert.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[MediaConvert.dotnetv3.HelloMediaConvert] using Amazon.MediaConvert; diff --git a/dotnetv3/MediaConvert/Actions/MediaConvertWrapper.cs b/dotnetv3/MediaConvert/Actions/MediaConvertWrapper.cs index 5ad59b4871e..0cb55ae59f4 100644 --- a/dotnetv3/MediaConvert/Actions/MediaConvertWrapper.cs +++ b/dotnetv3/MediaConvert/Actions/MediaConvertWrapper.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon.MediaConvert; using Amazon.MediaConvert.Model; diff --git a/dotnetv3/MediaConvert/Scenarios/CreateJob/CreateJob.cs b/dotnetv3/MediaConvert/Scenarios/CreateJob/CreateJob.cs index 61f6a9b438b..5fd48182529 100644 --- a/dotnetv3/MediaConvert/Scenarios/CreateJob/CreateJob.cs +++ b/dotnetv3/MediaConvert/Scenarios/CreateJob/CreateJob.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.MediaConvert; using Amazon.MediaConvert.Model; @@ -23,7 +23,7 @@ static async Task Main(string[] args) // snippet-start:[MediaConvert.dotnetv3.Setup] - // MediaConvert role Amazon Resource Name (ARN). + // MediaConvert role Amazon Resource Name (ARN). // For information on creating this role, see // https://docs.aws.amazon.com/mediaconvert/latest/ug/creating-the-iam-role-in-mediaconvert-configured.html. var mediaConvertRole = _configuration["mediaConvertRoleARN"]; diff --git a/dotnetv3/MediaConvert/Tests/MediaConvertTests.cs b/dotnetv3/MediaConvert/Tests/MediaConvertTests.cs index f00a08c0fce..7b854e4448f 100644 --- a/dotnetv3/MediaConvert/Tests/MediaConvertTests.cs +++ b/dotnetv3/MediaConvert/Tests/MediaConvertTests.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon.MediaConvert; using MediaConvertActions; diff --git a/dotnetv3/MediaConvert/Tests/Usings.cs b/dotnetv3/MediaConvert/Tests/Usings.cs index 0979f98c637..ef5ce323ba9 100644 --- a/dotnetv3/MediaConvert/Tests/Usings.cs +++ b/dotnetv3/MediaConvert/Tests/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 global using Xunit; global using Xunit.Extensions.Ordering; diff --git a/dotnetv3/Organizations/AttachPolicyExample/AttachPolicyExample/AttachPolicy.cs b/dotnetv3/Organizations/AttachPolicyExample/AttachPolicyExample/AttachPolicy.cs index 7c6d1ed2698..88ac7492c1b 100644 --- a/dotnetv3/Organizations/AttachPolicyExample/AttachPolicyExample/AttachPolicy.cs +++ b/dotnetv3/Organizations/AttachPolicyExample/AttachPolicyExample/AttachPolicy.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace AttachPolicyExample { diff --git a/dotnetv3/Organizations/CreateAccountExample/CreateAccountExample/CreateAccount.cs b/dotnetv3/Organizations/CreateAccountExample/CreateAccountExample/CreateAccount.cs index 9d415f451b3..5e6461264c8 100644 --- a/dotnetv3/Organizations/CreateAccountExample/CreateAccountExample/CreateAccount.cs +++ b/dotnetv3/Organizations/CreateAccountExample/CreateAccountExample/CreateAccount.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace CreateAccountExample { diff --git a/dotnetv3/Organizations/CreateOrganizationExample/CreateOrganizationExample/CreateOrganization.cs b/dotnetv3/Organizations/CreateOrganizationExample/CreateOrganizationExample/CreateOrganization.cs index dd5d92ae8df..058ca9e1c68 100644 --- a/dotnetv3/Organizations/CreateOrganizationExample/CreateOrganizationExample/CreateOrganization.cs +++ b/dotnetv3/Organizations/CreateOrganizationExample/CreateOrganizationExample/CreateOrganization.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace CreateOrganizationExample { diff --git a/dotnetv3/Organizations/CreateOrganizationalUnitExample/CreateOrganizationalUnitExample/CreateOrganizationalUnit.cs b/dotnetv3/Organizations/CreateOrganizationalUnitExample/CreateOrganizationalUnitExample/CreateOrganizationalUnit.cs index c46a46fd7e5..9443b2ba211 100644 --- a/dotnetv3/Organizations/CreateOrganizationalUnitExample/CreateOrganizationalUnitExample/CreateOrganizationalUnit.cs +++ b/dotnetv3/Organizations/CreateOrganizationalUnitExample/CreateOrganizationalUnitExample/CreateOrganizationalUnit.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace CreateOrganizationalUnitExample { diff --git a/dotnetv3/Organizations/CreatePolicyExample/CreatePolicyExample/CreatePolicy.cs b/dotnetv3/Organizations/CreatePolicyExample/CreatePolicyExample/CreatePolicy.cs index a99b2d80bbf..184e982a9ac 100644 --- a/dotnetv3/Organizations/CreatePolicyExample/CreatePolicyExample/CreatePolicy.cs +++ b/dotnetv3/Organizations/CreatePolicyExample/CreatePolicyExample/CreatePolicy.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace CreatePolicyExample { diff --git a/dotnetv3/Organizations/DeleteOrganizationExample/DeleteOrganizationExample/DeleteOrganization.cs b/dotnetv3/Organizations/DeleteOrganizationExample/DeleteOrganizationExample/DeleteOrganization.cs index 89622b7131e..02ebd0a6a4a 100644 --- a/dotnetv3/Organizations/DeleteOrganizationExample/DeleteOrganizationExample/DeleteOrganization.cs +++ b/dotnetv3/Organizations/DeleteOrganizationExample/DeleteOrganizationExample/DeleteOrganization.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DeleteOrganizationExample { diff --git a/dotnetv3/Organizations/DeleteOrganizationalUnitExample/DeleteOrganizationalUnitExample/DeleteOrganizationalUnit.cs b/dotnetv3/Organizations/DeleteOrganizationalUnitExample/DeleteOrganizationalUnitExample/DeleteOrganizationalUnit.cs index 6a53a2fa012..913b0c8473e 100644 --- a/dotnetv3/Organizations/DeleteOrganizationalUnitExample/DeleteOrganizationalUnitExample/DeleteOrganizationalUnit.cs +++ b/dotnetv3/Organizations/DeleteOrganizationalUnitExample/DeleteOrganizationalUnitExample/DeleteOrganizationalUnit.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DeleteOrganizationalUnitExample { diff --git a/dotnetv3/Organizations/DeletePolicyExample/DeletePolicyExample/DeletePolicy.cs b/dotnetv3/Organizations/DeletePolicyExample/DeletePolicyExample/DeletePolicy.cs index f2e92f69825..77dd49fb5eb 100644 --- a/dotnetv3/Organizations/DeletePolicyExample/DeletePolicyExample/DeletePolicy.cs +++ b/dotnetv3/Organizations/DeletePolicyExample/DeletePolicyExample/DeletePolicy.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DeletePolicyExample { diff --git a/dotnetv3/Organizations/DetachPolicyExample/DetachPolicyExample/DetachPolicy.cs b/dotnetv3/Organizations/DetachPolicyExample/DetachPolicyExample/DetachPolicy.cs index 7e3df109b1d..462a6c558bd 100644 --- a/dotnetv3/Organizations/DetachPolicyExample/DetachPolicyExample/DetachPolicy.cs +++ b/dotnetv3/Organizations/DetachPolicyExample/DetachPolicyExample/DetachPolicy.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DetachPolicyExample { diff --git a/dotnetv3/Organizations/ListAccountsExample/ListAccountsExample/ListAccounts.cs b/dotnetv3/Organizations/ListAccountsExample/ListAccountsExample/ListAccounts.cs index 8e7d0534247..458f7ccea96 100644 --- a/dotnetv3/Organizations/ListAccountsExample/ListAccountsExample/ListAccounts.cs +++ b/dotnetv3/Organizations/ListAccountsExample/ListAccountsExample/ListAccounts.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ListAccountsExample { diff --git a/dotnetv3/Organizations/ListOrganizationalUnitsForParentExample/ListOrganizationalUnitsForParentExample/ListOrganizationalUnitsForParent.cs b/dotnetv3/Organizations/ListOrganizationalUnitsForParentExample/ListOrganizationalUnitsForParentExample/ListOrganizationalUnitsForParent.cs index 2a771e278fb..524e4d75e3f 100644 --- a/dotnetv3/Organizations/ListOrganizationalUnitsForParentExample/ListOrganizationalUnitsForParentExample/ListOrganizationalUnitsForParent.cs +++ b/dotnetv3/Organizations/ListOrganizationalUnitsForParentExample/ListOrganizationalUnitsForParentExample/ListOrganizationalUnitsForParent.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ListOrganizationalUnitsForParentExample { diff --git a/dotnetv3/Organizations/ListPoliciesExample/ListPoliciesExample/ListPolicies.cs b/dotnetv3/Organizations/ListPoliciesExample/ListPoliciesExample/ListPolicies.cs index b2ff546850f..2ef1c7c5697 100644 --- a/dotnetv3/Organizations/ListPoliciesExample/ListPoliciesExample/ListPolicies.cs +++ b/dotnetv3/Organizations/ListPoliciesExample/ListPoliciesExample/ListPolicies.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ListPoliciesExample { diff --git a/dotnetv3/Polly/DeleteLexiconExample/DeleteLexicon.cs b/dotnetv3/Polly/DeleteLexiconExample/DeleteLexicon.cs index 456059b2b8b..9fae2550bc2 100644 --- a/dotnetv3/Polly/DeleteLexiconExample/DeleteLexicon.cs +++ b/dotnetv3/Polly/DeleteLexiconExample/DeleteLexicon.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DeleteLexiconExample { diff --git a/dotnetv3/Polly/DescribeVoicesExample/DescribeVoices.cs b/dotnetv3/Polly/DescribeVoicesExample/DescribeVoices.cs index 84125ac4367..79cfdfe6b48 100644 --- a/dotnetv3/Polly/DescribeVoicesExample/DescribeVoices.cs +++ b/dotnetv3/Polly/DescribeVoicesExample/DescribeVoices.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 /// /// Displays information about the voices available for Amazon Polly. This diff --git a/dotnetv3/Polly/GetLexiconExample/GetLexicon.cs b/dotnetv3/Polly/GetLexiconExample/GetLexicon.cs index c63c848c785..af47ca800a2 100644 --- a/dotnetv3/Polly/GetLexiconExample/GetLexicon.cs +++ b/dotnetv3/Polly/GetLexiconExample/GetLexicon.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace GetLexiconExample { diff --git a/dotnetv3/Polly/ListLexiconsExample/ListLexicons.cs b/dotnetv3/Polly/ListLexiconsExample/ListLexicons.cs index 3e9dfd8a076..2dc0f93f09f 100644 --- a/dotnetv3/Polly/ListLexiconsExample/ListLexicons.cs +++ b/dotnetv3/Polly/ListLexiconsExample/ListLexicons.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ListLexiconsExample { diff --git a/dotnetv3/Polly/PutLexiconExample/PutLexicon.cs b/dotnetv3/Polly/PutLexiconExample/PutLexicon.cs index 2aead5c818f..e5952d30722 100644 --- a/dotnetv3/Polly/PutLexiconExample/PutLexicon.cs +++ b/dotnetv3/Polly/PutLexiconExample/PutLexicon.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace PutLexiconExample { diff --git a/dotnetv3/Polly/SynthesizeSpeechExample/SynthesizeSpeech.cs b/dotnetv3/Polly/SynthesizeSpeechExample/SynthesizeSpeech.cs index e2a13cfd431..5d650655560 100644 --- a/dotnetv3/Polly/SynthesizeSpeechExample/SynthesizeSpeech.cs +++ b/dotnetv3/Polly/SynthesizeSpeechExample/SynthesizeSpeech.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 /// /// This example uses Amazon Polly to convert text to speech. Then, it saves diff --git a/dotnetv3/Polly/SynthesizeSpeechMarksExample/SynthesizeSpeechMarks.cs b/dotnetv3/Polly/SynthesizeSpeechMarksExample/SynthesizeSpeechMarks.cs index 7846f074a53..28341465e2a 100644 --- a/dotnetv3/Polly/SynthesizeSpeechMarksExample/SynthesizeSpeechMarks.cs +++ b/dotnetv3/Polly/SynthesizeSpeechMarksExample/SynthesizeSpeechMarks.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 /// /// Uses the Amazon Polly Service to synthesize speech from text using speech diff --git a/dotnetv3/RDS/Actions/HelloRDS.cs b/dotnetv3/RDS/Actions/HelloRDS.cs index 036284220c3..cb94696d47c 100644 --- a/dotnetv3/RDS/Actions/HelloRDS.cs +++ b/dotnetv3/RDS/Actions/HelloRDS.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[RDS.dotnetv3.HelloRds] using System; diff --git a/dotnetv3/RDS/Actions/RDSWrapper.Instances.cs b/dotnetv3/RDS/Actions/RDSWrapper.Instances.cs index 6a4e87705da..13a59ea7d0d 100644 --- a/dotnetv3/RDS/Actions/RDSWrapper.Instances.cs +++ b/dotnetv3/RDS/Actions/RDSWrapper.Instances.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using System.Threading.Tasks; @@ -47,7 +47,7 @@ public async Task> DescribeDBEngineVersions(string engine, /// /// Get a list of orderable DB instance options for a specific - /// engine and engine version. + /// engine and engine version. /// /// Name of the engine. /// Version of the engine. diff --git a/dotnetv3/RDS/Actions/RDSWrapper.ParameterGroups.cs b/dotnetv3/RDS/Actions/RDSWrapper.ParameterGroups.cs index 20736881b60..b90c050981d 100644 --- a/dotnetv3/RDS/Actions/RDSWrapper.ParameterGroups.cs +++ b/dotnetv3/RDS/Actions/RDSWrapper.ParameterGroups.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using System.Net; diff --git a/dotnetv3/RDS/Actions/RDSWrapper.Snapshots.cs b/dotnetv3/RDS/Actions/RDSWrapper.Snapshots.cs index 2b14ad34730..625af840c9f 100644 --- a/dotnetv3/RDS/Actions/RDSWrapper.Snapshots.cs +++ b/dotnetv3/RDS/Actions/RDSWrapper.Snapshots.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using System.Threading.Tasks; diff --git a/dotnetv3/RDS/Scenarios/RDSInstanceScenario/RDSInstanceScenario.cs b/dotnetv3/RDS/Scenarios/RDSInstanceScenario/RDSInstanceScenario.cs index 82c8cada050..77c5fe8d5d9 100644 --- a/dotnetv3/RDS/Scenarios/RDSInstanceScenario/RDSInstanceScenario.cs +++ b/dotnetv3/RDS/Scenarios/RDSInstanceScenario/RDSInstanceScenario.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.RDS; using Amazon.RDS.Model; @@ -33,7 +33,7 @@ 6. Modifies both the auto_increment_offset and auto_increment_increment paramet 7. Gets and displays the updated parameters using the DescribeDBParameters method with a source of "user". 8. Gets a list of allowed engine versions using the DescribeDBEngineVersionsAsync method. 9. Displays and selects from a list of micro instance classes available for the selected engine and version. - 10. Creates an RDS DB instance that contains a MySql database and uses the parameter group + 10. Creates an RDS DB instance that contains a MySql database and uses the parameter group using the CreateDBInstanceAsync method. 11. Waits for DB instance to be ready using the DescribeDBInstancesAsync method. 12. Prints out the connection endpoint string for the new DB instance. diff --git a/dotnetv3/RDS/Tests/RDSInstanceScenarioTests.cs b/dotnetv3/RDS/Tests/RDSInstanceScenarioTests.cs index 897a4bd5cac..a5f1b03b0a3 100644 --- a/dotnetv3/RDS/Tests/RDSInstanceScenarioTests.cs +++ b/dotnetv3/RDS/Tests/RDSInstanceScenarioTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.RDS; using Amazon.RDS.Model; diff --git a/dotnetv3/RDS/Tests/Usings.cs b/dotnetv3/RDS/Tests/Usings.cs index 158ebd88747..ef5ce323ba9 100644 --- a/dotnetv3/RDS/Tests/Usings.cs +++ b/dotnetv3/RDS/Tests/Usings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Xunit; global using Xunit.Extensions.Ordering; diff --git a/dotnetv3/Rekognition/AddFacesExample/AddFaces.cs b/dotnetv3/Rekognition/AddFacesExample/AddFaces.cs index 3ef011dc965..502fa0f793d 100644 --- a/dotnetv3/Rekognition/AddFacesExample/AddFaces.cs +++ b/dotnetv3/Rekognition/AddFacesExample/AddFaces.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace AddFacesExample { diff --git a/dotnetv3/Rekognition/CelebritiesInImageExample/CelebritiesInImage.cs b/dotnetv3/Rekognition/CelebritiesInImageExample/CelebritiesInImage.cs index 54d21289e0b..200863b61f8 100644 --- a/dotnetv3/Rekognition/CelebritiesInImageExample/CelebritiesInImage.cs +++ b/dotnetv3/Rekognition/CelebritiesInImageExample/CelebritiesInImage.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace CelebritiesInImageExample { diff --git a/dotnetv3/Rekognition/CelebrityInfoExample/CelebrityInfo.cs b/dotnetv3/Rekognition/CelebrityInfoExample/CelebrityInfo.cs index 9e5facb927f..6743385cb70 100644 --- a/dotnetv3/Rekognition/CelebrityInfoExample/CelebrityInfo.cs +++ b/dotnetv3/Rekognition/CelebrityInfoExample/CelebrityInfo.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace CelebrityInfoExample { diff --git a/dotnetv3/Rekognition/CompareFacesExample/CompareFaces.cs b/dotnetv3/Rekognition/CompareFacesExample/CompareFaces.cs index eaa19f9b5fd..6fc6d7ef992 100644 --- a/dotnetv3/Rekognition/CompareFacesExample/CompareFaces.cs +++ b/dotnetv3/Rekognition/CompareFacesExample/CompareFaces.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace CompareFacesExample { diff --git a/dotnetv3/Rekognition/CreateCollectionExample/CreateCollection.cs b/dotnetv3/Rekognition/CreateCollectionExample/CreateCollection.cs index aa759eebcf6..84947a55ec1 100644 --- a/dotnetv3/Rekognition/CreateCollectionExample/CreateCollection.cs +++ b/dotnetv3/Rekognition/CreateCollectionExample/CreateCollection.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace CreateCollectionExample { diff --git a/dotnetv3/Rekognition/DeleteCollectionExample/DeleteCollection.cs b/dotnetv3/Rekognition/DeleteCollectionExample/DeleteCollection.cs index ed8f4c7296d..ae513bacda8 100644 --- a/dotnetv3/Rekognition/DeleteCollectionExample/DeleteCollection.cs +++ b/dotnetv3/Rekognition/DeleteCollectionExample/DeleteCollection.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DeleteCollectionExample { diff --git a/dotnetv3/Rekognition/DeleteFacesExample/DeleteFaces.cs b/dotnetv3/Rekognition/DeleteFacesExample/DeleteFaces.cs index 21f99c31858..b77544d1fce 100644 --- a/dotnetv3/Rekognition/DeleteFacesExample/DeleteFaces.cs +++ b/dotnetv3/Rekognition/DeleteFacesExample/DeleteFaces.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DeleteFacesExample { diff --git a/dotnetv3/Rekognition/DescribeCollectionExample/DescribeCollection.cs b/dotnetv3/Rekognition/DescribeCollectionExample/DescribeCollection.cs index 860f3d8bc86..82fcde00720 100644 --- a/dotnetv3/Rekognition/DescribeCollectionExample/DescribeCollection.cs +++ b/dotnetv3/Rekognition/DescribeCollectionExample/DescribeCollection.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DescribeCollectionExample { diff --git a/dotnetv3/Rekognition/DetectFacesExample/DetectFaces.cs b/dotnetv3/Rekognition/DetectFacesExample/DetectFaces.cs index bfb4dc3cbf9..c58ce4cbaef 100644 --- a/dotnetv3/Rekognition/DetectFacesExample/DetectFaces.cs +++ b/dotnetv3/Rekognition/DetectFacesExample/DetectFaces.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DetectFacesExample { diff --git a/dotnetv3/Rekognition/DetectLabelsExample/DetectLabels.cs b/dotnetv3/Rekognition/DetectLabelsExample/DetectLabels.cs index e33c34e9646..010a453b822 100644 --- a/dotnetv3/Rekognition/DetectLabelsExample/DetectLabels.cs +++ b/dotnetv3/Rekognition/DetectLabelsExample/DetectLabels.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DetectLabelsExample { diff --git a/dotnetv3/Rekognition/DetectLabelsLocalFileExample/DetectLabelsLocalFile.cs b/dotnetv3/Rekognition/DetectLabelsLocalFileExample/DetectLabelsLocalFile.cs index 86f4093624b..a11ecbfa146 100644 --- a/dotnetv3/Rekognition/DetectLabelsLocalFileExample/DetectLabelsLocalFile.cs +++ b/dotnetv3/Rekognition/DetectLabelsLocalFileExample/DetectLabelsLocalFile.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DetectLabelsLocalFileExample { diff --git a/dotnetv3/Rekognition/DetectModerationLabelsExample/DetectModerationLabels.cs b/dotnetv3/Rekognition/DetectModerationLabelsExample/DetectModerationLabels.cs index 4bbad311cb9..46d84f33bf2 100644 --- a/dotnetv3/Rekognition/DetectModerationLabelsExample/DetectModerationLabels.cs +++ b/dotnetv3/Rekognition/DetectModerationLabelsExample/DetectModerationLabels.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DetectModerationLabelsExample { diff --git a/dotnetv3/Rekognition/DetectTextExample/DetectText.cs b/dotnetv3/Rekognition/DetectTextExample/DetectText.cs index 21866f48b3d..5622ba4655c 100644 --- a/dotnetv3/Rekognition/DetectTextExample/DetectText.cs +++ b/dotnetv3/Rekognition/DetectTextExample/DetectText.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DetectTextExample { diff --git a/dotnetv3/Rekognition/FaceRekognitionExample/FaceRekognitionExample/FaceRekognition.cs b/dotnetv3/Rekognition/FaceRekognitionExample/FaceRekognitionExample/FaceRekognition.cs index d7288502a6f..ff25c945ef8 100644 --- a/dotnetv3/Rekognition/FaceRekognitionExample/FaceRekognitionExample/FaceRekognition.cs +++ b/dotnetv3/Rekognition/FaceRekognitionExample/FaceRekognitionExample/FaceRekognition.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace FaceRekognitionExample { diff --git a/dotnetv3/Rekognition/FaceRekognitionExample/FaceRekognitionExampleTests/FaceRekognitionTests.cs b/dotnetv3/Rekognition/FaceRekognitionExample/FaceRekognitionExampleTests/FaceRekognitionTests.cs index 30f99cee58f..e9b300558e7 100644 --- a/dotnetv3/Rekognition/FaceRekognitionExample/FaceRekognitionExampleTests/FaceRekognitionTests.cs +++ b/dotnetv3/Rekognition/FaceRekognitionExample/FaceRekognitionExampleTests/FaceRekognitionTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace FaceRekognitionExampleTests { diff --git a/dotnetv3/Rekognition/ImageOrientationBoundingBoxExample/ImageOrientationBoundingBox.cs b/dotnetv3/Rekognition/ImageOrientationBoundingBoxExample/ImageOrientationBoundingBox.cs index 5dfd8dc673c..2662232a66d 100644 --- a/dotnetv3/Rekognition/ImageOrientationBoundingBoxExample/ImageOrientationBoundingBox.cs +++ b/dotnetv3/Rekognition/ImageOrientationBoundingBoxExample/ImageOrientationBoundingBox.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ImageOrientationBoundingBoxExample { diff --git a/dotnetv3/Rekognition/ListCollectionsExample/ListCollections.cs b/dotnetv3/Rekognition/ListCollectionsExample/ListCollections.cs index a9184a07b8d..10895effcd8 100644 --- a/dotnetv3/Rekognition/ListCollectionsExample/ListCollections.cs +++ b/dotnetv3/Rekognition/ListCollectionsExample/ListCollections.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ListCollectionsExample { diff --git a/dotnetv3/Rekognition/ListFacesExample/ListFaces.cs b/dotnetv3/Rekognition/ListFacesExample/ListFaces.cs index 08b0531ad74..6821b51a808 100644 --- a/dotnetv3/Rekognition/ListFacesExample/ListFaces.cs +++ b/dotnetv3/Rekognition/ListFacesExample/ListFaces.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ListFacesExample { diff --git a/dotnetv3/Rekognition/SearchFacesMatchingIdExample/SearchFacesMatchingId.cs b/dotnetv3/Rekognition/SearchFacesMatchingIdExample/SearchFacesMatchingId.cs index bdc6bb2dede..30a3ac64f06 100644 --- a/dotnetv3/Rekognition/SearchFacesMatchingIdExample/SearchFacesMatchingId.cs +++ b/dotnetv3/Rekognition/SearchFacesMatchingIdExample/SearchFacesMatchingId.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace SearchFacesMatchingIdExample { diff --git a/dotnetv3/Rekognition/SearchFacesMatchingImageExample/SearchFacesMatchingImage.cs b/dotnetv3/Rekognition/SearchFacesMatchingImageExample/SearchFacesMatchingImage.cs index 876e5329109..aa904e54acb 100644 --- a/dotnetv3/Rekognition/SearchFacesMatchingImageExample/SearchFacesMatchingImage.cs +++ b/dotnetv3/Rekognition/SearchFacesMatchingImageExample/SearchFacesMatchingImage.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace SearchFacesMatchingImageExample { diff --git a/dotnetv3/Route53/Actions/HelloRoute53.cs b/dotnetv3/Route53/Actions/HelloRoute53.cs index c253d4cf99b..dfc60fc6f8e 100644 --- a/dotnetv3/Route53/Actions/HelloRoute53.cs +++ b/dotnetv3/Route53/Actions/HelloRoute53.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.Route53Domains; using Amazon.Route53Domains.Model; diff --git a/dotnetv3/Route53/Actions/Route53Wrapper.cs b/dotnetv3/Route53/Actions/Route53Wrapper.cs index eb9037d3a7c..64f0a5e39f2 100644 --- a/dotnetv3/Route53/Actions/Route53Wrapper.cs +++ b/dotnetv3/Route53/Actions/Route53Wrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.Route53Domains; using Amazon.Route53Domains.Model; diff --git a/dotnetv3/Route53/Scenarios/Route53DomainScenario.cs b/dotnetv3/Route53/Scenarios/Route53DomainScenario.cs index d5913e5de1d..0fc27ef4dca 100644 --- a/dotnetv3/Route53/Scenarios/Route53DomainScenario.cs +++ b/dotnetv3/Route53/Scenarios/Route53DomainScenario.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.Route53Domains; using Amazon.Route53Domains.Model; diff --git a/dotnetv3/Route53/Tests/Route53ServiceTests.cs b/dotnetv3/Route53/Tests/Route53ServiceTests.cs index 56d1dcad19f..9d81867912f 100644 --- a/dotnetv3/Route53/Tests/Route53ServiceTests.cs +++ b/dotnetv3/Route53/Tests/Route53ServiceTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.Route53Domains; using Amazon.Route53Domains.Model; diff --git a/dotnetv3/Route53/Tests/Usings.cs b/dotnetv3/Route53/Tests/Usings.cs index 158ebd88747..ef5ce323ba9 100644 --- a/dotnetv3/Route53/Tests/Usings.cs +++ b/dotnetv3/Route53/Tests/Usings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Xunit; global using Xunit.Extensions.Ordering; diff --git a/dotnetv3/S3/AbortMPUExample/AbortMPU.cs b/dotnetv3/S3/AbortMPUExample/AbortMPU.cs index 802fc8da309..547ae708c5f 100644 --- a/dotnetv3/S3/AbortMPUExample/AbortMPU.cs +++ b/dotnetv3/S3/AbortMPUExample/AbortMPU.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace AbortMPUExample { diff --git a/dotnetv3/S3/BucketACLExample/BucketACL.cs b/dotnetv3/S3/BucketACLExample/BucketACL.cs index 998d887b505..971ddfc897d 100644 --- a/dotnetv3/S3/BucketACLExample/BucketACL.cs +++ b/dotnetv3/S3/BucketACLExample/BucketACL.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace BucketACLExample { diff --git a/dotnetv3/S3/CopyObjectExample/CopyObject.cs b/dotnetv3/S3/CopyObjectExample/CopyObject.cs index c74d126b113..7b1c7a1762c 100644 --- a/dotnetv3/S3/CopyObjectExample/CopyObject.cs +++ b/dotnetv3/S3/CopyObjectExample/CopyObject.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 /// /// This example copies an object from one Amazon Simple Storage Service diff --git a/dotnetv3/S3/EnableNotificationsExample/EnableNotifications.cs b/dotnetv3/S3/EnableNotificationsExample/EnableNotifications.cs index f3ac0d6d873..6f4bd632cf6 100644 --- a/dotnetv3/S3/EnableNotificationsExample/EnableNotifications.cs +++ b/dotnetv3/S3/EnableNotificationsExample/EnableNotifications.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace EnableNotificationsExample { diff --git a/dotnetv3/S3/GenPresignedURLExample/GenPresignedUrl.cs b/dotnetv3/S3/GenPresignedURLExample/GenPresignedUrl.cs index 57aabbede4d..13abf0b1561 100644 --- a/dotnetv3/S3/GenPresignedURLExample/GenPresignedUrl.cs +++ b/dotnetv3/S3/GenPresignedURLExample/GenPresignedUrl.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 /// /// This example generates a presigned URL for an object in an Amazon diff --git a/dotnetv3/S3/LifecycleExample/Lifecycle.cs b/dotnetv3/S3/LifecycleExample/Lifecycle.cs index 9c0f1e99cb1..7e402986c92 100644 --- a/dotnetv3/S3/LifecycleExample/Lifecycle.cs +++ b/dotnetv3/S3/LifecycleExample/Lifecycle.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace LifecycleExample { diff --git a/dotnetv3/S3/ListBucketsExample/ListBuckets.cs b/dotnetv3/S3/ListBucketsExample/ListBuckets.cs index b14d4bcc72b..9c39c728352 100644 --- a/dotnetv3/S3/ListBucketsExample/ListBuckets.cs +++ b/dotnetv3/S3/ListBucketsExample/ListBuckets.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[S3.dotnetv3.ListBuckets] namespace ListBucketsExample diff --git a/dotnetv3/S3/ListObjectsPaginatorExample/ListObjectsPaginator.cs b/dotnetv3/S3/ListObjectsPaginatorExample/ListObjectsPaginator.cs index df3141fe10b..afdeacb3e0c 100644 --- a/dotnetv3/S3/ListObjectsPaginatorExample/ListObjectsPaginator.cs +++ b/dotnetv3/S3/ListObjectsPaginatorExample/ListObjectsPaginator.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ListObjectsPaginatorExample { diff --git a/dotnetv3/S3/MPUapiCopyObjExample/MPUapiCopyObj.cs b/dotnetv3/S3/MPUapiCopyObjExample/MPUapiCopyObj.cs index 4b4b004f65a..a930d088109 100644 --- a/dotnetv3/S3/MPUapiCopyObjExample/MPUapiCopyObj.cs +++ b/dotnetv3/S3/MPUapiCopyObjExample/MPUapiCopyObj.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace MPUapiCopyObjectExample { diff --git a/dotnetv3/S3/ManageACLsExample/ManageACLs.cs b/dotnetv3/S3/ManageACLsExample/ManageACLs.cs index 8022642678c..bf620e05f33 100644 --- a/dotnetv3/S3/ManageACLsExample/ManageACLs.cs +++ b/dotnetv3/S3/ManageACLsExample/ManageACLs.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ManageACLsExample { diff --git a/dotnetv3/S3/ObjectTagExample/ObjectTag.cs b/dotnetv3/S3/ObjectTagExample/ObjectTag.cs index 6636cece08a..862ea6dc228 100644 --- a/dotnetv3/S3/ObjectTagExample/ObjectTag.cs +++ b/dotnetv3/S3/ObjectTagExample/ObjectTag.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ObjectTagExample { diff --git a/dotnetv3/S3/RestoreArchivedObjectExample/RestoreArchivedObject.cs b/dotnetv3/S3/RestoreArchivedObjectExample/RestoreArchivedObject.cs index 5bcd88c1a79..79b3c72de48 100644 --- a/dotnetv3/S3/RestoreArchivedObjectExample/RestoreArchivedObject.cs +++ b/dotnetv3/S3/RestoreArchivedObjectExample/RestoreArchivedObject.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace RestoreArchivedObjectExample { diff --git a/dotnetv3/S3/S3_Basics/GlobalUsings.cs b/dotnetv3/S3/S3_Basics/GlobalUsings.cs index beb68ecbc7b..afef03366a1 100644 --- a/dotnetv3/S3/S3_Basics/GlobalUsings.cs +++ b/dotnetv3/S3/S3_Basics/GlobalUsings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[S3.dotnetv3.S3_BasicsScenario.GlobalUsings] global using Amazon.S3; diff --git a/dotnetv3/S3/S3_Basics/S3Bucket.cs b/dotnetv3/S3/S3_Basics/S3Bucket.cs index 29e357a5d7c..61ada153122 100644 --- a/dotnetv3/S3/S3_Basics/S3Bucket.cs +++ b/dotnetv3/S3/S3_Basics/S3Bucket.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace S3_BasicsScenario { diff --git a/dotnetv3/S3/S3_Basics/S3_Basics.cs b/dotnetv3/S3/S3_Basics/S3_Basics.cs index fafab964c6d..8c37398bb02 100644 --- a/dotnetv3/S3/S3_Basics/S3_Basics.cs +++ b/dotnetv3/S3/S3_Basics/S3_Basics.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // This example shows the basic API calls for the Amazon Simple Storage Service // (Amazon S3). The example steps you through the process of creating diff --git a/dotnetv3/S3/S3_BasicsScenarioTests/GlobalUsings.cs b/dotnetv3/S3/S3_BasicsScenarioTests/GlobalUsings.cs index 5f90c3bb123..9b88c94d541 100644 --- a/dotnetv3/S3/S3_BasicsScenarioTests/GlobalUsings.cs +++ b/dotnetv3/S3/S3_BasicsScenarioTests/GlobalUsings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // Global using directives diff --git a/dotnetv3/S3/S3_BasicsScenarioTests/S3BucketTests.cs b/dotnetv3/S3/S3_BasicsScenarioTests/S3BucketTests.cs index 8ed3537f2b5..4cf50486130 100644 --- a/dotnetv3/S3/S3_BasicsScenarioTests/S3BucketTests.cs +++ b/dotnetv3/S3/S3_BasicsScenarioTests/S3BucketTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace S3_BasicsScenario.Tests { diff --git a/dotnetv3/S3/SSECLowLevelMPUcopyObjectExample/SSECLowLevelMPUcopyObject.cs b/dotnetv3/S3/SSECLowLevelMPUcopyObjectExample/SSECLowLevelMPUcopyObject.cs index ebad916d833..ea062cfc08b 100644 --- a/dotnetv3/S3/SSECLowLevelMPUcopyObjectExample/SSECLowLevelMPUcopyObject.cs +++ b/dotnetv3/S3/SSECLowLevelMPUcopyObjectExample/SSECLowLevelMPUcopyObject.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace SSECLowLevelMPUcopyObjectExample { diff --git a/dotnetv3/S3/SSEClientEncryptionExample/SSEClientEncryption.cs b/dotnetv3/S3/SSEClientEncryptionExample/SSEClientEncryption.cs index 7a3e1648022..cbf24036da1 100644 --- a/dotnetv3/S3/SSEClientEncryptionExample/SSEClientEncryption.cs +++ b/dotnetv3/S3/SSEClientEncryptionExample/SSEClientEncryption.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace SSEClientEncryptionExample { diff --git a/dotnetv3/S3/ServerAccessLoggingExample/ServerAccessLogging.cs b/dotnetv3/S3/ServerAccessLoggingExample/ServerAccessLogging.cs index 2af74b592ac..af45275d4f7 100644 --- a/dotnetv3/S3/ServerAccessLoggingExample/ServerAccessLogging.cs +++ b/dotnetv3/S3/ServerAccessLoggingExample/ServerAccessLogging.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ServerAccessLoggingExample { diff --git a/dotnetv3/S3/ServerSideEncryptionExample/ServerSideEncryption.cs b/dotnetv3/S3/ServerSideEncryptionExample/ServerSideEncryption.cs index 431b4a5f5be..ce5246bab9c 100644 --- a/dotnetv3/S3/ServerSideEncryptionExample/ServerSideEncryption.cs +++ b/dotnetv3/S3/ServerSideEncryptionExample/ServerSideEncryption.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ServerSideEncryptionExample { diff --git a/dotnetv3/S3/TrackMPUUsingHighLevelAPIExample/TrackMPUUsingHighLevelAPI.cs b/dotnetv3/S3/TrackMPUUsingHighLevelAPIExample/TrackMPUUsingHighLevelAPI.cs index 7b5ae441076..17f7b50ddb7 100644 --- a/dotnetv3/S3/TrackMPUUsingHighLevelAPIExample/TrackMPUUsingHighLevelAPI.cs +++ b/dotnetv3/S3/TrackMPUUsingHighLevelAPIExample/TrackMPUUsingHighLevelAPI.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace TrackMPUUsingHighLevelAPIExample { diff --git a/dotnetv3/S3/TransferAccelerationExample/TransferAcceleration.cs b/dotnetv3/S3/TransferAccelerationExample/TransferAcceleration.cs index 8aa97c78cba..75ded2d42ad 100644 --- a/dotnetv3/S3/TransferAccelerationExample/TransferAcceleration.cs +++ b/dotnetv3/S3/TransferAccelerationExample/TransferAcceleration.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace TransferAccelerationExample { diff --git a/dotnetv3/S3/UploadUsingPresignedURLExample/UploadUsingPresignedURL.cs b/dotnetv3/S3/UploadUsingPresignedURLExample/UploadUsingPresignedURL.cs index 2c20a68e12c..a9fc781bd16 100644 --- a/dotnetv3/S3/UploadUsingPresignedURLExample/UploadUsingPresignedURL.cs +++ b/dotnetv3/S3/UploadUsingPresignedURLExample/UploadUsingPresignedURL.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace UploadUsingPresignedURLExample { diff --git a/dotnetv3/S3/WebsiteConfigExample/WebsiteConfig.cs b/dotnetv3/S3/WebsiteConfigExample/WebsiteConfig.cs index 584e5e3c25a..abddc644e66 100644 --- a/dotnetv3/S3/WebsiteConfigExample/WebsiteConfig.cs +++ b/dotnetv3/S3/WebsiteConfigExample/WebsiteConfig.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace WebsiteConfigExample { diff --git a/dotnetv3/S3/non-versioned-examples/DeleteMultipleObjectsExample/DeleteMultipleObjects.cs b/dotnetv3/S3/non-versioned-examples/DeleteMultipleObjectsExample/DeleteMultipleObjects.cs index c232ac2b9fd..10439db7b67 100644 --- a/dotnetv3/S3/non-versioned-examples/DeleteMultipleObjectsExample/DeleteMultipleObjects.cs +++ b/dotnetv3/S3/non-versioned-examples/DeleteMultipleObjectsExample/DeleteMultipleObjects.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DeleteMultipleObjectsExample { diff --git a/dotnetv3/S3/non-versioned-examples/DeleteObjectExample/DeleteObject.cs b/dotnetv3/S3/non-versioned-examples/DeleteObjectExample/DeleteObject.cs index 4190458308e..60b3d539d5f 100644 --- a/dotnetv3/S3/non-versioned-examples/DeleteObjectExample/DeleteObject.cs +++ b/dotnetv3/S3/non-versioned-examples/DeleteObjectExample/DeleteObject.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DeleteObjectExample { diff --git a/dotnetv3/S3/s3CORSExample/S3CORS.cs b/dotnetv3/S3/s3CORSExample/S3CORS.cs index 6cb72d9fbe7..e412253c7d2 100644 --- a/dotnetv3/S3/s3CORSExample/S3CORS.cs +++ b/dotnetv3/S3/s3CORSExample/S3CORS.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace S3CORSExample { diff --git a/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasics/GlobalUsings.cs b/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasics/GlobalUsings.cs index c6a85f75056..e109fda6fa9 100644 --- a/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasics/GlobalUsings.cs +++ b/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasics/GlobalUsings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[S3.dotnetv3.TransferUtilityBasics.GlobalUsings] global using System.Text; diff --git a/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasics/TransferBasics.cs b/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasics/TransferBasics.cs index db96d00a5a2..2fa1968d3cb 100644 --- a/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasics/TransferBasics.cs +++ b/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasics/TransferBasics.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[S3.dotnetv3.TransferUtilityBasics.Main] diff --git a/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasics/TransferMethods.cs b/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasics/TransferMethods.cs index 17a29312e47..534eb22e017 100644 --- a/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasics/TransferMethods.cs +++ b/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasics/TransferMethods.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace TransferUtilityBasics { diff --git a/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasicsTests/GlobalUsings.cs b/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasicsTests/GlobalUsings.cs index 033c400042c..4a34a7a7bac 100644 --- a/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasicsTests/GlobalUsings.cs +++ b/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasicsTests/GlobalUsings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 global using Amazon.S3; global using Amazon.S3.Transfer; diff --git a/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasicsTests/TransferMethodsTests.cs b/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasicsTests/TransferMethodsTests.cs index 41643e31a8c..56db92c5fdb 100644 --- a/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasicsTests/TransferMethodsTests.cs +++ b/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasicsTests/TransferMethodsTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Xunit.Extensions.Ordering; diff --git a/dotnetv3/S3/versioned-examples/DeleteMultipleObjectsExample/DeleteMultipleObjects.cs b/dotnetv3/S3/versioned-examples/DeleteMultipleObjectsExample/DeleteMultipleObjects.cs index 4f0866f9f7b..54cb686c928 100644 --- a/dotnetv3/S3/versioned-examples/DeleteMultipleObjectsExample/DeleteMultipleObjects.cs +++ b/dotnetv3/S3/versioned-examples/DeleteMultipleObjectsExample/DeleteMultipleObjects.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DeleteMultipleObjectsExample { diff --git a/dotnetv3/S3/versioned-examples/DeleteObjectVersionExample/DeleteObjectVersion.cs b/dotnetv3/S3/versioned-examples/DeleteObjectVersionExample/DeleteObjectVersion.cs index 193b6569a18..fb3555f2157 100644 --- a/dotnetv3/S3/versioned-examples/DeleteObjectVersionExample/DeleteObjectVersion.cs +++ b/dotnetv3/S3/versioned-examples/DeleteObjectVersionExample/DeleteObjectVersion.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DeleteObjectVersionExample { diff --git a/dotnetv3/S3/versioned-examples/ListObjectVersionsExample/ListObjectVersions.cs b/dotnetv3/S3/versioned-examples/ListObjectVersionsExample/ListObjectVersions.cs index ec3a7b2fc70..d65e5935880 100644 --- a/dotnetv3/S3/versioned-examples/ListObjectVersionsExample/ListObjectVersions.cs +++ b/dotnetv3/S3/versioned-examples/ListObjectVersionsExample/ListObjectVersions.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ListObjectVersionsExample { diff --git a/dotnetv3/SES/Actions/SESActionExamples.cs b/dotnetv3/SES/Actions/SESActionExamples.cs index 4744dbc30cd..a05f284c53c 100644 --- a/dotnetv3/SES/Actions/SESActionExamples.cs +++ b/dotnetv3/SES/Actions/SESActionExamples.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.SimpleEmail; using Microsoft.Extensions.DependencyInjection; diff --git a/dotnetv3/SES/Actions/SESWrapper.cs b/dotnetv3/SES/Actions/SESWrapper.cs index 8ec98b1f97c..273e71b8460 100644 --- a/dotnetv3/SES/Actions/SESWrapper.cs +++ b/dotnetv3/SES/Actions/SESWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Net; using System.Text.Json; diff --git a/dotnetv3/SES/Tests/SESExampleTests.cs b/dotnetv3/SES/Tests/SESExampleTests.cs index f092bec4cc7..d74e74c7dd8 100644 --- a/dotnetv3/SES/Tests/SESExampleTests.cs +++ b/dotnetv3/SES/Tests/SESExampleTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.SimpleEmail; using Microsoft.Extensions.Configuration; diff --git a/dotnetv3/SES/Tests/Usings.cs b/dotnetv3/SES/Tests/Usings.cs index 158ebd88747..ef5ce323ba9 100644 --- a/dotnetv3/SES/Tests/Usings.cs +++ b/dotnetv3/SES/Tests/Usings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Xunit; global using Xunit.Extensions.Ordering; diff --git a/dotnetv3/SNS/CreateSNSTopicExample/CreateSNSTopicExample/CreateSNSTopic.cs b/dotnetv3/SNS/CreateSNSTopicExample/CreateSNSTopicExample/CreateSNSTopic.cs index 7ef75063f2c..935a0e3674d 100644 --- a/dotnetv3/SNS/CreateSNSTopicExample/CreateSNSTopicExample/CreateSNSTopic.cs +++ b/dotnetv3/SNS/CreateSNSTopicExample/CreateSNSTopicExample/CreateSNSTopic.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace CreateSNSTopicExample { diff --git a/dotnetv3/SNS/GetTopicAttributesExample/GetTopicAttributesExample/GetTopicAttributes.cs b/dotnetv3/SNS/GetTopicAttributesExample/GetTopicAttributesExample/GetTopicAttributes.cs index a54df384db3..24fa0ec9bda 100644 --- a/dotnetv3/SNS/GetTopicAttributesExample/GetTopicAttributesExample/GetTopicAttributes.cs +++ b/dotnetv3/SNS/GetTopicAttributesExample/GetTopicAttributesExample/GetTopicAttributes.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace GetTopicAttributesExample { diff --git a/dotnetv3/SNS/IsPhoneNumOptedOutExample/IsPhoneNumOptedOutExample/IsPhoneNumOptedOut.cs b/dotnetv3/SNS/IsPhoneNumOptedOutExample/IsPhoneNumOptedOutExample/IsPhoneNumOptedOut.cs index 6bd84f9c140..d8b0812fe8a 100644 --- a/dotnetv3/SNS/IsPhoneNumOptedOutExample/IsPhoneNumOptedOutExample/IsPhoneNumOptedOut.cs +++ b/dotnetv3/SNS/IsPhoneNumOptedOutExample/IsPhoneNumOptedOutExample/IsPhoneNumOptedOut.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace IsPhoneNumOptedOutExample { diff --git a/dotnetv3/SNS/ListSNSSubscriptionsExample/ListSNSSubscriptionsExample/ListSubscriptions.cs b/dotnetv3/SNS/ListSNSSubscriptionsExample/ListSNSSubscriptionsExample/ListSubscriptions.cs index 024fc3d3135..16e4b03476c 100644 --- a/dotnetv3/SNS/ListSNSSubscriptionsExample/ListSNSSubscriptionsExample/ListSubscriptions.cs +++ b/dotnetv3/SNS/ListSNSSubscriptionsExample/ListSNSSubscriptionsExample/ListSubscriptions.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ListSNSSubscriptionsExample { diff --git a/dotnetv3/SNS/ListSNSTopicsExample/ListSNSTopicsExample/ListSNSTopics.cs b/dotnetv3/SNS/ListSNSTopicsExample/ListSNSTopicsExample/ListSNSTopics.cs index 85058bb1993..29e57fd74d1 100644 --- a/dotnetv3/SNS/ListSNSTopicsExample/ListSNSTopicsExample/ListSNSTopics.cs +++ b/dotnetv3/SNS/ListSNSTopicsExample/ListSNSTopicsExample/ListSNSTopics.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ListSNSTopicsExample { diff --git a/dotnetv3/SNS/ManageTopicSubscriptionExample/ManageTopicSubscriptionExample/ManageTopicSubscription.cs b/dotnetv3/SNS/ManageTopicSubscriptionExample/ManageTopicSubscriptionExample/ManageTopicSubscription.cs index c7f049310a9..61e6fb9d03f 100644 --- a/dotnetv3/SNS/ManageTopicSubscriptionExample/ManageTopicSubscriptionExample/ManageTopicSubscription.cs +++ b/dotnetv3/SNS/ManageTopicSubscriptionExample/ManageTopicSubscriptionExample/ManageTopicSubscription.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ManageTopicSubscriptionExample { diff --git a/dotnetv3/SNS/PublishToSNSTopicExample/PublishToSNSTopicExample/PublishToSNSTopic.cs b/dotnetv3/SNS/PublishToSNSTopicExample/PublishToSNSTopicExample/PublishToSNSTopic.cs index a20e515be59..9ba1cbcfdbe 100644 --- a/dotnetv3/SNS/PublishToSNSTopicExample/PublishToSNSTopicExample/PublishToSNSTopic.cs +++ b/dotnetv3/SNS/PublishToSNSTopicExample/PublishToSNSTopicExample/PublishToSNSTopic.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace PublishToSNSTopicExample { diff --git a/dotnetv3/SNS/SNSMessageExample/SNSMessageExample/SNSMessage.cs b/dotnetv3/SNS/SNSMessageExample/SNSMessageExample/SNSMessage.cs index a08659879b1..04abafb32ab 100644 --- a/dotnetv3/SNS/SNSMessageExample/SNSMessageExample/SNSMessage.cs +++ b/dotnetv3/SNS/SNSMessageExample/SNSMessageExample/SNSMessage.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[SNS.dotnetv3.SNSMessageExample] namespace SNSMessageExample diff --git a/dotnetv3/SNS/SNSMessageExample/SNSMessageExample/SNSMessageExample.cs b/dotnetv3/SNS/SNSMessageExample/SNSMessageExample/SNSMessageExample.cs index 6b7765c125f..3bdbf1b61b1 100644 --- a/dotnetv3/SNS/SNSMessageExample/SNSMessageExample/SNSMessageExample.cs +++ b/dotnetv3/SNS/SNSMessageExample/SNSMessageExample/SNSMessageExample.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace SNSMessageExample { diff --git a/dotnetv3/SNS/SNSMessageExample/SNSMessageExampleTest/SNSMessageTest.cs b/dotnetv3/SNS/SNSMessageExample/SNSMessageExampleTest/SNSMessageTest.cs index 26971857631..bfe72895d6a 100644 --- a/dotnetv3/SNS/SNSMessageExample/SNSMessageExampleTest/SNSMessageTest.cs +++ b/dotnetv3/SNS/SNSMessageExample/SNSMessageExampleTest/SNSMessageTest.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using System.Net; diff --git a/dotnetv3/SQS/AuthorizeS3ToSendMessageExample/AuthorizeS3ToSendMessageExample/AuthorizeS3ToSendMessage.cs b/dotnetv3/SQS/AuthorizeS3ToSendMessageExample/AuthorizeS3ToSendMessageExample/AuthorizeS3ToSendMessage.cs index bc28c16a864..d9ea7173398 100644 --- a/dotnetv3/SQS/AuthorizeS3ToSendMessageExample/AuthorizeS3ToSendMessageExample/AuthorizeS3ToSendMessage.cs +++ b/dotnetv3/SQS/AuthorizeS3ToSendMessageExample/AuthorizeS3ToSendMessageExample/AuthorizeS3ToSendMessage.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 /// /// Shows how to authorize an Amazon Simple Storage Service (Amazon S3) diff --git a/dotnetv3/SQS/CreateSendExample/CreateSendExample/CreateSendExample.cs b/dotnetv3/SQS/CreateSendExample/CreateSendExample/CreateSendExample.cs index 1d7b85ba9b9..d3598946664 100644 --- a/dotnetv3/SQS/CreateSendExample/CreateSendExample/CreateSendExample.cs +++ b/dotnetv3/SQS/CreateSendExample/CreateSendExample/CreateSendExample.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // The following example creates a queue using the Amazon Simple Queue // Service (Amazon SQS) and then sends a message to the queue. diff --git a/dotnetv3/SQS/CreateSendExample/CreateSendExampleTests/CreateSendExampleTests.cs b/dotnetv3/SQS/CreateSendExample/CreateSendExampleTests/CreateSendExampleTests.cs index dfb170cd5c2..08fd164599e 100644 --- a/dotnetv3/SQS/CreateSendExample/CreateSendExampleTests/CreateSendExampleTests.cs +++ b/dotnetv3/SQS/CreateSendExample/CreateSendExampleTests/CreateSendExampleTests.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using System.Net; diff --git a/dotnetv3/SQS/DeleteMessageExample/DeleteMessageExample/DeleteMessage.cs b/dotnetv3/SQS/DeleteMessageExample/DeleteMessageExample/DeleteMessage.cs index 592983c6bcb..4fe068e9eb4 100644 --- a/dotnetv3/SQS/DeleteMessageExample/DeleteMessageExample/DeleteMessage.cs +++ b/dotnetv3/SQS/DeleteMessageExample/DeleteMessageExample/DeleteMessage.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 /// /// Shows how to delete one or more messages from an Amazon Simple Queue diff --git a/dotnetv3/SQS/GetQueueUrlExample/GetQueueUrlExample/GetQueueUrl.cs b/dotnetv3/SQS/GetQueueUrlExample/GetQueueUrlExample/GetQueueUrl.cs index 68b8c0ecde1..cc863b8b463 100644 --- a/dotnetv3/SQS/GetQueueUrlExample/GetQueueUrlExample/GetQueueUrl.cs +++ b/dotnetv3/SQS/GetQueueUrlExample/GetQueueUrlExample/GetQueueUrl.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 /// /// Shows how to retrieve the Amazon Simple Queue Service (Amazon SQS) diff --git a/dotnetv3/SQS/ReceiveDeleteExample/ReceiveDeleteExample/ReceiveDeleteExample.cs b/dotnetv3/SQS/ReceiveDeleteExample/ReceiveDeleteExample/ReceiveDeleteExample.cs index b5fd9e07a27..bbdd2137cee 100644 --- a/dotnetv3/SQS/ReceiveDeleteExample/ReceiveDeleteExample/ReceiveDeleteExample.cs +++ b/dotnetv3/SQS/ReceiveDeleteExample/ReceiveDeleteExample/ReceiveDeleteExample.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 /// /// This example retrieves a single message from an Amazon Simple diff --git a/dotnetv3/SQS/ReceiveDeleteExample/ReceiveDeleteExampleTests/ReceiveDeleteExampleTests.cs b/dotnetv3/SQS/ReceiveDeleteExample/ReceiveDeleteExampleTests/ReceiveDeleteExampleTests.cs index 21c392de6f9..393470768c4 100644 --- a/dotnetv3/SQS/ReceiveDeleteExample/ReceiveDeleteExampleTests/ReceiveDeleteExampleTests.cs +++ b/dotnetv3/SQS/ReceiveDeleteExample/ReceiveDeleteExampleTests/ReceiveDeleteExampleTests.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using System.Net; diff --git a/dotnetv3/STS/AssumeRole/AssumeRoleExample/AssumeRole.cs b/dotnetv3/STS/AssumeRole/AssumeRoleExample/AssumeRole.cs index f6df58f71ab..292797cedf1 100644 --- a/dotnetv3/STS/AssumeRole/AssumeRoleExample/AssumeRole.cs +++ b/dotnetv3/STS/AssumeRole/AssumeRoleExample/AssumeRole.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[STS.dotnetv3.AssumeRoleMessage] using System; @@ -15,13 +15,13 @@ class AssumeRole /// /// This example shows how to use the AWS Security Token /// Service (AWS STS) to assume an IAM role. - /// + /// /// NOTE: It is important that the role that will be assumed has a /// trust relationship with the account that will assume the role. - /// + /// /// Before you run the example, you need to create the role you want to /// assume and have it trust the IAM account that will assume that role. - /// + /// /// See https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html /// for help in working with roles. /// diff --git a/dotnetv3/STS/AssumeRole/AssumeRoleExampleTest/AssumeRoleTests.cs b/dotnetv3/STS/AssumeRole/AssumeRoleExampleTest/AssumeRoleTests.cs index a81028bcdc4..9f5970a3a11 100644 --- a/dotnetv3/STS/AssumeRole/AssumeRoleExampleTest/AssumeRoleTests.cs +++ b/dotnetv3/STS/AssumeRole/AssumeRoleExampleTest/AssumeRoleTests.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System.Net; using System.Threading; diff --git a/dotnetv3/SageMaker/Actions/HelloSageMaker.cs b/dotnetv3/SageMaker/Actions/HelloSageMaker.cs index 8d1c169b716..28b44ef115f 100644 --- a/dotnetv3/SageMaker/Actions/HelloSageMaker.cs +++ b/dotnetv3/SageMaker/Actions/HelloSageMaker.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[SageMaker.dotnetv3.HelloSageMaker] diff --git a/dotnetv3/SageMaker/Actions/SageMakerWrapper.cs b/dotnetv3/SageMaker/Actions/SageMakerWrapper.cs index e7b8994cb01..798e0a17c3b 100644 --- a/dotnetv3/SageMaker/Actions/SageMakerWrapper.cs +++ b/dotnetv3/SageMaker/Actions/SageMakerWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[SageMaker.dotnetv3.SagemakerWrapper] diff --git a/dotnetv3/SageMaker/Lambdas/PipelineRequest.cs b/dotnetv3/SageMaker/Lambdas/PipelineRequest.cs index 20b5d833b93..69e4254d99f 100644 --- a/dotnetv3/SageMaker/Lambdas/PipelineRequest.cs +++ b/dotnetv3/SageMaker/Lambdas/PipelineRequest.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.Lambda.SQSEvents; diff --git a/dotnetv3/SageMaker/Lambdas/QueuePayload.cs b/dotnetv3/SageMaker/Lambdas/QueuePayload.cs index a604c961bc0..66e66703fc1 100644 --- a/dotnetv3/SageMaker/Lambdas/QueuePayload.cs +++ b/dotnetv3/SageMaker/Lambdas/QueuePayload.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace SageMakerLambda; diff --git a/dotnetv3/SageMaker/Lambdas/SageMakerLambdaFunction.cs b/dotnetv3/SageMaker/Lambdas/SageMakerLambdaFunction.cs index 5ebb59658ff..0b2a4d03b68 100644 --- a/dotnetv3/SageMaker/Lambdas/SageMakerLambdaFunction.cs +++ b/dotnetv3/SageMaker/Lambdas/SageMakerLambdaFunction.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[SageMaker.dotnetv3.SagemakerLambda] diff --git a/dotnetv3/SageMaker/Scenarios/PipelineWorkflow.cs b/dotnetv3/SageMaker/Scenarios/PipelineWorkflow.cs index 248179546fe..d99149fe241 100644 --- a/dotnetv3/SageMaker/Scenarios/PipelineWorkflow.cs +++ b/dotnetv3/SageMaker/Scenarios/PipelineWorkflow.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon; using Amazon.EC2; diff --git a/dotnetv3/SageMaker/Tests/SageMakerTests.cs b/dotnetv3/SageMaker/Tests/SageMakerTests.cs index 48f9012ce36..46a811e5ab3 100644 --- a/dotnetv3/SageMaker/Tests/SageMakerTests.cs +++ b/dotnetv3/SageMaker/Tests/SageMakerTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon; using Amazon.IdentityManagement; diff --git a/dotnetv3/SageMaker/Tests/Usings.cs b/dotnetv3/SageMaker/Tests/Usings.cs index 158ebd88747..ef5ce323ba9 100644 --- a/dotnetv3/SageMaker/Tests/Usings.cs +++ b/dotnetv3/SageMaker/Tests/Usings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Xunit; global using Xunit.Extensions.Ordering; diff --git a/dotnetv3/SecretsManager/GetSecretValue/GetSecretValueExample/GetSecretValue.cs b/dotnetv3/SecretsManager/GetSecretValue/GetSecretValueExample/GetSecretValue.cs index 61f19120bd0..09c2ef49abd 100644 --- a/dotnetv3/SecretsManager/GetSecretValue/GetSecretValueExample/GetSecretValue.cs +++ b/dotnetv3/SecretsManager/GetSecretValue/GetSecretValueExample/GetSecretValue.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace GetSecretValueExample { diff --git a/dotnetv3/SecretsManager/GetSecretValue/GetSecretValueExampleTests/GetSecretValueTests.cs b/dotnetv3/SecretsManager/GetSecretValue/GetSecretValueExampleTests/GetSecretValueTests.cs index 72a9a08535c..20c1af57391 100644 --- a/dotnetv3/SecretsManager/GetSecretValue/GetSecretValueExampleTests/GetSecretValueTests.cs +++ b/dotnetv3/SecretsManager/GetSecretValue/GetSecretValueExampleTests/GetSecretValueTests.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using System.IO; diff --git a/dotnetv3/StepFunctions/Actions/HelloStepFunctions.cs b/dotnetv3/StepFunctions/Actions/HelloStepFunctions.cs index b51fff31689..145139e57fa 100644 --- a/dotnetv3/StepFunctions/Actions/HelloStepFunctions.cs +++ b/dotnetv3/StepFunctions/Actions/HelloStepFunctions.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[StepFunctions.dotnetv3.HelloStepFunctions] diff --git a/dotnetv3/StepFunctions/Actions/StepFunctionsWrapper.cs b/dotnetv3/StepFunctions/Actions/StepFunctionsWrapper.cs index e39b5886c22..5379b77436a 100644 --- a/dotnetv3/StepFunctions/Actions/StepFunctionsWrapper.cs +++ b/dotnetv3/StepFunctions/Actions/StepFunctionsWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[StepFunctions.dotnetv3.StepFunctionsActions] diff --git a/dotnetv3/StepFunctions/Scenarios/StepFunctionsBasics.cs b/dotnetv3/StepFunctions/Scenarios/StepFunctionsBasics.cs index dab4273be70..758ab328c35 100644 --- a/dotnetv3/StepFunctions/Scenarios/StepFunctionsBasics.cs +++ b/dotnetv3/StepFunctions/Scenarios/StepFunctionsBasics.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[StepFunctions.dotnetv3.StepFunctionsBasics] diff --git a/dotnetv3/StepFunctions/Scenarios/UIMethods.cs b/dotnetv3/StepFunctions/Scenarios/UIMethods.cs index a7ae6f33472..75b401b003e 100644 --- a/dotnetv3/StepFunctions/Scenarios/UIMethods.cs +++ b/dotnetv3/StepFunctions/Scenarios/UIMethods.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[StepFunctions.dotnetv3.StepFunctionsBasics.UIMethods] namespace StepFunctionsBasics; diff --git a/dotnetv3/StepFunctions/Scenarios/Usings.cs b/dotnetv3/StepFunctions/Scenarios/Usings.cs index 35f9937cce4..92b5b6c5dcd 100644 --- a/dotnetv3/StepFunctions/Scenarios/Usings.cs +++ b/dotnetv3/StepFunctions/Scenarios/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[StepFunctions.dotnetv3.StepFunctionsBasics.Usings] global using System.Text.Json; diff --git a/dotnetv3/StepFunctions/Tests/StepFunctionsWrapperTests.cs b/dotnetv3/StepFunctions/Tests/StepFunctionsWrapperTests.cs index 0f55f8fdd24..01856c44f7f 100644 --- a/dotnetv3/StepFunctions/Tests/StepFunctionsWrapperTests.cs +++ b/dotnetv3/StepFunctions/Tests/StepFunctionsWrapperTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.StepFunctions.Model; diff --git a/dotnetv3/StepFunctions/Tests/Usings.cs b/dotnetv3/StepFunctions/Tests/Usings.cs index faa359be2bd..f057a79c070 100644 --- a/dotnetv3/StepFunctions/Tests/Usings.cs +++ b/dotnetv3/StepFunctions/Tests/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 global using Amazon.StepFunctions; global using Microsoft.Extensions.Configuration; diff --git a/dotnetv3/Support/Actions/HelloSupport.cs b/dotnetv3/Support/Actions/HelloSupport.cs index 86e2ff5caa7..fa3bd122f56 100644 --- a/dotnetv3/Support/Actions/HelloSupport.cs +++ b/dotnetv3/Support/Actions/HelloSupport.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace SupportActions; diff --git a/dotnetv3/Support/Actions/SupportWrapper.cs b/dotnetv3/Support/Actions/SupportWrapper.cs index d31c21d4d7a..162d988e350 100644 --- a/dotnetv3/Support/Actions/SupportWrapper.cs +++ b/dotnetv3/Support/Actions/SupportWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Net; using Amazon.AWSSupport; diff --git a/dotnetv3/Support/Scenarios/SupportCaseScenario.cs b/dotnetv3/Support/Scenarios/SupportCaseScenario.cs index 02ef58af1f6..91de69d3064 100644 --- a/dotnetv3/Support/Scenarios/SupportCaseScenario.cs +++ b/dotnetv3/Support/Scenarios/SupportCaseScenario.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Text; using Amazon.AWSSupport; @@ -43,7 +43,7 @@ 10. Resolve the support case. static async Task Main(string[] args) { - // Set up dependency injection for the AWS Support service. + // Set up dependency injection for the AWS Support service. // Use your AWS profile name, or leave it blank to use the default profile. using var host = Host.CreateDefaultBuilder(args) .ConfigureLogging(logging => diff --git a/dotnetv3/Support/Tests/SupportIntegrationTests.cs b/dotnetv3/Support/Tests/SupportIntegrationTests.cs index a1b8050ffd1..ebfc4cc9e6a 100644 --- a/dotnetv3/Support/Tests/SupportIntegrationTests.cs +++ b/dotnetv3/Support/Tests/SupportIntegrationTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.AWSSupport; using Amazon.AWSSupport.Model; diff --git a/dotnetv3/Support/Tests/Usings.cs b/dotnetv3/Support/Tests/Usings.cs index 0979f98c637..ef5ce323ba9 100644 --- a/dotnetv3/Support/Tests/Usings.cs +++ b/dotnetv3/Support/Tests/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 global using Xunit; global using Xunit.Extensions.Ordering; diff --git a/dotnetv3/Transcribe/Actions/ActionExamples.cs b/dotnetv3/Transcribe/Actions/ActionExamples.cs index f0eedce961b..ce872b75f33 100644 --- a/dotnetv3/Transcribe/Actions/ActionExamples.cs +++ b/dotnetv3/Transcribe/Actions/ActionExamples.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Net; using System.Text.Json; diff --git a/dotnetv3/Transcribe/Actions/TranscribeWrapper.MedicalTranscriptions.cs b/dotnetv3/Transcribe/Actions/TranscribeWrapper.MedicalTranscriptions.cs index 33682427a3f..1968a473a3e 100644 --- a/dotnetv3/Transcribe/Actions/TranscribeWrapper.MedicalTranscriptions.cs +++ b/dotnetv3/Transcribe/Actions/TranscribeWrapper.MedicalTranscriptions.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Net; using Amazon.TranscribeService; diff --git a/dotnetv3/Transcribe/Actions/TranscribeWrapper.Vocabularies.cs b/dotnetv3/Transcribe/Actions/TranscribeWrapper.Vocabularies.cs index 041b93adffd..d1eb4cd8b1a 100644 --- a/dotnetv3/Transcribe/Actions/TranscribeWrapper.Vocabularies.cs +++ b/dotnetv3/Transcribe/Actions/TranscribeWrapper.Vocabularies.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Net; using Amazon.TranscribeService; diff --git a/dotnetv3/Transcribe/Actions/TranscribeWrapper.cs b/dotnetv3/Transcribe/Actions/TranscribeWrapper.cs index a3c7ef28d40..a062deba93c 100644 --- a/dotnetv3/Transcribe/Actions/TranscribeWrapper.cs +++ b/dotnetv3/Transcribe/Actions/TranscribeWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Net; using Amazon.TranscribeService; diff --git a/dotnetv3/Transcribe/Tests/TranscribeExampleTests.cs b/dotnetv3/Transcribe/Tests/TranscribeExampleTests.cs index f23f2ab7635..bee65f00350 100644 --- a/dotnetv3/Transcribe/Tests/TranscribeExampleTests.cs +++ b/dotnetv3/Transcribe/Tests/TranscribeExampleTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.TranscribeService; using Microsoft.Extensions.Configuration; diff --git a/dotnetv3/Transcribe/Tests/Usings.cs b/dotnetv3/Transcribe/Tests/Usings.cs index 158ebd88747..ef5ce323ba9 100644 --- a/dotnetv3/Transcribe/Tests/Usings.cs +++ b/dotnetv3/Transcribe/Tests/Usings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Xunit; global using Xunit.Extensions.Ordering; diff --git a/dotnetv3/Translate/BatchTranslateExample/BatchTranslate.cs b/dotnetv3/Translate/BatchTranslateExample/BatchTranslate.cs index af9d9160f21..01c5d81a37d 100644 --- a/dotnetv3/Translate/BatchTranslateExample/BatchTranslate.cs +++ b/dotnetv3/Translate/BatchTranslateExample/BatchTranslate.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace BatchTranslateExample { diff --git a/dotnetv3/Translate/DescribeTextTranslationExample/DescribeTextTranslation.cs b/dotnetv3/Translate/DescribeTextTranslationExample/DescribeTextTranslation.cs index 03c40a6afb3..040835b317c 100644 --- a/dotnetv3/Translate/DescribeTextTranslationExample/DescribeTextTranslation.cs +++ b/dotnetv3/Translate/DescribeTextTranslationExample/DescribeTextTranslation.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DescribeTextTranslationExample { diff --git a/dotnetv3/Translate/ListTranslationJobsExample/ListTranslationJobs.cs b/dotnetv3/Translate/ListTranslationJobsExample/ListTranslationJobs.cs index d0bb9f6d892..45b2cb2015c 100644 --- a/dotnetv3/Translate/ListTranslationJobsExample/ListTranslationJobs.cs +++ b/dotnetv3/Translate/ListTranslationJobsExample/ListTranslationJobs.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace ListTranslationJobsExample { diff --git a/dotnetv3/Translate/StopTextTranslationJobExample/StopTextTranslationJob.cs b/dotnetv3/Translate/StopTextTranslationJobExample/StopTextTranslationJob.cs index 5755079dab9..5cdc52c1a54 100644 --- a/dotnetv3/Translate/StopTextTranslationJobExample/StopTextTranslationJob.cs +++ b/dotnetv3/Translate/StopTextTranslationJobExample/StopTextTranslationJob.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace StopTextTranslationJobExample { diff --git a/dotnetv3/Translate/TranslateTextExample/TranslateText.cs b/dotnetv3/Translate/TranslateTextExample/TranslateText.cs index 305202ed176..d543b61e018 100644 --- a/dotnetv3/Translate/TranslateTextExample/TranslateText.cs +++ b/dotnetv3/Translate/TranslateTextExample/TranslateText.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace TranslateTextExample { diff --git a/dotnetv3/cross-service/AuroraItemTracker/AuroraItemTracker/Program.cs b/dotnetv3/cross-service/AuroraItemTracker/AuroraItemTracker/Program.cs index eb2e68944c0..04f9e4e6bd0 100644 --- a/dotnetv3/cross-service/AuroraItemTracker/AuroraItemTracker/Program.cs +++ b/dotnetv3/cross-service/AuroraItemTracker/AuroraItemTracker/Program.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.RDSDataService; using Amazon.SimpleEmailV2; diff --git a/dotnetv3/cross-service/AuroraItemTracker/AuroraItemTracker/ReportRequest.cs b/dotnetv3/cross-service/AuroraItemTracker/AuroraItemTracker/ReportRequest.cs index 0317a9129cf..420d8eda26d 100644 --- a/dotnetv3/cross-service/AuroraItemTracker/AuroraItemTracker/ReportRequest.cs +++ b/dotnetv3/cross-service/AuroraItemTracker/AuroraItemTracker/ReportRequest.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace AuroraItemTracker; diff --git a/dotnetv3/cross-service/AuroraItemTracker/AuroraItemTracker/ReportService.cs b/dotnetv3/cross-service/AuroraItemTracker/AuroraItemTracker/ReportService.cs index be5d611535c..36cf781ecaa 100644 --- a/dotnetv3/cross-service/AuroraItemTracker/AuroraItemTracker/ReportService.cs +++ b/dotnetv3/cross-service/AuroraItemTracker/AuroraItemTracker/ReportService.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Globalization; using Amazon.SimpleEmailV2; diff --git a/dotnetv3/cross-service/AuroraItemTracker/AuroraItemTracker/WorkItem.cs b/dotnetv3/cross-service/AuroraItemTracker/AuroraItemTracker/WorkItem.cs index cea535796ea..3b009b3413f 100644 --- a/dotnetv3/cross-service/AuroraItemTracker/AuroraItemTracker/WorkItem.cs +++ b/dotnetv3/cross-service/AuroraItemTracker/AuroraItemTracker/WorkItem.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace AuroraItemTracker; diff --git a/dotnetv3/cross-service/AuroraItemTracker/AuroraItemTracker/WorkItemService.cs b/dotnetv3/cross-service/AuroraItemTracker/AuroraItemTracker/WorkItemService.cs index 282f59cbb7e..f5a6c936b28 100644 --- a/dotnetv3/cross-service/AuroraItemTracker/AuroraItemTracker/WorkItemService.cs +++ b/dotnetv3/cross-service/AuroraItemTracker/AuroraItemTracker/WorkItemService.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Net; using System.Text.Json; diff --git a/dotnetv3/cross-service/AuroraItemTracker/ItemTrackerTests/ReportServiceTests.cs b/dotnetv3/cross-service/AuroraItemTracker/ItemTrackerTests/ReportServiceTests.cs index a65dc0fe0c3..d4b8c2c179c 100644 --- a/dotnetv3/cross-service/AuroraItemTracker/ItemTrackerTests/ReportServiceTests.cs +++ b/dotnetv3/cross-service/AuroraItemTracker/ItemTrackerTests/ReportServiceTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Globalization; using Amazon.SimpleEmailV2; diff --git a/dotnetv3/cross-service/AuroraItemTracker/ItemTrackerTests/Usings.cs b/dotnetv3/cross-service/AuroraItemTracker/ItemTrackerTests/Usings.cs index 0979f98c637..ef5ce323ba9 100644 --- a/dotnetv3/cross-service/AuroraItemTracker/ItemTrackerTests/Usings.cs +++ b/dotnetv3/cross-service/AuroraItemTracker/ItemTrackerTests/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 global using Xunit; global using Xunit.Extensions.Ordering; diff --git a/dotnetv3/cross-service/AuroraItemTracker/ItemTrackerTests/WorkItemServiceTests.cs b/dotnetv3/cross-service/AuroraItemTracker/ItemTrackerTests/WorkItemServiceTests.cs index 4cef19fb651..14831f656ea 100644 --- a/dotnetv3/cross-service/AuroraItemTracker/ItemTrackerTests/WorkItemServiceTests.cs +++ b/dotnetv3/cross-service/AuroraItemTracker/ItemTrackerTests/WorkItemServiceTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Net; using Amazon.RDSDataService; diff --git a/dotnetv3/cross-service/DynamoDbItemTracker/DynamoDbItemTracker/Program.cs b/dotnetv3/cross-service/DynamoDbItemTracker/DynamoDbItemTracker/Program.cs index 0015a4e5064..dedbbade905 100644 --- a/dotnetv3/cross-service/DynamoDbItemTracker/DynamoDbItemTracker/Program.cs +++ b/dotnetv3/cross-service/DynamoDbItemTracker/DynamoDbItemTracker/Program.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DataModel; diff --git a/dotnetv3/cross-service/DynamoDbItemTracker/DynamoDbItemTracker/ReportRequest.cs b/dotnetv3/cross-service/DynamoDbItemTracker/DynamoDbItemTracker/ReportRequest.cs index aa5a4626ef9..ed1827e11f9 100644 --- a/dotnetv3/cross-service/DynamoDbItemTracker/DynamoDbItemTracker/ReportRequest.cs +++ b/dotnetv3/cross-service/DynamoDbItemTracker/DynamoDbItemTracker/ReportRequest.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DynamoDbItemTracker; diff --git a/dotnetv3/cross-service/DynamoDbItemTracker/DynamoDbItemTracker/ReportService.cs b/dotnetv3/cross-service/DynamoDbItemTracker/DynamoDbItemTracker/ReportService.cs index a77207bfb19..9feca0e3e68 100644 --- a/dotnetv3/cross-service/DynamoDbItemTracker/DynamoDbItemTracker/ReportService.cs +++ b/dotnetv3/cross-service/DynamoDbItemTracker/DynamoDbItemTracker/ReportService.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Globalization; using Amazon.SimpleEmailV2; diff --git a/dotnetv3/cross-service/DynamoDbItemTracker/DynamoDbItemTracker/WorkItem.cs b/dotnetv3/cross-service/DynamoDbItemTracker/DynamoDbItemTracker/WorkItem.cs index 2017b98d2b9..6589a6a9c80 100644 --- a/dotnetv3/cross-service/DynamoDbItemTracker/DynamoDbItemTracker/WorkItem.cs +++ b/dotnetv3/cross-service/DynamoDbItemTracker/DynamoDbItemTracker/WorkItem.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Text.Json.Serialization; using Amazon.DynamoDBv2.DataModel; diff --git a/dotnetv3/cross-service/DynamoDbItemTracker/DynamoDbItemTracker/WorkItemService.cs b/dotnetv3/cross-service/DynamoDbItemTracker/DynamoDbItemTracker/WorkItemService.cs index 3b5eb23116c..076217e07a7 100644 --- a/dotnetv3/cross-service/DynamoDbItemTracker/DynamoDbItemTracker/WorkItemService.cs +++ b/dotnetv3/cross-service/DynamoDbItemTracker/DynamoDbItemTracker/WorkItemService.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.DynamoDBv2.DataModel; using Amazon.DynamoDBv2.DocumentModel; diff --git a/dotnetv3/cross-service/DynamoDbItemTracker/ItemTrackerTests/ReportServiceTests.cs b/dotnetv3/cross-service/DynamoDbItemTracker/ItemTrackerTests/ReportServiceTests.cs index f7b596f7c3d..106284107f1 100644 --- a/dotnetv3/cross-service/DynamoDbItemTracker/ItemTrackerTests/ReportServiceTests.cs +++ b/dotnetv3/cross-service/DynamoDbItemTracker/ItemTrackerTests/ReportServiceTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Globalization; using Amazon.SimpleEmailV2; diff --git a/dotnetv3/cross-service/DynamoDbItemTracker/ItemTrackerTests/Usings.cs b/dotnetv3/cross-service/DynamoDbItemTracker/ItemTrackerTests/Usings.cs index 0979f98c637..ef5ce323ba9 100644 --- a/dotnetv3/cross-service/DynamoDbItemTracker/ItemTrackerTests/Usings.cs +++ b/dotnetv3/cross-service/DynamoDbItemTracker/ItemTrackerTests/Usings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 global using Xunit; global using Xunit.Extensions.Ordering; diff --git a/dotnetv3/cross-service/DynamoDbItemTracker/ItemTrackerTests/WorkItemServiceTests.cs b/dotnetv3/cross-service/DynamoDbItemTracker/ItemTrackerTests/WorkItemServiceTests.cs index 21d2e7937b7..3d9f839f107 100644 --- a/dotnetv3/cross-service/DynamoDbItemTracker/ItemTrackerTests/WorkItemServiceTests.cs +++ b/dotnetv3/cross-service/DynamoDbItemTracker/ItemTrackerTests/WorkItemServiceTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DataModel; diff --git a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaAnalyzeSentiment/AnalyzeSentimentFunction.cs b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaAnalyzeSentiment/AnalyzeSentimentFunction.cs index e80b999ae5c..a01f52a26ea 100644 --- a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaAnalyzeSentiment/AnalyzeSentimentFunction.cs +++ b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaAnalyzeSentiment/AnalyzeSentimentFunction.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.Comprehend; using Amazon.Lambda.Core; diff --git a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaExtractText/ExtractTextFunction.cs b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaExtractText/ExtractTextFunction.cs index 98cfe084832..3cdee0e886a 100644 --- a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaExtractText/ExtractTextFunction.cs +++ b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaExtractText/ExtractTextFunction.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.Lambda.Core; using Amazon.Textract; @@ -40,7 +40,7 @@ public ExtractTextFunction(IAmazonTextract textractClient) } /// - /// This method is called for every Lambda invocation. This method takes in an S3 event object and can be used + /// This method is called for every Lambda invocation. This method takes in an S3 event object and can be used /// to respond to S3 notifications. /// /// The CloudWatch S3 Event. diff --git a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/AudioSourceDestinationDetails.cs b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/AudioSourceDestinationDetails.cs index 221ea6aad71..3485ab9fd76 100644 --- a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/AudioSourceDestinationDetails.cs +++ b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/AudioSourceDestinationDetails.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 namespace FsaServices.Models; diff --git a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/CardObjectCreated.cs b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/CardObjectCreated.cs index f427ed6ec98..32b926c3621 100644 --- a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/CardObjectCreated.cs +++ b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/CardObjectCreated.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 namespace FsaServices.Models; diff --git a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/SentimentDetails.cs b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/SentimentDetails.cs index 79d4420ac9d..438525df36d 100644 --- a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/SentimentDetails.cs +++ b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/SentimentDetails.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 namespace FsaServices.Models; diff --git a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/SourceTextDetails.cs b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/SourceTextDetails.cs index 59f62507c57..14aeebcd155 100644 --- a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/SourceTextDetails.cs +++ b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/SourceTextDetails.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 namespace FsaServices.Models; diff --git a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/TextWithSourceLanguage.cs b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/TextWithSourceLanguage.cs index 471dfa2fb19..eead840259a 100644 --- a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/TextWithSourceLanguage.cs +++ b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/TextWithSourceLanguage.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 namespace FsaServices.Models; diff --git a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/TranslatedTextDetails.cs b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/TranslatedTextDetails.cs index 0c4c0edde5b..a5899fb13fe 100644 --- a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/TranslatedTextDetails.cs +++ b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Models/TranslatedTextDetails.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 namespace FsaServices.Models; diff --git a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Services/ExtractionService.cs b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Services/ExtractionService.cs index 089d63cfd7a..a8186cb6b04 100644 --- a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Services/ExtractionService.cs +++ b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Services/ExtractionService.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon.Textract; using Amazon.Textract.Model; diff --git a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Services/SentimentService.cs b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Services/SentimentService.cs index 9d2737bd74f..39269b05761 100644 --- a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Services/SentimentService.cs +++ b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Services/SentimentService.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon.Comprehend; using Amazon.Comprehend.Model; diff --git a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Services/SynthesizeService.cs b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Services/SynthesizeService.cs index e91a17f886a..091322612b7 100644 --- a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Services/SynthesizeService.cs +++ b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Services/SynthesizeService.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon.Polly; using Amazon.Polly.Model; diff --git a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Services/TranslationService.cs b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Services/TranslationService.cs index e5b1338a305..022901956e3 100644 --- a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Services/TranslationService.cs +++ b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServices/Services/TranslationService.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon.Translate; using Amazon.Translate.Model; diff --git a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServicesTest/ExtractionServiceTests.cs b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServicesTest/ExtractionServiceTests.cs index d01b3c10f11..8cf73875c25 100644 --- a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServicesTest/ExtractionServiceTests.cs +++ b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServicesTest/ExtractionServiceTests.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon.Textract; using Amazon.Textract.Model; diff --git a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServicesTest/SentimentServiceTests.cs b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServicesTest/SentimentServiceTests.cs index faabcb241b6..95457575a2b 100644 --- a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServicesTest/SentimentServiceTests.cs +++ b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServicesTest/SentimentServiceTests.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon.Comprehend; using Amazon.Comprehend.Model; diff --git a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServicesTest/SynthesizeServiceTests.cs b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServicesTest/SynthesizeServiceTests.cs index d96f3ae9867..8e4ad6dfad0 100644 --- a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServicesTest/SynthesizeServiceTests.cs +++ b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServicesTest/SynthesizeServiceTests.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon.Polly; using Amazon.Polly.Model; diff --git a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServicesTest/TranslationServiceTests.cs b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServicesTest/TranslationServiceTests.cs index cc3378899a9..088724e6200 100644 --- a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServicesTest/TranslationServiceTests.cs +++ b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServicesTest/TranslationServiceTests.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon.Translate; using Amazon.Translate.Model; diff --git a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServicesTest/Usings.cs b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServicesTest/Usings.cs index 92fe41799a7..24f9d54e547 100644 --- a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServicesTest/Usings.cs +++ b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaServicesTest/Usings.cs @@ -1,4 +1,4 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Xunit; \ No newline at end of file diff --git a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaSynthesizeAudio/SynthesizeAudioFunction.cs b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaSynthesizeAudio/SynthesizeAudioFunction.cs index 0256f173458..5f4c5b1a30b 100644 --- a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaSynthesizeAudio/SynthesizeAudioFunction.cs +++ b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaSynthesizeAudio/SynthesizeAudioFunction.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.Lambda.Core; using Amazon.Polly; diff --git a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaTranslateText/TranslateTextFunction.cs b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaTranslateText/TranslateTextFunction.cs index 0221e7cf4d9..1a7a997c6f6 100644 --- a/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaTranslateText/TranslateTextFunction.cs +++ b/dotnetv3/cross-service/FeedbackSentimentAnalyzer/FsaTranslateText/TranslateTextFunction.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.Lambda.Core; using Amazon.Translate; diff --git a/dotnetv3/cross-service/PhotoAnalyzerApp/PhotoAnalyzerApp/Controllers/AWSService.cs b/dotnetv3/cross-service/PhotoAnalyzerApp/PhotoAnalyzerApp/Controllers/AWSService.cs index 7a44f9d1028..ec7471f372b 100644 --- a/dotnetv3/cross-service/PhotoAnalyzerApp/PhotoAnalyzerApp/Controllers/AWSService.cs +++ b/dotnetv3/cross-service/PhotoAnalyzerApp/PhotoAnalyzerApp/Controllers/AWSService.cs @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Threading.Tasks; @@ -34,11 +36,11 @@ public async void SendMessage(string text, string toAddress) var sub = new Content { Data = "Amazon Rekognition Report" - }; - + }; + var body = new Body { - Text = content + Text = content }; var message = new Message @@ -62,9 +64,9 @@ public async void SendMessage(string text, string toAddress) { Console.WriteLine(ex.Message); } - } - - // Uses the Amazon Rekognition service to detect labels within an image. + } + + // Uses the Amazon Rekognition service to detect labels within an image. public async Task> DetectLabels(string bucketName, string photo) { var rekognitionClient = new AmazonRekognitionClient(RegionEndpoint.USWest2); @@ -102,8 +104,8 @@ public async Task> DetectLabels(string bucketName, string photo) catch (Exception ex) { Console.WriteLine(ex.Message); - } - + } + return null; } @@ -121,8 +123,8 @@ public async Task> ListBucketNames(string bucketName) ListObjectsResponse response = await s3Client.ListObjectsAsync(listRequest); obList = response.S3Objects; - foreach (var myobj in obList) - obName.Add(myobj.Key); + foreach (var myobj in obList) + obName.Add(myobj.Key); return obName; } @@ -140,8 +142,8 @@ public async Task ListBucketObjects(string bucketName) ListObjectsResponse response = await s3Client.ListObjectsAsync(listRequest); obList = response.S3Objects; - BucketItem myItem; - + BucketItem myItem; + foreach (var myobj in obList) { myItem = new BucketItem(); @@ -198,10 +200,10 @@ public string GenerateXMLFromList(List> obList) XmlNode subsNode = doc.CreateElement("Items"); doc.AppendChild(subsNode); - // Iterate through the outer list. + // Iterate through the outer list. foreach (var listItem in obList) - { - // Iterate through the collection of WorkItem objects. + { + // Iterate through the collection of WorkItem objects. foreach (WorkItem item in listItem) { XmlNode subNode = doc.CreateElement("Item"); @@ -219,8 +221,8 @@ public string GenerateXMLFromList(List> obList) size.AppendChild(doc.CreateTextNode(item.Name)); subNode.AppendChild(size); } - } - + } + return doc.OuterXml; } } diff --git a/dotnetv3/cross-service/PhotoAnalyzerApp/PhotoAnalyzerApp/Controllers/BucketItem.cs b/dotnetv3/cross-service/PhotoAnalyzerApp/PhotoAnalyzerApp/Controllers/BucketItem.cs index 20a2a59785e..c7e36120670 100644 --- a/dotnetv3/cross-service/PhotoAnalyzerApp/PhotoAnalyzerApp/Controllers/BucketItem.cs +++ b/dotnetv3/cross-service/PhotoAnalyzerApp/PhotoAnalyzerApp/Controllers/BucketItem.cs @@ -1,14 +1,16 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace PhotoAnalyzerApp.Controllers -{ - public class BucketItem - { - public string Key { get; set; } - public string Owner { get; set; } - public string Size { get; set; } - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace PhotoAnalyzerApp.Controllers +{ + public class BucketItem + { + public string Key { get; set; } + public string Owner { get; set; } + public string Size { get; set; } + } +} diff --git a/dotnetv3/cross-service/PhotoAnalyzerApp/PhotoAnalyzerApp/Controllers/HomeController.cs b/dotnetv3/cross-service/PhotoAnalyzerApp/PhotoAnalyzerApp/Controllers/HomeController.cs index 409119445c1..5d7aaea1b45 100644 --- a/dotnetv3/cross-service/PhotoAnalyzerApp/PhotoAnalyzerApp/Controllers/HomeController.cs +++ b/dotnetv3/cross-service/PhotoAnalyzerApp/PhotoAnalyzerApp/Controllers/HomeController.cs @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; diff --git a/dotnetv3/cross-service/PhotoAnalyzerApp/PhotoAnalyzerApp/Controllers/WorkItem.cs b/dotnetv3/cross-service/PhotoAnalyzerApp/PhotoAnalyzerApp/Controllers/WorkItem.cs index 821b9a6e570..e69de29bb2d 100644 --- a/dotnetv3/cross-service/PhotoAnalyzerApp/PhotoAnalyzerApp/Controllers/WorkItem.cs +++ b/dotnetv3/cross-service/PhotoAnalyzerApp/PhotoAnalyzerApp/Controllers/WorkItem.cs @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace PhotoAnalyzerApp.Controllers -{ - public class WorkItem - { - public string Key { get; set; } - public string Name { get; set; } - public string Confidence { get; set; } - } -} diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamApi/Controllers/ApiController.cs b/dotnetv3/cross-service/PhotoAssetManager/PamApi/Controllers/ApiController.cs index 1b01141e479..1d50a0fd193 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamApi/Controllers/ApiController.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamApi/Controllers/ApiController.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using AWS.Lambda.Powertools.Logging; using Microsoft.AspNetCore.Mvc; diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamApi/DetectLabelsFunction.cs b/dotnetv3/cross-service/PhotoAssetManager/PamApi/DetectLabelsFunction.cs index cf4ddb7d972..f80681923c2 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamApi/DetectLabelsFunction.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamApi/DetectLabelsFunction.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon; using Amazon.DynamoDBv2; diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamApi/DownloadFunction.cs b/dotnetv3/cross-service/PhotoAssetManager/PamApi/DownloadFunction.cs index 926d2e41511..2adc94958cc 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamApi/DownloadFunction.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamApi/DownloadFunction.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon; using Amazon.DynamoDBv2; diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamApi/LambdaEntryPoint.cs b/dotnetv3/cross-service/PhotoAssetManager/PamApi/LambdaEntryPoint.cs index 7a97a490d92..9876c1e717e 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamApi/LambdaEntryPoint.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamApi/LambdaEntryPoint.cs @@ -1,12 +1,12 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace PamApi; /// -/// This class extends from APIGatewayProxyFunction which contains the method FunctionHandlerAsync which is the +/// This class extends from APIGatewayProxyFunction which contains the method FunctionHandlerAsync which is the /// actual AWS Lambda function entry point. The Lambda handler field should be set to -/// +/// /// PamApi::PamApi.LambdaEntryPoint::FunctionHandlerAsync /// public class LambdaEntryPoint : @@ -18,7 +18,7 @@ public class LambdaEntryPoint : // API Gateway HTTP API payload version 1.0 -> Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction // API Gateway HTTP API payload version 2.0 -> Amazon.Lambda.AspNetCoreServer.APIGatewayHttpApiV2ProxyFunction // Application Load Balancer -> Amazon.Lambda.AspNetCoreServer.ApplicationLoadBalancerFunction - // + // // Note: When using the AWS::Serverless::Function resource with an event type of "HttpApi" then payload version 2.0 // will be the default and you must make Amazon.Lambda.AspNetCoreServer.APIGatewayHttpApiV2ProxyFunction the base class. diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamApi/LocalEntryPoint.cs b/dotnetv3/cross-service/PhotoAssetManager/PamApi/LocalEntryPoint.cs index c7a7e9edc12..b1292d3014b 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamApi/LocalEntryPoint.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamApi/LocalEntryPoint.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace PamApi; diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamApi/Startup.cs b/dotnetv3/cross-service/PhotoAssetManager/PamApi/Startup.cs index ad61a4ee4fb..68aa369493a 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamApi/Startup.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamApi/Startup.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon; using Amazon.DynamoDBv2; diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamApiAnnotations/DetectLabelsFunction.cs b/dotnetv3/cross-service/PhotoAssetManager/PamApiAnnotations/DetectLabelsFunction.cs index 65ea97a92d0..e381892aff6 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamApiAnnotations/DetectLabelsFunction.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamApiAnnotations/DetectLabelsFunction.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon; using Amazon.DynamoDBv2; diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamApiAnnotations/DownloadFunction.cs b/dotnetv3/cross-service/PhotoAssetManager/PamApiAnnotations/DownloadFunction.cs index 4d8f49010ac..c1806f4edcc 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamApiAnnotations/DownloadFunction.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamApiAnnotations/DownloadFunction.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon; using Amazon.DynamoDBv2; diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamApiAnnotations/Functions.cs b/dotnetv3/cross-service/PhotoAssetManager/PamApiAnnotations/Functions.cs index 9a848224de4..4766c999ea9 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamApiAnnotations/Functions.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamApiAnnotations/Functions.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System.Net; using System.Text.Json; @@ -15,7 +15,7 @@ namespace PamApiAnnotations { /// - /// A collection of sample AWS Lambda functions that provide a REST API using Lambda annotations for the Photo Analyzer example. + /// A collection of sample AWS Lambda functions that provide a REST API using Lambda annotations for the Photo Analyzer example. /// public class Functions { diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamApiAnnotations/Startup.cs b/dotnetv3/cross-service/PhotoAssetManager/PamApiAnnotations/Startup.cs index 6e46246835b..6e61e3e911d 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamApiAnnotations/Startup.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamApiAnnotations/Startup.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon; using Amazon.DynamoDBv2; @@ -21,7 +21,7 @@ public Startup() } /// - /// Services for AWS Lambda functions can be registered in the services dependency injection container in this method. + /// Services for AWS Lambda functions can be registered in the services dependency injection container in this method. /// /// The services can be injected into the Lambda function through the containing type's constructor or as a /// parameter in the Lambda function using the FromService attribute. Services injected for the constructor have diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamServices.Test/ImageServiceTests.cs b/dotnetv3/cross-service/PhotoAssetManager/PamServices.Test/ImageServiceTests.cs index 11081850bf1..d40798690ea 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamServices.Test/ImageServiceTests.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamServices.Test/ImageServiceTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.Rekognition; using Amazon.Rekognition.Model; diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamServices.Test/LabelServiceTests.cs b/dotnetv3/cross-service/PhotoAssetManager/PamServices.Test/LabelServiceTests.cs index bbcb538a437..069b7dfe168 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamServices.Test/LabelServiceTests.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamServices.Test/LabelServiceTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.DynamoDBv2.DataModel; using Amazon.DynamoDBv2.DocumentModel; diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamServices.Test/NotificationServiceTests.cs b/dotnetv3/cross-service/PhotoAssetManager/PamServices.Test/NotificationServiceTests.cs index 72c4aabbfdb..21a21374070 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamServices.Test/NotificationServiceTests.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamServices.Test/NotificationServiceTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamServices.Test/StorageServiceTests.cs b/dotnetv3/cross-service/PhotoAssetManager/PamServices.Test/StorageServiceTests.cs index 2c9f0015a40..c24393fe802 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamServices.Test/StorageServiceTests.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamServices.Test/StorageServiceTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Text; using Amazon.S3; diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamServices.Test/Usings.cs b/dotnetv3/cross-service/PhotoAssetManager/PamServices.Test/Usings.cs index 92fe41799a7..24f9d54e547 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamServices.Test/Usings.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamServices.Test/Usings.cs @@ -1,4 +1,4 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Xunit; \ No newline at end of file diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamServices/DownloadRequest.cs b/dotnetv3/cross-service/PhotoAssetManager/PamServices/DownloadRequest.cs index 268a85be756..982e46b6e44 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamServices/DownloadRequest.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamServices/DownloadRequest.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace PamApi; diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamServices/ImageService.cs b/dotnetv3/cross-service/PhotoAssetManager/PamServices/ImageService.cs index 4d2de8310aa..94bffd8361f 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamServices/ImageService.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamServices/ImageService.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.Rekognition; using Amazon.Rekognition.Model; diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamServices/Label.cs b/dotnetv3/cross-service/PhotoAssetManager/PamServices/Label.cs index 65f767e5782..77d4dfd23c0 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamServices/Label.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamServices/Label.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.DynamoDBv2.DataModel; diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamServices/LabelService.cs b/dotnetv3/cross-service/PhotoAssetManager/PamServices/LabelService.cs index 07eff8419b5..177e7e7bb47 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamServices/LabelService.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamServices/LabelService.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.DynamoDBv2.DataModel; using Amazon.DynamoDBv2.DocumentModel; diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamServices/LabelsResponse.cs b/dotnetv3/cross-service/PhotoAssetManager/PamServices/LabelsResponse.cs index c9f7586e16b..48e328bf4b1 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamServices/LabelsResponse.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamServices/LabelsResponse.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace PamServices; diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamServices/NotificationService.cs b/dotnetv3/cross-service/PhotoAssetManager/PamServices/NotificationService.cs index 01c8eb17e62..48630a86cbb 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamServices/NotificationService.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamServices/NotificationService.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamServices/StorageService.cs b/dotnetv3/cross-service/PhotoAssetManager/PamServices/StorageService.cs index 5ec56e1253a..a70ac1266a9 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamServices/StorageService.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamServices/StorageService.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.IO.Compression; using Amazon.S3; diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamServices/UploadRequest.cs b/dotnetv3/cross-service/PhotoAssetManager/PamServices/UploadRequest.cs index 14b8c2b0643..1dbe835f51b 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamServices/UploadRequest.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamServices/UploadRequest.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace PamServices; diff --git a/dotnetv3/cross-service/PhotoAssetManager/PamServices/UploadResponse.cs b/dotnetv3/cross-service/PhotoAssetManager/PamServices/UploadResponse.cs index 2ae814bddd3..9b4a0216a20 100644 --- a/dotnetv3/cross-service/PhotoAssetManager/PamServices/UploadResponse.cs +++ b/dotnetv3/cross-service/PhotoAssetManager/PamServices/UploadResponse.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace PamServices; diff --git a/dotnetv3/cross-service/ResilientService/AutoScalerActions/AutoScalerWrapper.cs b/dotnetv3/cross-service/ResilientService/AutoScalerActions/AutoScalerWrapper.cs index 7e2ca3e55a2..3c6de99ff98 100644 --- a/dotnetv3/cross-service/ResilientService/AutoScalerActions/AutoScalerWrapper.cs +++ b/dotnetv3/cross-service/ResilientService/AutoScalerActions/AutoScalerWrapper.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon.AutoScaling; using Amazon.AutoScaling.Model; @@ -770,7 +770,7 @@ await _amazonEc2.AuthorizeSecurityGroupIngressAsync( // snippet-start:[ResilientService.dotnetv3.AutoScaling.AttachLoadBalancer] /// /// Attaches an Elastic Load Balancing (ELB) target group to this EC2 Auto Scaling group. - /// The + /// The /// /// The name of the Auto Scaling group. /// The Arn for the target group. diff --git a/dotnetv3/cross-service/ResilientService/ElasticLoadBalancerActions/ElasticLoadBalancerWrapper.cs b/dotnetv3/cross-service/ResilientService/ElasticLoadBalancerActions/ElasticLoadBalancerWrapper.cs index f2fb7109127..f1c8d73651b 100644 --- a/dotnetv3/cross-service/ResilientService/ElasticLoadBalancerActions/ElasticLoadBalancerWrapper.cs +++ b/dotnetv3/cross-service/ResilientService/ElasticLoadBalancerActions/ElasticLoadBalancerWrapper.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon.ElasticLoadBalancingV2; using Amazon.ElasticLoadBalancingV2.Model; diff --git a/dotnetv3/cross-service/ResilientService/ParameterActions/SMParameterWrapper.cs b/dotnetv3/cross-service/ResilientService/ParameterActions/SMParameterWrapper.cs index 5aae24a4616..b6215cf5ede 100644 --- a/dotnetv3/cross-service/ResilientService/ParameterActions/SMParameterWrapper.cs +++ b/dotnetv3/cross-service/ResilientService/ParameterActions/SMParameterWrapper.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon.SimpleSystemsManagement; using Amazon.SimpleSystemsManagement.Model; diff --git a/dotnetv3/cross-service/ResilientService/RecommendationService/RecommendationModel.cs b/dotnetv3/cross-service/ResilientService/RecommendationService/RecommendationModel.cs index 00d4cd46bc0..3ad0495915a 100644 --- a/dotnetv3/cross-service/ResilientService/RecommendationService/RecommendationModel.cs +++ b/dotnetv3/cross-service/ResilientService/RecommendationService/RecommendationModel.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon.DynamoDBv2.DataModel; diff --git a/dotnetv3/cross-service/ResilientService/RecommendationService/Recommendations.cs b/dotnetv3/cross-service/ResilientService/RecommendationService/Recommendations.cs index 734a61cd41e..c977d6b5ea8 100644 --- a/dotnetv3/cross-service/ResilientService/RecommendationService/Recommendations.cs +++ b/dotnetv3/cross-service/ResilientService/RecommendationService/Recommendations.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System.Text.Json; using Amazon.DynamoDBv2; diff --git a/dotnetv3/cross-service/ResilientService/ResilientServiceWorkflow/ResilientServiceWorkflow.cs b/dotnetv3/cross-service/ResilientService/ResilientServiceWorkflow/ResilientServiceWorkflow.cs index bfa6cc218c7..22cfceef73e 100644 --- a/dotnetv3/cross-service/ResilientService/ResilientServiceWorkflow/ResilientServiceWorkflow.cs +++ b/dotnetv3/cross-service/ResilientService/ResilientServiceWorkflow/ResilientServiceWorkflow.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using System.Text.Json; using Amazon.AutoScaling; diff --git a/dotnetv3/cross-service/ResilientService/Tests/ResilientServiceTests.cs b/dotnetv3/cross-service/ResilientService/Tests/ResilientServiceTests.cs index 2fab59e139d..8b55af69c54 100644 --- a/dotnetv3/cross-service/ResilientService/Tests/ResilientServiceTests.cs +++ b/dotnetv3/cross-service/ResilientService/Tests/ResilientServiceTests.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 using Amazon.AutoScaling; using Amazon.DynamoDBv2; diff --git a/dotnetv3/cross-service/ResilientService/Tests/Usings.cs b/dotnetv3/cross-service/ResilientService/Tests/Usings.cs index 158ebd88747..ef5ce323ba9 100644 --- a/dotnetv3/cross-service/ResilientService/Tests/Usings.cs +++ b/dotnetv3/cross-service/ResilientService/Tests/Usings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Xunit; global using Xunit.Extensions.Ordering; diff --git a/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Controllers/HomeController.cs b/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Controllers/HomeController.cs index ff582dd6575..ea62bf357cd 100644 --- a/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Controllers/HomeController.cs +++ b/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Controllers/HomeController.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace SNSExample.Controllers { diff --git a/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Controllers/SnsService.cs b/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Controllers/SnsService.cs index 3733f863f5c..d11bbfd3508 100644 --- a/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Controllers/SnsService.cs +++ b/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Controllers/SnsService.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace SubscribePublishTranslate.Controllers { diff --git a/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Models/ErrorViewModel.cs b/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Models/ErrorViewModel.cs index 25a340b0985..6516c9be6cb 100644 --- a/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Models/ErrorViewModel.cs +++ b/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Models/ErrorViewModel.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace SNSExample.Models { diff --git a/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Program.cs b/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Program.cs index b303c80e19d..58e09c9a062 100644 --- a/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Program.cs +++ b/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Program.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace SNSExample { diff --git a/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Startup.cs b/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Startup.cs index f628b8f778d..72f88e3c20d 100644 --- a/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Startup.cs +++ b/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Startup.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace SNSExample { diff --git a/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Views/Shared/_Layout.cshtml b/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Views/Shared/_Layout.cshtml index 3d79b8ecc13..424f8a1791b 100644 --- a/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Views/Shared/_Layout.cshtml +++ b/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/Views/Shared/_Layout.cshtml @@ -1,6 +1,6 @@  @@ -42,7 +42,7 @@ SPDX-License-Identifier: Apache-2.0
- © 2021 - Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 - Privacy + © 2021 - Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 - Privacy
diff --git a/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/wwwroot/js/site.js b/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/wwwroot/js/site.js index b2685426ef9..9a9f447cf75 100644 --- a/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/wwwroot/js/site.js +++ b/dotnetv3/cross-service/SubscribePublishTranslate/SubscribePublishTranslate/wwwroot/js/site.js @@ -1,108 +1,105 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 $(function () { - $("#SendButton").click(function ($e) { - - var body = $('#body').val(); - var lang = $('#lang option:selected').text(); - if (body == '') { - alert("Please enter text"); - return; - } - - $.ajax('home/PublishMessage', { - type: 'POST', - data: 'lang=' + lang + '&body=' + body, - success: function (data, status, xhr) { + $("#SendButton").click(function ($e) { + var body = $("#body").val(); + var lang = $("#lang option:selected").text(); + if (body == "") { + alert("Please enter text"); + return; + } - alert(data) - $('#body').val(""); - }, - error: function (jqXhr, textStatus, errorMessage) { - $('p').append('Error' + errorMessage); - } - }); + $.ajax("home/PublishMessage", { + type: "POST", + data: "lang=" + lang + "&body=" + body, + success: function (data, status, xhr) { + alert(data); + $("#body").val(""); + }, + error: function (jqXhr, textStatus, errorMessage) { + $("p").append("Error" + errorMessage); + }, }); + }); }); function subEmail() { - var mail = $('#inputEmail1').val(); - var result = validate(mail) - if (result == false) { - alert(mail + " is not valid. Please specify a valid email."); - return; - } - - $.ajax('home/AddEmailSub', { - type: 'POST', - data: 'email=' + mail, - success: function (data, status, xhr) { - alert("Subscription validation is " + data) - }, - error: function (jqXhr, textStatus, errorMessage) { - $('p').append('Error' + errorMessage); - } - }); + var mail = $("#inputEmail1").val(); + var result = validate(mail); + if (result == false) { + alert(mail + " is not valid. Please specify a valid email."); + return; + } + + $.ajax("home/AddEmailSub", { + type: "POST", + data: "email=" + mail, + success: function (data, status, xhr) { + alert("Subscription validation is " + data); + }, + error: function (jqXhr, textStatus, errorMessage) { + $("p").append("Error" + errorMessage); + }, + }); } function delSub(event) { - var mail = $('#inputEmail1').val(); - var result = validate(mail) - - if (result == false) { - alert(mail + " is not valid. Please specify a valid email"); - return; - } - - $.ajax('home/RemoveEmailSub', { - type: 'POST', // http GET method - data: 'email=' + mail, - success: function (data, status, xhr) { - - alert(data); - }, - error: function (jqXhr, textStatus, errorMessage) { - $('p').append('Error' + errorMessage); - } - }); + var mail = $("#inputEmail1").val(); + var result = validate(mail); + + if (result == false) { + alert(mail + " is not valid. Please specify a valid email"); + return; + } + + $.ajax("home/RemoveEmailSub", { + type: "POST", // http GET method + data: "email=" + mail, + success: function (data, status, xhr) { + alert(data); + }, + error: function (jqXhr, textStatus, errorMessage) { + $("p").append("Error" + errorMessage); + }, + }); } function subscribe() { - - $.ajax({ - url: 'home/GetAjaxValue', - success: function (data, status, xhr) { - - $('.modal-body').empty(); - var xml = data; - $(xml).find('Sub').each(function () { - - var $field = $(this); - var email = $field.find('email').text(); - - // Append this data to the main list. - $('.modal-body').append("

" + email + "

"); - }); - $("#myModal").modal(); - }, - error: function (jqXhr, textStatus, errorMessage) { - $('p').append('Error' + errorMessage); - } - }); + $.ajax({ + url: "home/GetAjaxValue", + success: function (data, status, xhr) { + $(".modal-body").empty(); + var xml = data; + $(xml) + .find("Sub") + .each(function () { + var $field = $(this); + var email = $field.find("email").text(); + + // Append this data to the main list. + $(".modal-body").append("

" + email + "

"); + }); + $("#myModal").modal(); + }, + error: function (jqXhr, textStatus, errorMessage) { + $("p").append("Error" + errorMessage); + }, + }); } function validateEmail(email) { - const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; - return re.test(email); + const re = + /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; + return re.test(email); } function validate(email) { - const $result = $("#result"); + const $result = $("#result"); - if (validateEmail(email)) { - return true; - } else { - return false; - } -} \ No newline at end of file + if (validateEmail(email)) { + return true; + } else { + return false; + } +} diff --git a/dotnetv3/cross-service/TopicsAndQueues/Actions/SNSActions/HelloSNS.cs b/dotnetv3/cross-service/TopicsAndQueues/Actions/SNSActions/HelloSNS.cs index 9003041613b..913312827f3 100644 --- a/dotnetv3/cross-service/TopicsAndQueues/Actions/SNSActions/HelloSNS.cs +++ b/dotnetv3/cross-service/TopicsAndQueues/Actions/SNSActions/HelloSNS.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[TopicsAndQueues.dotnetv3.HelloSNS] diff --git a/dotnetv3/cross-service/TopicsAndQueues/Actions/SNSActions/SNSWrapper.cs b/dotnetv3/cross-service/TopicsAndQueues/Actions/SNSActions/SNSWrapper.cs index 67bd383a741..e9494dc4544 100644 --- a/dotnetv3/cross-service/TopicsAndQueues/Actions/SNSActions/SNSWrapper.cs +++ b/dotnetv3/cross-service/TopicsAndQueues/Actions/SNSActions/SNSWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Net; using Amazon.SimpleNotificationService; diff --git a/dotnetv3/cross-service/TopicsAndQueues/Actions/SQSActions/HelloSQS.cs b/dotnetv3/cross-service/TopicsAndQueues/Actions/SQSActions/HelloSQS.cs index 2b2337eff5f..c97e39a96d5 100644 --- a/dotnetv3/cross-service/TopicsAndQueues/Actions/SQSActions/HelloSQS.cs +++ b/dotnetv3/cross-service/TopicsAndQueues/Actions/SQSActions/HelloSQS.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[TopicsAndQueues.dotnetv3.HelloSQS] diff --git a/dotnetv3/cross-service/TopicsAndQueues/Actions/SQSActions/SQSWrapper.cs b/dotnetv3/cross-service/TopicsAndQueues/Actions/SQSActions/SQSWrapper.cs index cb76a0008d4..c032d980d46 100644 --- a/dotnetv3/cross-service/TopicsAndQueues/Actions/SQSActions/SQSWrapper.cs +++ b/dotnetv3/cross-service/TopicsAndQueues/Actions/SQSActions/SQSWrapper.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Net; using Amazon.SQS; diff --git a/dotnetv3/cross-service/TopicsAndQueues/Scenarios/TopicsAndQueuesScenario/TopicsAndQueues.cs b/dotnetv3/cross-service/TopicsAndQueues/Scenarios/TopicsAndQueuesScenario/TopicsAndQueues.cs index a9090a5bba0..f587a5d341d 100644 --- a/dotnetv3/cross-service/TopicsAndQueues/Scenarios/TopicsAndQueuesScenario/TopicsAndQueues.cs +++ b/dotnetv3/cross-service/TopicsAndQueues/Scenarios/TopicsAndQueuesScenario/TopicsAndQueues.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Text.Json; diff --git a/dotnetv3/cross-service/TopicsAndQueues/Tests/TopicsAndQueuesTests/TopicsAndQueuesTests.cs b/dotnetv3/cross-service/TopicsAndQueues/Tests/TopicsAndQueuesTests/TopicsAndQueuesTests.cs index 5be0d126881..3c18f0bee41 100644 --- a/dotnetv3/cross-service/TopicsAndQueues/Tests/TopicsAndQueuesTests/TopicsAndQueuesTests.cs +++ b/dotnetv3/cross-service/TopicsAndQueues/Tests/TopicsAndQueuesTests/TopicsAndQueuesTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.SimpleNotificationService; using Amazon.SQS; diff --git a/dotnetv3/cross-service/TopicsAndQueues/Tests/TopicsAndQueuesTests/Usings.cs b/dotnetv3/cross-service/TopicsAndQueues/Tests/TopicsAndQueuesTests/Usings.cs index 158ebd88747..ef5ce323ba9 100644 --- a/dotnetv3/cross-service/TopicsAndQueues/Tests/TopicsAndQueuesTests/Usings.cs +++ b/dotnetv3/cross-service/TopicsAndQueues/Tests/TopicsAndQueuesTests/Usings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Xunit; global using Xunit.Extensions.Ordering; diff --git a/dotnetv3/dynamodb/CreateTablesLoadDataExample/CreateTablesLoadDataExample/CreateTablesLoadData.cs b/dotnetv3/dynamodb/CreateTablesLoadDataExample/CreateTablesLoadDataExample/CreateTablesLoadData.cs index 18739cbcc7a..4c822237176 100644 --- a/dotnetv3/dynamodb/CreateTablesLoadDataExample/CreateTablesLoadDataExample/CreateTablesLoadData.cs +++ b/dotnetv3/dynamodb/CreateTablesLoadDataExample/CreateTablesLoadDataExample/CreateTablesLoadData.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace CreateTablesLoadDataExample { diff --git a/dotnetv3/dynamodb/high-level-api/HighLevelBatchWriteItemExample/HighLevelBatchWriteItemExample/Book.cs b/dotnetv3/dynamodb/high-level-api/HighLevelBatchWriteItemExample/HighLevelBatchWriteItemExample/Book.cs index e352c5176b1..2332456f742 100644 --- a/dotnetv3/dynamodb/high-level-api/HighLevelBatchWriteItemExample/HighLevelBatchWriteItemExample/Book.cs +++ b/dotnetv3/dynamodb/high-level-api/HighLevelBatchWriteItemExample/HighLevelBatchWriteItemExample/Book.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace HighLevelBatchWriteItemExample { diff --git a/dotnetv3/dynamodb/high-level-api/HighLevelBatchWriteItemExample/HighLevelBatchWriteItemExample/Forum.cs b/dotnetv3/dynamodb/high-level-api/HighLevelBatchWriteItemExample/HighLevelBatchWriteItemExample/Forum.cs index 5977c3be771..9402010ab74 100644 --- a/dotnetv3/dynamodb/high-level-api/HighLevelBatchWriteItemExample/HighLevelBatchWriteItemExample/Forum.cs +++ b/dotnetv3/dynamodb/high-level-api/HighLevelBatchWriteItemExample/HighLevelBatchWriteItemExample/Forum.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace HighLevelBatchWriteItemExample { diff --git a/dotnetv3/dynamodb/high-level-api/HighLevelBatchWriteItemExample/HighLevelBatchWriteItemExample/HighLevelBatchWriteItem.cs b/dotnetv3/dynamodb/high-level-api/HighLevelBatchWriteItemExample/HighLevelBatchWriteItemExample/HighLevelBatchWriteItem.cs index cdea93072e8..4ab37a2dc16 100644 --- a/dotnetv3/dynamodb/high-level-api/HighLevelBatchWriteItemExample/HighLevelBatchWriteItemExample/HighLevelBatchWriteItem.cs +++ b/dotnetv3/dynamodb/high-level-api/HighLevelBatchWriteItemExample/HighLevelBatchWriteItemExample/HighLevelBatchWriteItem.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace HighLevelBatchWriteItemExample { diff --git a/dotnetv3/dynamodb/high-level-api/HighLevelBatchWriteItemExample/HighLevelBatchWriteItemExample/Reply.cs b/dotnetv3/dynamodb/high-level-api/HighLevelBatchWriteItemExample/HighLevelBatchWriteItemExample/Reply.cs index e3eb55b140c..46e7bd8ec43 100644 --- a/dotnetv3/dynamodb/high-level-api/HighLevelBatchWriteItemExample/HighLevelBatchWriteItemExample/Reply.cs +++ b/dotnetv3/dynamodb/high-level-api/HighLevelBatchWriteItemExample/HighLevelBatchWriteItemExample/Reply.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace HighLevelBatchWriteItemExample { diff --git a/dotnetv3/dynamodb/high-level-api/HighLevelBatchWriteItemExample/HighLevelBatchWriteItemExample/Thread.cs b/dotnetv3/dynamodb/high-level-api/HighLevelBatchWriteItemExample/HighLevelBatchWriteItemExample/Thread.cs index d10ef096a52..45b0b9c930f 100644 --- a/dotnetv3/dynamodb/high-level-api/HighLevelBatchWriteItemExample/HighLevelBatchWriteItemExample/Thread.cs +++ b/dotnetv3/dynamodb/high-level-api/HighLevelBatchWriteItemExample/HighLevelBatchWriteItemExample/Thread.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace HighLevelBatchWriteItemExample { diff --git a/dotnetv3/dynamodb/high-level-api/HighLevelItemCRUDExample/HighLevelItemCRUDExample/Book.cs b/dotnetv3/dynamodb/high-level-api/HighLevelItemCRUDExample/HighLevelItemCRUDExample/Book.cs index bc949f51bbc..04e540459df 100644 --- a/dotnetv3/dynamodb/high-level-api/HighLevelItemCRUDExample/HighLevelItemCRUDExample/Book.cs +++ b/dotnetv3/dynamodb/high-level-api/HighLevelItemCRUDExample/HighLevelItemCRUDExample/Book.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace HighLevelItemCRUDExample { diff --git a/dotnetv3/dynamodb/high-level-api/HighLevelItemCRUDExample/HighLevelItemCRUDExample/HighLevelItemCRUD.cs b/dotnetv3/dynamodb/high-level-api/HighLevelItemCRUDExample/HighLevelItemCRUDExample/HighLevelItemCRUD.cs index c4b170dbe96..08cc7332ebe 100644 --- a/dotnetv3/dynamodb/high-level-api/HighLevelItemCRUDExample/HighLevelItemCRUDExample/HighLevelItemCRUD.cs +++ b/dotnetv3/dynamodb/high-level-api/HighLevelItemCRUDExample/HighLevelItemCRUDExample/HighLevelItemCRUD.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace HighLevelItemCRUDExample { diff --git a/dotnetv3/dynamodb/high-level-api/HighLevelMappingArbitraryDataExample/HighLevelMappingArbitraryDataExample/Book.cs b/dotnetv3/dynamodb/high-level-api/HighLevelMappingArbitraryDataExample/HighLevelMappingArbitraryDataExample/Book.cs index b82b246af93..58e24756443 100644 --- a/dotnetv3/dynamodb/high-level-api/HighLevelMappingArbitraryDataExample/HighLevelMappingArbitraryDataExample/Book.cs +++ b/dotnetv3/dynamodb/high-level-api/HighLevelMappingArbitraryDataExample/HighLevelMappingArbitraryDataExample/Book.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace HighLevelMappingArbitraryDataExample { diff --git a/dotnetv3/dynamodb/high-level-api/HighLevelMappingArbitraryDataExample/HighLevelMappingArbitraryDataExample/DimensionType.cs b/dotnetv3/dynamodb/high-level-api/HighLevelMappingArbitraryDataExample/HighLevelMappingArbitraryDataExample/DimensionType.cs index fa998f7d60e..626bc3ce924 100644 --- a/dotnetv3/dynamodb/high-level-api/HighLevelMappingArbitraryDataExample/HighLevelMappingArbitraryDataExample/DimensionType.cs +++ b/dotnetv3/dynamodb/high-level-api/HighLevelMappingArbitraryDataExample/HighLevelMappingArbitraryDataExample/DimensionType.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace HighLevelMappingArbitraryDataExample { diff --git a/dotnetv3/dynamodb/high-level-api/HighLevelMappingArbitraryDataExample/HighLevelMappingArbitraryDataExample/DimensionTypeConverter.cs b/dotnetv3/dynamodb/high-level-api/HighLevelMappingArbitraryDataExample/HighLevelMappingArbitraryDataExample/DimensionTypeConverter.cs index 9a14c8bc76b..37edc844481 100644 --- a/dotnetv3/dynamodb/high-level-api/HighLevelMappingArbitraryDataExample/HighLevelMappingArbitraryDataExample/DimensionTypeConverter.cs +++ b/dotnetv3/dynamodb/high-level-api/HighLevelMappingArbitraryDataExample/HighLevelMappingArbitraryDataExample/DimensionTypeConverter.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace HighLevelMappingArbitraryDataExample { diff --git a/dotnetv3/dynamodb/high-level-api/HighLevelMappingArbitraryDataExample/HighLevelMappingArbitraryDataExample/HighLevelMappingArbitraryData.cs b/dotnetv3/dynamodb/high-level-api/HighLevelMappingArbitraryDataExample/HighLevelMappingArbitraryDataExample/HighLevelMappingArbitraryData.cs index 9c9a329cf00..a85de1b04c5 100644 --- a/dotnetv3/dynamodb/high-level-api/HighLevelMappingArbitraryDataExample/HighLevelMappingArbitraryDataExample/HighLevelMappingArbitraryData.cs +++ b/dotnetv3/dynamodb/high-level-api/HighLevelMappingArbitraryDataExample/HighLevelMappingArbitraryDataExample/HighLevelMappingArbitraryData.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace HighLevelMappingArbitraryDataExample { diff --git a/dotnetv3/dynamodb/high-level-api/HighLevelQueryAndScanExample/HighLevelQueryAndScanExample/Book.cs b/dotnetv3/dynamodb/high-level-api/HighLevelQueryAndScanExample/HighLevelQueryAndScanExample/Book.cs index e7cb6dfed1e..43eb4004bd5 100644 --- a/dotnetv3/dynamodb/high-level-api/HighLevelQueryAndScanExample/HighLevelQueryAndScanExample/Book.cs +++ b/dotnetv3/dynamodb/high-level-api/HighLevelQueryAndScanExample/HighLevelQueryAndScanExample/Book.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace HighLevelQueryAndScanExample { diff --git a/dotnetv3/dynamodb/high-level-api/HighLevelQueryAndScanExample/HighLevelQueryAndScanExample/Forum.cs b/dotnetv3/dynamodb/high-level-api/HighLevelQueryAndScanExample/HighLevelQueryAndScanExample/Forum.cs index 81bc537f1db..3bd0d932c4f 100644 --- a/dotnetv3/dynamodb/high-level-api/HighLevelQueryAndScanExample/HighLevelQueryAndScanExample/Forum.cs +++ b/dotnetv3/dynamodb/high-level-api/HighLevelQueryAndScanExample/HighLevelQueryAndScanExample/Forum.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace HighLevelQueryAndScanExample { diff --git a/dotnetv3/dynamodb/high-level-api/HighLevelQueryAndScanExample/HighLevelQueryAndScanExample/HighLevelQueryAndScan.cs b/dotnetv3/dynamodb/high-level-api/HighLevelQueryAndScanExample/HighLevelQueryAndScanExample/HighLevelQueryAndScan.cs index 499f397ca10..f972a53bad5 100644 --- a/dotnetv3/dynamodb/high-level-api/HighLevelQueryAndScanExample/HighLevelQueryAndScanExample/HighLevelQueryAndScan.cs +++ b/dotnetv3/dynamodb/high-level-api/HighLevelQueryAndScanExample/HighLevelQueryAndScanExample/HighLevelQueryAndScan.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace HighLevelQueryAndScanExample { diff --git a/dotnetv3/dynamodb/high-level-api/HighLevelQueryAndScanExample/HighLevelQueryAndScanExample/Reply.cs b/dotnetv3/dynamodb/high-level-api/HighLevelQueryAndScanExample/HighLevelQueryAndScanExample/Reply.cs index 678ad70651d..771c4f446f7 100644 --- a/dotnetv3/dynamodb/high-level-api/HighLevelQueryAndScanExample/HighLevelQueryAndScanExample/Reply.cs +++ b/dotnetv3/dynamodb/high-level-api/HighLevelQueryAndScanExample/HighLevelQueryAndScanExample/Reply.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace HighLevelQueryAndScanExample { diff --git a/dotnetv3/dynamodb/high-level-api/HighLevelQueryAndScanExample/HighLevelQueryAndScanExample/Thread.cs b/dotnetv3/dynamodb/high-level-api/HighLevelQueryAndScanExample/HighLevelQueryAndScanExample/Thread.cs index aa54e597214..f9c02a4858b 100644 --- a/dotnetv3/dynamodb/high-level-api/HighLevelQueryAndScanExample/HighLevelQueryAndScanExample/Thread.cs +++ b/dotnetv3/dynamodb/high-level-api/HighLevelQueryAndScanExample/HighLevelQueryAndScanExample/Thread.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace HighLevelQueryAndScanExample { diff --git a/dotnetv3/dynamodb/low-level-api/LowLevelBatchGet/LowLevelBatchGet.cs b/dotnetv3/dynamodb/low-level-api/LowLevelBatchGet/LowLevelBatchGet.cs index a746124e8d8..a2280ac9ccd 100644 --- a/dotnetv3/dynamodb/low-level-api/LowLevelBatchGet/LowLevelBatchGet.cs +++ b/dotnetv3/dynamodb/low-level-api/LowLevelBatchGet/LowLevelBatchGet.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[dynamodb.dotnetv3.LowLevelBatchGetExample] using System; diff --git a/dotnetv3/dynamodb/low-level-api/LowLevelTableExample/LowLevelTableExample.cs b/dotnetv3/dynamodb/low-level-api/LowLevelTableExample/LowLevelTableExample.cs index 5f43a9ce959..39254ea9468 100644 --- a/dotnetv3/dynamodb/low-level-api/LowLevelTableExample/LowLevelTableExample.cs +++ b/dotnetv3/dynamodb/low-level-api/LowLevelTableExample/LowLevelTableExample.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[dynamodb.dotnetv3.LowLevelTableExample] using System; diff --git a/dotnetv3/dynamodb/mid-level-api/MidLevelBatchWriteItemExample/MidLevelBatchWriteItemExample/MidLevelBatchWriteItem.cs b/dotnetv3/dynamodb/mid-level-api/MidLevelBatchWriteItemExample/MidLevelBatchWriteItemExample/MidLevelBatchWriteItem.cs index 5c644e9476e..a411ad1bd97 100644 --- a/dotnetv3/dynamodb/mid-level-api/MidLevelBatchWriteItemExample/MidLevelBatchWriteItemExample/MidLevelBatchWriteItem.cs +++ b/dotnetv3/dynamodb/mid-level-api/MidLevelBatchWriteItemExample/MidLevelBatchWriteItemExample/MidLevelBatchWriteItem.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace MidLevelBatchWriteItemExample { diff --git a/dotnetv3/dynamodb/mid-level-api/MidLevelQueryAndScanExample/MidLevelQueryAndScanExample/MidLevelQueryAndScan.cs b/dotnetv3/dynamodb/mid-level-api/MidLevelQueryAndScanExample/MidLevelQueryAndScanExample/MidLevelQueryAndScan.cs index a2d18401ca9..9db097ab3a3 100644 --- a/dotnetv3/dynamodb/mid-level-api/MidLevelQueryAndScanExample/MidLevelQueryAndScanExample/MidLevelQueryAndScan.cs +++ b/dotnetv3/dynamodb/mid-level-api/MidLevelQueryAndScanExample/MidLevelQueryAndScanExample/MidLevelQueryAndScan.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace MidLevelQueryAndScanExample { diff --git a/dotnetv3/dynamodb/mid-level-api/MidLevelScanOnlyExample/MidLevelScanOnlyExample/MidLevelScanOnly.cs b/dotnetv3/dynamodb/mid-level-api/MidLevelScanOnlyExample/MidLevelScanOnlyExample/MidLevelScanOnly.cs index 12860e1b108..42a4a15750e 100644 --- a/dotnetv3/dynamodb/mid-level-api/MidLevelScanOnlyExample/MidLevelScanOnlyExample/MidLevelScanOnly.cs +++ b/dotnetv3/dynamodb/mid-level-api/MidLevelScanOnlyExample/MidLevelScanOnlyExample/MidLevelScanOnly.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace MidLevelScanOnlyExample { diff --git a/dotnetv3/dynamodb/mid-level-api/MidlevelItemCRUDExample/MidlevelItemCRUDExample/MidlevelItemCRUD.cs b/dotnetv3/dynamodb/mid-level-api/MidlevelItemCRUDExample/MidlevelItemCRUDExample/MidlevelItemCRUD.cs index 5522cb31afe..4a773916482 100644 --- a/dotnetv3/dynamodb/mid-level-api/MidlevelItemCRUDExample/MidlevelItemCRUDExample/MidlevelItemCRUD.cs +++ b/dotnetv3/dynamodb/mid-level-api/MidlevelItemCRUDExample/MidlevelItemCRUDExample/MidlevelItemCRUD.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace MidlevelItemCRUDExample { diff --git a/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Actions/DynamoDbMethods.cs b/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Actions/DynamoDbMethods.cs index a65bec9801c..99334150307 100644 --- a/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Actions/DynamoDbMethods.cs +++ b/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Actions/DynamoDbMethods.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using System.Text.Json; using Amazon.DynamoDBv2; diff --git a/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Actions/HelloDynamoDB.cs b/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Actions/HelloDynamoDB.cs index edbfd6c2c05..319a3b64fb9 100644 --- a/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Actions/HelloDynamoDB.cs +++ b/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Actions/HelloDynamoDB.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[DynamoDB.dotnetv3.HelloDynamoDB] diff --git a/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Actions/Movie.cs b/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Actions/Movie.cs index 0c6e7ee4050..ddab3216a51 100644 --- a/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Actions/Movie.cs +++ b/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Actions/Movie.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.DynamoDBv2.DataModel; diff --git a/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Actions/MovieInfo.cs b/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Actions/MovieInfo.cs index e41e5248085..208ca8aa793 100644 --- a/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Actions/MovieInfo.cs +++ b/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Actions/MovieInfo.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Amazon.DynamoDBv2.DataModel; diff --git a/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Basics_Scenario/DynamoDB_Basics.cs b/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Basics_Scenario/DynamoDB_Basics.cs index f4049c5215d..8d262becf21 100644 --- a/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Basics_Scenario/DynamoDB_Basics.cs +++ b/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Basics_Scenario/DynamoDB_Basics.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace DynamoDB_Basics_Scenario; diff --git a/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Basics_ScenarioTests/DynamoDbMethodsTests.cs b/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Basics_ScenarioTests/DynamoDbMethodsTests.cs index 30eab0477a6..b7a79b3e320 100644 --- a/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Basics_ScenarioTests/DynamoDbMethodsTests.cs +++ b/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Basics_ScenarioTests/DynamoDbMethodsTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using DynamoDB_Actions; diff --git a/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Basics_ScenarioTests/GlobalUsings.cs b/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Basics_ScenarioTests/GlobalUsings.cs index d1212b195db..516e4e07c08 100644 --- a/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Basics_ScenarioTests/GlobalUsings.cs +++ b/dotnetv3/dynamodb/scenarios/DynamoDB_Basics/DynamoDB_Basics_ScenarioTests/GlobalUsings.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 global using Amazon.DynamoDBv2; global using Xunit; diff --git a/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/DynamoDBMethods.cs b/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/DynamoDBMethods.cs index 15606d8e962..aeb7a4562e2 100644 --- a/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/DynamoDBMethods.cs +++ b/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/DynamoDBMethods.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace PartiQL_Basics_Scenario { diff --git a/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/GlobalUsings.cs b/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/GlobalUsings.cs index a34d8ab7376..615ec875d8a 100644 --- a/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/GlobalUsings.cs +++ b/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/GlobalUsings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Amazon.DynamoDBv2; global using Amazon.DynamoDBv2.Model; diff --git a/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/Movie.cs b/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/Movie.cs index 61f3323eb8f..26b49e051a2 100644 --- a/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/Movie.cs +++ b/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/Movie.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace PartiQL_Basics_Scenario { diff --git a/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/MovieInfo.cs b/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/MovieInfo.cs index e31f1fe9ce5..19a4f6ee3d2 100644 --- a/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/MovieInfo.cs +++ b/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/MovieInfo.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace PartiQL_Basics_Scenario { diff --git a/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/PartiQLBasics.cs b/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/PartiQLBasics.cs index e2450bd0595..c06c822ca2e 100644 --- a/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/PartiQLBasics.cs +++ b/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/PartiQLBasics.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[PartiQL.dotnetv3.PartiQLBasicsScenario] diff --git a/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/PartiQLMethods.cs b/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/PartiQLMethods.cs index 123c4b86880..544c1f00fa6 100644 --- a/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/PartiQLMethods.cs +++ b/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/PartiQLMethods.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[PartiQL.dotnetv3.PartiQLBasicsScenario-Complete] namespace PartiQL_Basics_Scenario diff --git a/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Tests/PartiQLMethodsTests.cs b/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Tests/PartiQLMethodsTests.cs index ccb75d5a97b..89867f3a8be 100644 --- a/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Tests/PartiQLMethodsTests.cs +++ b/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Tests/PartiQLMethodsTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace PartiQL_Basics_Tests { diff --git a/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Tests/PriorityOrderer.cs b/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Tests/PriorityOrderer.cs index 611889cce85..2fa395525dc 100644 --- a/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Tests/PriorityOrderer.cs +++ b/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Tests/PriorityOrderer.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Xunit.Abstractions; using Xunit.Sdk; diff --git a/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Tests/TestPriorityAttribute.cs b/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Tests/TestPriorityAttribute.cs index 9c1fc7ee0f6..d9c6672d206 100644 --- a/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Tests/TestPriorityAttribute.cs +++ b/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Tests/TestPriorityAttribute.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace PartiQL_Basics_Scenario_Tests { diff --git a/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Tests/Usings.cs b/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Tests/Usings.cs index 9c23415f7eb..cf67e8eb365 100644 --- a/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Tests/Usings.cs +++ b/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Tests/Usings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Amazon.DynamoDBv2; global using PartiQL_Basics_Scenario; diff --git a/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQLBatch_Tests/PartiQLBatchMethodsTests.cs b/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQLBatch_Tests/PartiQLBatchMethodsTests.cs index 06c86298b9e..f48414e816d 100644 --- a/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQLBatch_Tests/PartiQLBatchMethodsTests.cs +++ b/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQLBatch_Tests/PartiQLBatchMethodsTests.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace PartiQL_Batch_Scenario.Tests { diff --git a/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQLBatch_Tests/PriorityOrderer.cs b/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQLBatch_Tests/PriorityOrderer.cs index de8c273815d..8d1c4bbf439 100644 --- a/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQLBatch_Tests/PriorityOrderer.cs +++ b/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQLBatch_Tests/PriorityOrderer.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 using Xunit.Abstractions; using Xunit.Sdk; diff --git a/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQLBatch_Tests/TestPriorityAttribute.cs b/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQLBatch_Tests/TestPriorityAttribute.cs index 816f0047d20..3477ea5fc66 100644 --- a/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQLBatch_Tests/TestPriorityAttribute.cs +++ b/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQLBatch_Tests/TestPriorityAttribute.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace PartiQL_Batch_Scenario.Tests { diff --git a/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQLBatch_Tests/Usings.cs b/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQLBatch_Tests/Usings.cs index 92fe41799a7..24f9d54e547 100644 --- a/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQLBatch_Tests/Usings.cs +++ b/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQLBatch_Tests/Usings.cs @@ -1,4 +1,4 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Xunit; \ No newline at end of file diff --git a/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/DynamoDBMethods.cs b/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/DynamoDBMethods.cs index 1fd0d9eaa6d..f674bc0bc7a 100644 --- a/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/DynamoDBMethods.cs +++ b/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/DynamoDBMethods.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace PartiQL_Batch_Scenario { diff --git a/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/GlobalUsings.cs b/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/GlobalUsings.cs index 2271015ca24..fea9ce9b0b5 100644 --- a/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/GlobalUsings.cs +++ b/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/GlobalUsings.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 global using Amazon.DynamoDBv2; global using Amazon.DynamoDBv2.Model; diff --git a/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/Movie.cs b/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/Movie.cs index ccc849c83fb..406a5b80dde 100644 --- a/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/Movie.cs +++ b/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/Movie.cs @@ -1,5 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 namespace PartiQL_Batch_Scenario { diff --git a/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/MovieInfo.cs b/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/MovieInfo.cs index f7172e11502..5511f9e4c85 100644 --- a/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/MovieInfo.cs +++ b/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/MovieInfo.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace PartiQL_Batch_Scenario { diff --git a/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/PartiQLBatch.cs b/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/PartiQLBatch.cs index e861af9869e..46c7325d57b 100644 --- a/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/PartiQLBatch.cs +++ b/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/PartiQLBatch.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[PartiQL.dotnetv3.PartiQLBatchScenario] diff --git a/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/PartiQLBatchMethods.cs b/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/PartiQLBatchMethods.cs index 5a2205da13e..6468cb86b83 100644 --- a/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/PartiQLBatchMethods.cs +++ b/dotnetv3/dynamodb/scenarios/PartiQL_Batch_Scenario/PartiQL_Batch_Scenario/PartiQLBatchMethods.cs @@ -1,5 +1,5 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: Apache-2.0 namespace PartiQL_Batch_Scenario { diff --git a/go/cloudformation/CreateStack/CreateStack_test.go b/go/cloudformation/CreateStack/CreateStack_test.go index 1cc1c7e5f54..b01d39ed8cf 100644 --- a/go/cloudformation/CreateStack/CreateStack_test.go +++ b/go/cloudformation/CreateStack/CreateStack_test.go @@ -1,46 +1,47 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/cloudformation" - "github.com/aws/aws-sdk-go/service/cloudformation/cloudformationiface" + "github.com/aws/aws-sdk-go/service/cloudformation" + "github.com/aws/aws-sdk-go/service/cloudformation/cloudformationiface" ) // Define a mock struct to use in unit tests type mockCFNClient struct { - cloudformationiface.CloudFormationAPI + cloudformationiface.CloudFormationAPI } func (m *mockCFNClient) CreateStack(input *cloudformation.CreateStackInput) (*cloudformation.CreateStackOutput, error) { - // Check that required inputs exist - if input.StackName == nil || *input.StackName == "" || input.TemplateBody == nil || *input.TemplateBody == "" { - return nil, errors.New("CreateStackInput.StackName or CreateStackInput.TemplateBody is nil or an empty string") - } + // Check that required inputs exist + if input.StackName == nil || *input.StackName == "" || input.TemplateBody == nil || *input.TemplateBody == "" { + return nil, errors.New("CreateStackInput.StackName or CreateStackInput.TemplateBody is nil or an empty string") + } - resp := cloudformation.CreateStackOutput{} - return &resp, nil + resp := cloudformation.CreateStackOutput{} + return &resp, nil } func TestCreateStack(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - stackName := "test-stack" - templateBody := "{}" + // mock resource + stackName := "test-stack" + templateBody := "{}" - mockSvc := &mockCFNClient{} + mockSvc := &mockCFNClient{} - err := MakeStack(mockSvc, &stackName, &templateBody) - if err != nil { - t.Fatal(err) - } + err := MakeStack(mockSvc, &stackName, &templateBody) + if err != nil { + t.Fatal(err) + } - t.Log("Created stack " + stackName) + t.Log("Created stack " + stackName) } diff --git a/go/cloudformation/DeleteStack/DeleteStack_test.go b/go/cloudformation/DeleteStack/DeleteStack_test.go index 9bd305a31b2..cdae9d89093 100644 --- a/go/cloudformation/DeleteStack/DeleteStack_test.go +++ b/go/cloudformation/DeleteStack/DeleteStack_test.go @@ -1,45 +1,46 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/cloudformation" - "github.com/aws/aws-sdk-go/service/cloudformation/cloudformationiface" + "github.com/aws/aws-sdk-go/service/cloudformation" + "github.com/aws/aws-sdk-go/service/cloudformation/cloudformationiface" ) // Define a mock struct to use in unit tests type mockCFNClient struct { - cloudformationiface.CloudFormationAPI + cloudformationiface.CloudFormationAPI } func (m *mockCFNClient) DeleteStack(input *cloudformation.DeleteStackInput) (*cloudformation.DeleteStackOutput, error) { - // Check that required inputs exist - if input.StackName == nil || *input.StackName == "" { - return nil, errors.New("CreateStackInput.StackName is nil or an empty string") - } + // Check that required inputs exist + if input.StackName == nil || *input.StackName == "" { + return nil, errors.New("CreateStackInput.StackName is nil or an empty string") + } - resp := cloudformation.DeleteStackOutput{} - return &resp, nil + resp := cloudformation.DeleteStackOutput{} + return &resp, nil } func TestCreateStack(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - stackName := "test-stack" + // mock resource + stackName := "test-stack" - mockSvc := &mockCFNClient{} + mockSvc := &mockCFNClient{} - err := RemoveStack(mockSvc, &stackName) - if err != nil { - t.Fatal(err) - } + err := RemoveStack(mockSvc, &stackName) + if err != nil { + t.Fatal(err) + } - t.Log("Deleted stack " + stackName) + t.Log("Deleted stack " + stackName) } diff --git a/go/cloudformation/ListStacks/ListStacks_test.go b/go/cloudformation/ListStacks/ListStacks_test.go index 72c2def5992..97a03c0f5d4 100644 --- a/go/cloudformation/ListStacks/ListStacks_test.go +++ b/go/cloudformation/ListStacks/ListStacks_test.go @@ -1,28 +1,29 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "strconv" - "testing" - "time" + "strconv" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/aws/session" ) func TestListStacks(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - resp, err := GetStackSummaries(sess, "all") - if err != nil { - t.Fatal(err) - } + resp, err := GetStackSummaries(sess, "all") + if err != nil { + t.Fatal(err) + } - t.Log("Found " + strconv.Itoa(len(resp.StackSummaries)) + " stacks") + t.Log("Found " + strconv.Itoa(len(resp.StackSummaries)) + " stacks") } diff --git a/go/cloudtrail/cloudtrailOps.go b/go/cloudtrail/cloudtrailOps.go index 979232fe4e0..f8ac9571143 100644 --- a/go/cloudtrail/cloudtrailOps.go +++ b/go/cloudtrail/cloudtrailOps.go @@ -1,430 +1,456 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "fmt" - "os" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudtrail" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/sts" + "encoding/json" + "fmt" + "os" + "strings" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudtrail" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/sts" ) // ConfigureBucket configures a bucket to send event activity to AWS CloudTrail // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// trailName is the name of the trail -// bucketName is the name of the bucket +// +// sess is the current session, which provides configuration for the SDK's service clients +// trailName is the name of the trail +// bucketName is the name of the bucket +// // Output: -// If success, nil -// Otherwise, an error from the call to sts.GetCallerIdentity, json.Marshal, or s3.PutBucketPolicy +// +// If success, nil +// Otherwise, an error from the call to sts.GetCallerIdentity, json.Marshal, or s3.PutBucketPolicy +// // snippet-start:[cloudtrail.go.configure_trail] func ConfigureBucket(sess *session.Session, bucketName string) error { - stsSvc := sts.New(sess) - // snippet-start:[cloudtrail.go.configure_trail.policy] - input := &sts.GetCallerIdentityInput{} - - result, err := stsSvc.GetCallerIdentity(input) - if err != nil { - return err - } - - accountID := aws.StringValue(result.Account) - - // Create a policy so the bucket sends events to AWS CloudTrail - s3Policy := map[string]interface{}{ - "Version": "2012-10-17", - "Statement": []map[string]interface{}{ - { - "Sid": "AWSCloudTrailAclCheck20150319", - "Effect": "Allow", - "Principal": map[string]interface{}{ - "Service": "cloudtrail.amazonaws.com", - }, - "Action": "s3:GetBucketAcl", - "Resource": "arn:aws:s3:::" + bucketName, - }, - { - "Sid": "AWSCloudTrailWrite20150319", - "Effect": "Allow", - "Principal": map[string]interface{}{ - "Service": "cloudtrail.amazonaws.com", - }, - "Action": "s3:PutObject", - "Resource": "arn:aws:s3:::" + bucketName + "/AWSLogs/" + accountID + "/*", - "Condition": map[string]interface{}{ - "StringEquals": map[string]interface{}{ - "s3:x-amz-acl": "bucket-owner-full-control", - }, - }, - }, - }, - } - - policy, err := json.Marshal(s3Policy) - if err != nil { - return err - } - - // Create an S3 service - s3Svc := s3.New(sess) - - // Set the policy on the bucket - _, err = s3Svc.PutBucketPolicy(&s3.PutBucketPolicyInput{ - Bucket: aws.String(bucketName), - Policy: aws.String(string(policy)), - }) - if err != nil { - return err - } - // snippet-end:[cloudtrail.go.configure_trail.policy] - - return nil + stsSvc := sts.New(sess) + // snippet-start:[cloudtrail.go.configure_trail.policy] + input := &sts.GetCallerIdentityInput{} + + result, err := stsSvc.GetCallerIdentity(input) + if err != nil { + return err + } + + accountID := aws.StringValue(result.Account) + + // Create a policy so the bucket sends events to AWS CloudTrail + s3Policy := map[string]interface{}{ + "Version": "2012-10-17", + "Statement": []map[string]interface{}{ + { + "Sid": "AWSCloudTrailAclCheck20150319", + "Effect": "Allow", + "Principal": map[string]interface{}{ + "Service": "cloudtrail.amazonaws.com", + }, + "Action": "s3:GetBucketAcl", + "Resource": "arn:aws:s3:::" + bucketName, + }, + { + "Sid": "AWSCloudTrailWrite20150319", + "Effect": "Allow", + "Principal": map[string]interface{}{ + "Service": "cloudtrail.amazonaws.com", + }, + "Action": "s3:PutObject", + "Resource": "arn:aws:s3:::" + bucketName + "/AWSLogs/" + accountID + "/*", + "Condition": map[string]interface{}{ + "StringEquals": map[string]interface{}{ + "s3:x-amz-acl": "bucket-owner-full-control", + }, + }, + }, + }, + } + + policy, err := json.Marshal(s3Policy) + if err != nil { + return err + } + + // Create an S3 service + s3Svc := s3.New(sess) + + // Set the policy on the bucket + _, err = s3Svc.PutBucketPolicy(&s3.PutBucketPolicyInput{ + Bucket: aws.String(bucketName), + Policy: aws.String(string(policy)), + }) + if err != nil { + return err + } + // snippet-end:[cloudtrail.go.configure_trail.policy] + + return nil } + // snippet-end:[cloudtrail.go.configure_trail] // CreateTrail creates a trail to get event activity from a bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// trailName is the name of the trail -// bucketName is the name of the bucket +// +// sess is the current session, which provides configuration for the SDK's service clients +// trailName is the name of the trail +// bucketName is the name of the bucket +// // Output: -// If success, nil -// Otherwise, an error from the call to sts.GetCallerIdentity, json.Marshal, or s3.PutBucketPolicy +// +// If success, nil +// Otherwise, an error from the call to sts.GetCallerIdentity, json.Marshal, or s3.PutBucketPolicy +// // snippet-start:[cloudtrail.go.create_trail] func CreateTrail(sess *session.Session, trailName string, bucketName string) error { - // snippet-start:[cloudtrailops.go.create_trail.create] - svc := cloudtrail.New(sess) + // snippet-start:[cloudtrailops.go.create_trail.create] + svc := cloudtrail.New(sess) - ctInput := &cloudtrail.CreateTrailInput{ - Name: aws.String(trailName), - S3BucketName: aws.String(bucketName), - } + ctInput := &cloudtrail.CreateTrailInput{ + Name: aws.String(trailName), + S3BucketName: aws.String(bucketName), + } - _, err := svc.CreateTrail(ctInput) - if err != nil { - return err - } + _, err := svc.CreateTrail(ctInput) + if err != nil { + return err + } - return nil - // snippet-end:[cloudtrailops.go.create_trail.create] + return nil + // snippet-end:[cloudtrailops.go.create_trail.create] } + // snippet-end:[cloudtrail.go.create_trail] // GetTrails gets a list of trails // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients +// +// sess is the current session, which provides configuration for the SDK's service clients +// // Output: -// If success, a list of Trail objects and nil -// Otherwise, a nil object and an error from a call to DescribeTrails +// +// If success, a list of Trail objects and nil +// Otherwise, a nil object and an error from a call to DescribeTrails func GetTrails(sess *session.Session) ([]*cloudtrail.Trail, error) { - var trails []*cloudtrail.Trail - svc := cloudtrail.New(sess) + var trails []*cloudtrail.Trail + svc := cloudtrail.New(sess) - resp, err := svc.DescribeTrails(nil) - if err != nil { - return trails, err - } + resp, err := svc.DescribeTrails(nil) + if err != nil { + return trails, err + } - return resp.TrailList, nil + return resp.TrailList, nil } // listTrails displays a list of your trails // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients +// +// sess is the current session, which provides configuration for the SDK's service clients +// // Output: -// If success, nil -// Otherwise, an error returned by a call to DescribeTrails +// +// If success, nil +// Otherwise, an error returned by a call to DescribeTrails +// // snippet-start:[cloudtrail.go.list_trails] func listTrails(sess *session.Session) error { - svc := cloudtrail.New(sess) + svc := cloudtrail.New(sess) - resp, err := svc.DescribeTrails(nil) - if err != nil { - return err - } + resp, err := svc.DescribeTrails(nil) + if err != nil { + return err + } - fmt.Println("Found", len(resp.TrailList), "trail(s):") - fmt.Println("") + fmt.Println("Found", len(resp.TrailList), "trail(s):") + fmt.Println("") - for _, trail := range resp.TrailList { - fmt.Println("Trail name: " + *trail.Name) - fmt.Println("Bucket name: " + *trail.S3BucketName) - fmt.Println("") - } + for _, trail := range resp.TrailList { + fmt.Println("Trail name: " + *trail.Name) + fmt.Println("Bucket name: " + *trail.S3BucketName) + fmt.Println("") + } - return nil + return nil } + // snippet-end:[cloudtrail.go.list_trails] // DeleteTrail deletes a trail // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// trailName is the name of the trail +// +// sess is the current session, which provides configuration for the SDK's service clients +// trailName is the name of the trail +// // Output: -// If success, nil -// Otherwise, an error from a call to DeleteTrail +// +// If success, nil +// Otherwise, an error from a call to DeleteTrail +// // snippet-start:[cloudtrail.go.delete_trail] func DeleteTrail(sess *session.Session, trailName string) error { - svc := cloudtrail.New(sess) + svc := cloudtrail.New(sess) - input := &cloudtrail.DeleteTrailInput{ - Name: aws.String(trailName), - } + input := &cloudtrail.DeleteTrailInput{ + Name: aws.String(trailName), + } - _, err := svc.DeleteTrail(input) + _, err := svc.DeleteTrail(input) - return err + return err } + // snippet-end:[cloudtrail.go.delete_trail] // GetUser retrieves the name of the logged on user // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients +// +// sess is the current session, which provides configuration for the SDK's service clients +// // Output: -// If success, the user name and nil -// Otherwise, an empty string and an error from a call to GetCallerIdentity +// +// If success, the user name and nil +// Otherwise, an empty string and an error from a call to GetCallerIdentity func GetUser(sess *session.Session) (string, error) { - svc := sts.New(sess) - id, err := svc.GetCallerIdentity(nil) - if err != nil { - return "", err - } + svc := sts.New(sess) + id, err := svc.GetCallerIdentity(nil) + if err != nil { + return "", err + } - // arn:aws:iam::ACCOUNT-ID:user/USER - parts := strings.Split(*id.Arn, "/") - userName := parts[1] + // arn:aws:iam::ACCOUNT-ID:user/USER + parts := strings.Split(*id.Arn, "/") + userName := parts[1] - return userName, nil + return userName, nil } // GetTrailEvents gets the events for a trail // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// trailName is the name of the trail +// +// sess is the current session, which provides configuration for the SDK's service clients +// trailName is the name of the trail +// // Output: -// If success, a list of Event objects and nil -// Otherwise, a nil object and an error from a call to LookupEvents +// +// If success, a list of Event objects and nil +// Otherwise, a nil object and an error from a call to LookupEvents func GetTrailEvents(sess *session.Session, trailName string) ([]*cloudtrail.Event, error) { - var events []*cloudtrail.Event - svc := cloudtrail.New(sess) - input := &cloudtrail.LookupEventsInput{EndTime: aws.Time(time.Now())} + var events []*cloudtrail.Event + svc := cloudtrail.New(sess) + input := &cloudtrail.LookupEventsInput{EndTime: aws.Time(time.Now())} - resp, err := svc.LookupEvents(input) - if err != nil { - return events, err - } + resp, err := svc.LookupEvents(input) + if err != nil { + return events, err + } - return resp.Events, nil + return resp.Events, nil } // listTrailEvents lists the events for the user in a trail // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// trailName is the name of the trail -// userName is the name of the user +// +// sess is the current session, which provides configuration for the SDK's service clients +// trailName is the name of the trail +// userName is the name of the user +// // Output: -// If success, nil -// Otherwise, an error from a call to LookupEvents +// +// If success, nil +// Otherwise, an error from a call to LookupEvents +// // snippet-start:[cloudtrail.go.list_trail_events] func listTrailEvents(sess *session.Session, trailName string, userName string) error { - svc := cloudtrail.New(sess) - input := &cloudtrail.LookupEventsInput{EndTime: aws.Time(time.Now())} - - resp, err := svc.LookupEvents(input) - if err != nil { - return err - } - - fmt.Println("Events for the user " + userName + " in trail " + trailName + ":") - - for _, event := range resp.Events { - if userName == *event.Username { - fmt.Println("") - fmt.Println("Event:") - fmt.Println("") - fmt.Println("Name ", aws.StringValue(event.EventName)) - fmt.Println("ID: ", aws.StringValue(event.EventId)) - fmt.Println("Time: ", aws.TimeValue(event.EventTime)) - - fmt.Println("Resources:") - - for _, resource := range event.Resources { - fmt.Println(" Name:", aws.StringValue(resource.ResourceName)) - fmt.Println(" Type:", aws.StringValue(resource.ResourceType)) - } - } - } - - return nil + svc := cloudtrail.New(sess) + input := &cloudtrail.LookupEventsInput{EndTime: aws.Time(time.Now())} + + resp, err := svc.LookupEvents(input) + if err != nil { + return err + } + + fmt.Println("Events for the user " + userName + " in trail " + trailName + ":") + + for _, event := range resp.Events { + if userName == *event.Username { + fmt.Println("") + fmt.Println("Event:") + fmt.Println("") + fmt.Println("Name ", aws.StringValue(event.EventName)) + fmt.Println("ID: ", aws.StringValue(event.EventId)) + fmt.Println("Time: ", aws.TimeValue(event.EventTime)) + + fmt.Println("Resources:") + + for _, resource := range event.Resources { + fmt.Println(" Name:", aws.StringValue(resource.ResourceName)) + fmt.Println(" Type:", aws.StringValue(resource.ResourceType)) + } + } + } + + return nil } + // snippet-end:[cloudtrail.go.list_trail_events] // usage displays information on using this app // Inputs: -// none +// +// none +// // Output: -// none +// +// none func usage() { - fmt.Println("Usage:") - fmt.Println("") - fmt.Println(" go run sqsQueueOps.go OPERATION") - fmt.Println("") - fmt.Println("where OPERATION is one of:") - fmt.Println(" -l") - fmt.Println(" list your trails") - fmt.Println(" -c TRAIL-NAME BUCKET-NAME") - fmt.Println(" create trail TRAIL-NAME that gets events from bucket BUCKET-NAME") - fmt.Println(" -d TRAIL-NAME") - fmt.Println(" delete trail TRAIL-NAME") - fmt.Println(" -e USER-NAME TRAIL-NAME") - fmt.Println(" show events from the user USER-NAME for trail TRAIL-NAME") - fmt.Println(" -h") - fmt.Println(" print this message and quit") - fmt.Println("") + fmt.Println("Usage:") + fmt.Println("") + fmt.Println(" go run sqsQueueOps.go OPERATION") + fmt.Println("") + fmt.Println("where OPERATION is one of:") + fmt.Println(" -l") + fmt.Println(" list your trails") + fmt.Println(" -c TRAIL-NAME BUCKET-NAME") + fmt.Println(" create trail TRAIL-NAME that gets events from bucket BUCKET-NAME") + fmt.Println(" -d TRAIL-NAME") + fmt.Println(" delete trail TRAIL-NAME") + fmt.Println(" -e USER-NAME TRAIL-NAME") + fmt.Println(" show events from the user USER-NAME for trail TRAIL-NAME") + fmt.Println(" -h") + fmt.Println(" print this message and quit") + fmt.Println("") } func main() { - // Parse args ourselves so the user can request only one operation - op := "" - numOps := 0 // So we know when the user has requested more than one operation - length := len(os.Args) - i := 1 - trailName := "" - bucketName := "" - userName := "" - - for i < length { - switch os.Args[i] { - case "-h": - usage() - return - case "-c": - // -c TRAIL-NAME BUCKET-NAME - if length != 3 { - fmt.Println("You must supply a trail name and bucket name") - usage() - return - } - op = "create" - i++ - trailName = os.Args[i] - i++ - bucketName = os.Args[i] - numOps++ - - case "-d": - // -d TRAIL-NAME - op = "delete" - i++ - trailName = os.Args[i] - numOps++ - - case "-e": - // -e TRAIL-NAME - op = "events" - i++ - userName = os.Args[i] - i++ - trailName = os.Args[i] - numOps++ - - case "-l": - // -l - op = "list" - numOps++ - - default: - fmt.Println("Unrecognized option: " + os.Args[i]) - usage() - return - } - - i++ - } - - if numOps > 1 { - fmt.Println("You cannot request more than one operation") - usage() - return - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - switch op { - case "create": - if trailName == "" || bucketName == "" { - fmt.Println("You must supply a trail name and a bucket name") - usage() - return - } - - err := CreateTrail(sess, trailName, bucketName) - if err != nil { - fmt.Println("Got an error creating trail:") - fmt.Println(err) - return - } - - case "delete": - if trailName == "" { - fmt.Println("You must supply a trail name") - usage() - return - } - - err := DeleteTrail(sess, trailName) - if err != nil { - fmt.Println("Got an error deleting trail:") - fmt.Println(err) - return - } - - case "events": - if userName == "" || trailName == "" { - fmt.Println("You must supply a user name and trail name") - usage() - return - } - - err := listTrailEvents(sess, trailName, userName) - if err != nil { - fmt.Println("Got an error listing trail events:") - fmt.Println(err) - return - } - - case "list": - err := listTrails(sess) - if err != nil { - fmt.Println("Got an error listing trails:") - fmt.Println(err) - return - } - - default: - // This should never happen - fmt.Println("Unrecognized operation (typo?): " + op) - return - } + // Parse args ourselves so the user can request only one operation + op := "" + numOps := 0 // So we know when the user has requested more than one operation + length := len(os.Args) + i := 1 + trailName := "" + bucketName := "" + userName := "" + + for i < length { + switch os.Args[i] { + case "-h": + usage() + return + case "-c": + // -c TRAIL-NAME BUCKET-NAME + if length != 3 { + fmt.Println("You must supply a trail name and bucket name") + usage() + return + } + op = "create" + i++ + trailName = os.Args[i] + i++ + bucketName = os.Args[i] + numOps++ + + case "-d": + // -d TRAIL-NAME + op = "delete" + i++ + trailName = os.Args[i] + numOps++ + + case "-e": + // -e TRAIL-NAME + op = "events" + i++ + userName = os.Args[i] + i++ + trailName = os.Args[i] + numOps++ + + case "-l": + // -l + op = "list" + numOps++ + + default: + fmt.Println("Unrecognized option: " + os.Args[i]) + usage() + return + } + + i++ + } + + if numOps > 1 { + fmt.Println("You cannot request more than one operation") + usage() + return + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + switch op { + case "create": + if trailName == "" || bucketName == "" { + fmt.Println("You must supply a trail name and a bucket name") + usage() + return + } + + err := CreateTrail(sess, trailName, bucketName) + if err != nil { + fmt.Println("Got an error creating trail:") + fmt.Println(err) + return + } + + case "delete": + if trailName == "" { + fmt.Println("You must supply a trail name") + usage() + return + } + + err := DeleteTrail(sess, trailName) + if err != nil { + fmt.Println("Got an error deleting trail:") + fmt.Println(err) + return + } + + case "events": + if userName == "" || trailName == "" { + fmt.Println("You must supply a user name and trail name") + usage() + return + } + + err := listTrailEvents(sess, trailName, userName) + if err != nil { + fmt.Println("Got an error listing trail events:") + fmt.Println(err) + return + } + + case "list": + err := listTrails(sess) + if err != nil { + fmt.Println("Got an error listing trails:") + fmt.Println(err) + return + } + + default: + // This should never happen + fmt.Println("Unrecognized operation (typo?): " + op) + return + } } diff --git a/go/cloudtrail/cloudtrailOps_test.go b/go/cloudtrail/cloudtrailOps_test.go index 85037e81a1f..b8000487f47 100644 --- a/go/cloudtrail/cloudtrailOps_test.go +++ b/go/cloudtrail/cloudtrailOps_test.go @@ -1,40 +1,29 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main // snippet-start:[sqs.go.imports] import ( - "encoding/json" - "io/ioutil" - "strings" - "testing" + "encoding/json" + "io/ioutil" + "strings" + "testing" - "github.com/google/uuid" + "github.com/google/uuid" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" ) // snippet-end:[sqs.go.imports] // Config defines a set of configuration values type Config struct { - TrailName string `json:"TrailName"` - BucketName string `json:"BucketName"` + TrailName string `json:"TrailName"` + BucketName string `json:"BucketName"` } // ConfigFile defines the name of the file containing configuration values @@ -45,321 +34,324 @@ var GlobalConfig Config // PopulateConfiguration gets values from config.json and populates the configuration struct GlobalConfig // Inputs: -// none +// +// none +// // Output: -// If success, nil -// Otherwise, an error from reading or parsing the configuration file +// +// If success, nil +// Otherwise, an error from reading or parsing the configuration file func PopulateConfiguration() error { - // Get configuration from config.json + // Get configuration from config.json - // Get entire file as a JSON string - content, err := ioutil.ReadFile(ConfigFile) - if err != nil { - return err - } + // Get entire file as a JSON string + content, err := ioutil.ReadFile(ConfigFile) + if err != nil { + return err + } - // Convert []byte to string - text := string(content) + // Convert []byte to string + text := string(content) - // Marshall JSON string in text into global struct - err = json.Unmarshal([]byte(text), &GlobalConfig) - if err != nil { - return err - } + // Marshall JSON string in text into global struct + err = json.Unmarshal([]byte(text), &GlobalConfig) + if err != nil { + return err + } - return nil + return nil } func createBucket(sess *session.Session, bucketName string) error { - // Create the bucket - svc := s3.New(sess) - input := &s3.CreateBucketInput{ - Bucket: aws.String(bucketName), - } - _, err := svc.CreateBucket(input) - if err != nil { - return err - } - - // Wait until the bucket exists - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: aws.String(bucketName), - }) - if err != nil { - return err - } - - return nil + // Create the bucket + svc := s3.New(sess) + input := &s3.CreateBucketInput{ + Bucket: aws.String(bucketName), + } + _, err := svc.CreateBucket(input) + if err != nil { + return err + } + + // Wait until the bucket exists + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: aws.String(bucketName), + }) + if err != nil { + return err + } + + return nil } func addItemToBucket(sess *session.Session, bucketName string, objectName string) error { - svc := s3.New(sess) - - _, err := svc.PutObject(&s3.PutObjectInput{ - Body: strings.NewReader("Hello World!"), - Bucket: aws.String(bucketName), - Key: aws.String(objectName), - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.PutObject(&s3.PutObjectInput{ + Body: strings.NewReader("Hello World!"), + Bucket: aws.String(bucketName), + Key: aws.String(objectName), + }) + if err != nil { + return err + } + + return nil } func deleteItemFromBucket(sess *session.Session, bucketName string, objectName string) error { - svc := s3.New(sess) + svc := s3.New(sess) - _, err := svc.DeleteObject(&s3.DeleteObjectInput{ - Bucket: aws.String(bucketName), - Key: aws.String(objectName), - }) - if err != nil { - return err - } + _, err := svc.DeleteObject(&s3.DeleteObjectInput{ + Bucket: aws.String(bucketName), + Key: aws.String(objectName), + }) + if err != nil { + return err + } - return nil + return nil } func deleteBucket(sess *session.Session, bucketName string) error { - svc := s3.New(sess) - - // First delete any items in the bucket - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: aws.String(bucketName), - }) - - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - if err != nil { - return err - } - - _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: aws.String(bucketName), - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + // First delete any items in the bucket + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: aws.String(bucketName), + }) + + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + if err != nil { + return err + } + + _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: aws.String(bucketName), + }) + if err != nil { + return err + } + + return nil } func showEvents(t *testing.T, sess *session.Session, trailName string, userName string) error { - t.Log("Getting events for the user " + userName) - - events, err := GetTrailEvents(sess, trailName) - if err != nil { - t.Fatal(err) - } - - t.Log("Events for " + trailName + ":") - - for _, event := range events { - if nil == event.Username { - continue - } - - if userName == *event.Username { - t.Log("") - t.Log("Event:") - if nil != event.EventName { - t.Log("Name ", aws.StringValue(event.EventName)) - } - if nil != event.EventId { - t.Log("ID: ", aws.StringValue(event.EventId)) - } - if nil != event.EventTime { - t.Log("Time: ", aws.TimeValue(event.EventTime)) - } - - t.Log("Resources:") - - for _, resource := range event.Resources { - if nil != resource.ResourceName { - t.Log(" Name:", aws.StringValue(resource.ResourceName)) - } - if nil != resource.ResourceType { - t.Log(" Type:", aws.StringValue(resource.ResourceType)) - } - } - } - } - - return nil + t.Log("Getting events for the user " + userName) + + events, err := GetTrailEvents(sess, trailName) + if err != nil { + t.Fatal(err) + } + + t.Log("Events for " + trailName + ":") + + for _, event := range events { + if nil == event.Username { + continue + } + + if userName == *event.Username { + t.Log("") + t.Log("Event:") + if nil != event.EventName { + t.Log("Name ", aws.StringValue(event.EventName)) + } + if nil != event.EventId { + t.Log("ID: ", aws.StringValue(event.EventId)) + } + if nil != event.EventTime { + t.Log("Time: ", aws.TimeValue(event.EventTime)) + } + + t.Log("Resources:") + + for _, resource := range event.Resources { + if nil != resource.ResourceName { + t.Log(" Name:", aws.StringValue(resource.ResourceName)) + } + if nil != resource.ResourceType { + t.Log(" Type:", aws.StringValue(resource.ResourceType)) + } + } + } + } + + return nil } func showTrails(sess *session.Session, t *testing.T) error { - trails, err := GetTrails(sess) - if err != nil { - return err - } - - for _, trail := range trails { - t.Log("Trail name: " + *trail.Name) - t.Log("Bucket name: " + *trail.S3BucketName) - t.Log("") - } - - return nil + trails, err := GetTrails(sess) + if err != nil { + return err + } + + for _, trail := range trails { + t.Log("Trail name: " + *trail.Name) + t.Log("Bucket name: " + *trail.S3BucketName) + t.Log("") + } + + return nil } func logErrors(t *testing.T, dummy1 string, dummy2 string, bucketCreated bool, bucket string, trailCreated bool, trail string) { - if dummy1 != "" { - t.Log("You'll have to delete this bucket item yourself: " + dummy1) - } - if dummy2 != "" { - t.Log("You'll have to delete this bucket item yourself: " + dummy2) - } - if bucketCreated { - t.Log("You'll have to delete this bucket yourself: " + bucket) - } - if trailCreated { - t.Log("You'll have to delete this trail yourself: " + trail) - } + if dummy1 != "" { + t.Log("You'll have to delete this bucket item yourself: " + dummy1) + } + if dummy2 != "" { + t.Log("You'll have to delete this bucket item yourself: " + dummy2) + } + if bucketCreated { + t.Log("You'll have to delete this bucket yourself: " + bucket) + } + if trailCreated { + t.Log("You'll have to delete this trail yourself: " + trail) + } } func TestCloudTrailOps(t *testing.T) { - err := PopulateConfiguration() - if err != nil { - t.Fatal(err) - } - - bucketName := GlobalConfig.BucketName - bucketCreated := false - trailName := GlobalConfig.TrailName - trailCreated := false - dummy1 := "" - dummy2 := "" - - // snippet-start:[sqs.go.session] - // Create a session using credentials from ~/.aws/credentials - // and the Region from ~/.aws/config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[sqs.go.session] - - // Create a random, unique value - id := uuid.New() - - if bucketName == "" { - // Bucket names must be all lower-case, no underscores, dashes and numbers ok - bucketName = "mybucket-" + id.String() - - t.Log("Creating bucket " + bucketName) - err = createBucket(sess, bucketName) - if err != nil { - t.Fatal(err) - } - - bucketCreated = true - t.Log("Created bucket " + bucketName) - } else { - t.Log("Using existing bucket " + bucketName) - } - - err = ConfigureBucket(sess, bucketName) - if err != nil { - logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) - t.Fatal(err) - } - - if trailName == "" { - trailName = "MyTrail-" + id.String() - // Create a trail - t.Log("Creating trail " + trailName) - // CreateTrail(sess *session.Session, trailName string, bucketName string) error - err = CreateTrail(sess, trailName, bucketName) - if err != nil { - logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) - t.Fatal(err) - } - - trailCreated = true - t.Log("Created trail " + trailName) - } else { - t.Log("Using existing trail " + trailName) - } - - // Add a couple of dummy items to the bucket - dummy1 = "dummy1-" + id.String() - - err = addItemToBucket(sess, bucketName, dummy1) - if err != nil { - dummy1 = "" - logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) - t.Fatal(err) - } - - t.Log("Added " + dummy1 + " to bucket " + bucketName) - - dummy2 = "dummy2-" + id.String() - err = addItemToBucket(sess, bucketName, dummy2) - if err != nil { - dummy2 = "" - logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) - t.Fatal(err) - } - - t.Log("Added " + dummy2 + " to bucket " + bucketName) - - err = showTrails(sess, t) - if err != nil { - logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) - t.Fatal(err) - } - - // Get the user - user, err := GetUser(sess) - if err != nil { - logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) - t.Fatal(err) - } - - // List any events initiated by the user - err = showEvents(t, sess, trailName, user) - if err != nil { - logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) - t.Fatal(err) - } - - // Now delete the trail, if created - if trailCreated { - err = DeleteTrail(sess, trailName) - if err != nil { - logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) - t.Fatal(err) - } - - t.Log("Deleted trail " + trailName) - trailCreated = false - } - - // Delete dummy objects in bucket - err = deleteItemFromBucket(sess, bucketName, dummy1) - if err != nil { - logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) - t.Fatal(err) - } - - t.Log("Deleted " + dummy1 + " from bucket " + bucketName) - dummy1 = "" - - err = deleteItemFromBucket(sess, bucketName, dummy2) - if err != nil { - logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) - t.Fatal(err) - } - - t.Log("Deleted " + dummy2 + " from bucket " + bucketName) - dummy2 = "" - - // Delete the bucket, if created - if bucketCreated { - err = deleteBucket(sess, bucketName) - if err != nil { - logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) - t.Fatal(err) - } - } + err := PopulateConfiguration() + if err != nil { + t.Fatal(err) + } + + bucketName := GlobalConfig.BucketName + bucketCreated := false + trailName := GlobalConfig.TrailName + trailCreated := false + dummy1 := "" + dummy2 := "" + + // snippet-start:[sqs.go.session] + // Create a session using credentials from ~/.aws/credentials + // and the Region from ~/.aws/config + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[sqs.go.session] + + // Create a random, unique value + id := uuid.New() + + if bucketName == "" { + // Bucket names must be all lower-case, no underscores, dashes and numbers ok + bucketName = "mybucket-" + id.String() + + t.Log("Creating bucket " + bucketName) + err = createBucket(sess, bucketName) + if err != nil { + t.Fatal(err) + } + + bucketCreated = true + t.Log("Created bucket " + bucketName) + } else { + t.Log("Using existing bucket " + bucketName) + } + + err = ConfigureBucket(sess, bucketName) + if err != nil { + logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) + t.Fatal(err) + } + + if trailName == "" { + trailName = "MyTrail-" + id.String() + // Create a trail + t.Log("Creating trail " + trailName) + // CreateTrail(sess *session.Session, trailName string, bucketName string) error + err = CreateTrail(sess, trailName, bucketName) + if err != nil { + logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) + t.Fatal(err) + } + + trailCreated = true + t.Log("Created trail " + trailName) + } else { + t.Log("Using existing trail " + trailName) + } + + // Add a couple of dummy items to the bucket + dummy1 = "dummy1-" + id.String() + + err = addItemToBucket(sess, bucketName, dummy1) + if err != nil { + dummy1 = "" + logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) + t.Fatal(err) + } + + t.Log("Added " + dummy1 + " to bucket " + bucketName) + + dummy2 = "dummy2-" + id.String() + err = addItemToBucket(sess, bucketName, dummy2) + if err != nil { + dummy2 = "" + logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) + t.Fatal(err) + } + + t.Log("Added " + dummy2 + " to bucket " + bucketName) + + err = showTrails(sess, t) + if err != nil { + logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) + t.Fatal(err) + } + + // Get the user + user, err := GetUser(sess) + if err != nil { + logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) + t.Fatal(err) + } + + // List any events initiated by the user + err = showEvents(t, sess, trailName, user) + if err != nil { + logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) + t.Fatal(err) + } + + // Now delete the trail, if created + if trailCreated { + err = DeleteTrail(sess, trailName) + if err != nil { + logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) + t.Fatal(err) + } + + t.Log("Deleted trail " + trailName) + trailCreated = false + } + + // Delete dummy objects in bucket + err = deleteItemFromBucket(sess, bucketName, dummy1) + if err != nil { + logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) + t.Fatal(err) + } + + t.Log("Deleted " + dummy1 + " from bucket " + bucketName) + dummy1 = "" + + err = deleteItemFromBucket(sess, bucketName, dummy2) + if err != nil { + logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) + t.Fatal(err) + } + + t.Log("Deleted " + dummy2 + " from bucket " + bucketName) + dummy2 = "" + + // Delete the bucket, if created + if bucketCreated { + err = deleteBucket(sess, bucketName) + if err != nil { + logErrors(t, dummy1, dummy2, bucketCreated, bucketName, trailCreated, trailName) + t.Fatal(err) + } + } } diff --git a/go/cloudwatch/CreateCustomMetric/CreateCustomMetric.go b/go/cloudwatch/CreateCustomMetric/CreateCustomMetric.go index 5a0221df5b3..50ed3810be6 100644 --- a/go/cloudwatch/CreateCustomMetric/CreateCustomMetric.go +++ b/go/cloudwatch/CreateCustomMetric/CreateCustomMetric.go @@ -1,98 +1,92 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cloudwatch.go.create_custom_metric] package main // snippet-start:[cloudwatch.go.create_custom_metric.import] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatch" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatch" ) + // snippet-end:[cloudwatch.go.create_custom_metric.import] // CreateCustomMetric creates a new metric in a namespace // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// namespace is the metric namespace -// metricName is the name of the metric -// unit is what the value represents -// value is the value of the metric unit -// dimensionName is the name of the dimension -// dimensionValue is the value of the dimensionName +// +// sess is the current session, which provides configuration for the SDK's service clients +// namespace is the metric namespace +// metricName is the name of the metric +// unit is what the value represents +// value is the value of the metric unit +// dimensionName is the name of the dimension +// dimensionValue is the value of the dimensionName +// // Output: -// If success, nil -// Otherwise, an error from a call to PutMetricData +// +// If success, nil +// Otherwise, an error from a call to PutMetricData func CreateCustomMetric(sess *session.Session, namespace *string, metricName *string, unit *string, value *float64, dimensionName *string, dimensionValue *string) error { - // Create new Amazon CloudWatch client - // snippet-start:[cloudwatch.go.create_custom_metric.call] - svc := cloudwatch.New(sess) + // Create new Amazon CloudWatch client + // snippet-start:[cloudwatch.go.create_custom_metric.call] + svc := cloudwatch.New(sess) - _, err := svc.PutMetricData(&cloudwatch.PutMetricDataInput{ - Namespace: namespace, - MetricData: []*cloudwatch.MetricDatum{ - &cloudwatch.MetricDatum{ - MetricName: metricName, - Unit: unit, - Value: value, - Dimensions: []*cloudwatch.Dimension{ - &cloudwatch.Dimension{ - Name: dimensionName, - Value: dimensionValue, - }, - }, - }, - }, - }) - // snippet-end:[cloudwatch.go.create_custom_metric.call] - if err != nil { - return err - } + _, err := svc.PutMetricData(&cloudwatch.PutMetricDataInput{ + Namespace: namespace, + MetricData: []*cloudwatch.MetricDatum{ + &cloudwatch.MetricDatum{ + MetricName: metricName, + Unit: unit, + Value: value, + Dimensions: []*cloudwatch.Dimension{ + &cloudwatch.Dimension{ + Name: dimensionName, + Value: dimensionValue, + }, + }, + }, + }, + }) + // snippet-end:[cloudwatch.go.create_custom_metric.call] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[cloudwatch.go.create_custom_metric.args] - namespace := flag.String("n", "", "The namespace for the metric") - metricName := flag.String("m", "", "The name of the metric") - unit := flag.String("u", "", "The units for the metric") - value := flag.Float64("v", 0.0, "The value of the units") - dimensionName := flag.String("dn", "", "The name of the dimension") - dimensionValue := flag.String("dv", "", "The value of the dimension") - flag.Parse() + // snippet-start:[cloudwatch.go.create_custom_metric.args] + namespace := flag.String("n", "", "The namespace for the metric") + metricName := flag.String("m", "", "The name of the metric") + unit := flag.String("u", "", "The units for the metric") + value := flag.Float64("v", 0.0, "The value of the units") + dimensionName := flag.String("dn", "", "The name of the dimension") + dimensionValue := flag.String("dv", "", "The value of the dimension") + flag.Parse() + + if *namespace == "" || *metricName == "" || *unit == "" || *dimensionName == "" || *dimensionValue == "" { + fmt.Println("You must supply a namespace, metric name, value, dimension name, and dimension value") + return + } + // snippet-end:[cloudwatch.go.create_custom_metric.args] - if *namespace == "" || *metricName == "" ||*unit == "" || *dimensionName == "" || *dimensionValue == "" { - fmt.Println("You must supply a namespace, metric name, value, dimension name, and dimension value") - return - } - // snippet-end:[cloudwatch.go.create_custom_metric.args] + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + // snippet-start:[cloudwatch.go.create_custom_metric.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[cloudwatch.go.create_custom_metric.session] - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - // snippet-start:[cloudwatch.go.create_custom_metric.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[cloudwatch.go.create_custom_metric.session] - - err := CreateCustomMetric(sess, namespace, metricName, unit, value, dimensionName, dimensionValue) - if err != nil { - fmt.Println() - } + err := CreateCustomMetric(sess, namespace, metricName, unit, value, dimensionName, dimensionValue) + if err != nil { + fmt.Println() + } } + // snippet-end:[cloudwatch.go.create_custom_metric] diff --git a/go/cloudwatch/CreateCustomMetric/CreateCustomMetric_test.go b/go/cloudwatch/CreateCustomMetric/CreateCustomMetric_test.go index d9fd03dfaa3..34ca74752aa 100644 --- a/go/cloudwatch/CreateCustomMetric/CreateCustomMetric_test.go +++ b/go/cloudwatch/CreateCustomMetric/CreateCustomMetric_test.go @@ -1,39 +1,28 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "strconv" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatch" + "encoding/json" + "io/ioutil" + "strconv" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatch" ) type config struct { - Namespace string `json:"Namespace"` - Metrics []struct { - MetricName string `json:"MetricName"` - Unit string `json:"Unit"` - Value float64 `json:"Value"` - DimensionName string `json:"DimensionName"` - DimensionValue string `json:"DimensionValue"` - } `json:"Metrics"` + Namespace string `json:"Namespace"` + Metrics []struct { + MetricName string `json:"MetricName"` + Unit string `json:"Unit"` + Value float64 `json:"Value"` + DimensionName string `json:"DimensionName"` + DimensionValue string `json:"DimensionValue"` + } `json:"Metrics"` } var globalConfig config @@ -41,79 +30,79 @@ var globalConfig config var configFileName = "config.json" func populateConfig(t *testing.T) error { - // Get and store configuration values - // Get configuration from config.json + // Get and store configuration values + // Get configuration from config.json - // Get entire file as a JSON string - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + // Get entire file as a JSON string + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - // Convert []byte to string - text := string(content) + // Convert []byte to string + text := string(content) - // Marshall JSON string in text into global struct - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + // Marshall JSON string in text into global struct + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Namespace: " + globalConfig.Namespace) + t.Log("Namespace: " + globalConfig.Namespace) - return nil + return nil } func listMetrics(t *testing.T, sess *session.Session, namespace *string) error { - svc := cloudwatch.New(sess) + svc := cloudwatch.New(sess) - result, err := svc.ListMetrics(&cloudwatch.ListMetricsInput{ - Namespace: namespace, - }) - if err != nil { - return err - } + result, err := svc.ListMetrics(&cloudwatch.ListMetricsInput{ + Namespace: namespace, + }) + if err != nil { + return err + } - numMetrics := 0 + numMetrics := 0 - for _, m := range result.Metrics { - t.Log(" Metric Name: " + *m.MetricName) - numMetrics++ - } + for _, m := range result.Metrics { + t.Log(" Metric Name: " + *m.MetricName) + numMetrics++ + } - t.Log("Found " + strconv.Itoa(numMetrics) + " custom metrics in namespace " + *namespace) + t.Log("Found " + strconv.Itoa(numMetrics) + " custom metrics in namespace " + *namespace) - return nil + return nil } func TestCustomMetric(t *testing.T) { - // When the test started - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Started unit test at " + nowString) - - err := populateConfig(t) - if err != nil { - t.Fatal(err) - } - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - for _, m := range globalConfig.Metrics { - err := CreateCustomMetric(sess, &globalConfig.Namespace, &m.MetricName, &m.Unit, &m.Value, &m.DimensionName, &m.DimensionValue) - if err != nil { - t.Fatal(err) - } - } - - // Now list them out - err = listMetrics(t, sess, &globalConfig.Namespace) - if err != nil { - t.Fatal(err) - } + // When the test started + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Started unit test at " + nowString) + + err := populateConfig(t) + if err != nil { + t.Fatal(err) + } + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + for _, m := range globalConfig.Metrics { + err := CreateCustomMetric(sess, &globalConfig.Namespace, &m.MetricName, &m.Unit, &m.Value, &m.DimensionName, &m.DimensionValue) + if err != nil { + t.Fatal(err) + } + } + + // Now list them out + err = listMetrics(t, sess, &globalConfig.Namespace) + if err != nil { + t.Fatal(err) + } } diff --git a/go/cloudwatch/CreateRole/CreateRole.go b/go/cloudwatch/CreateRole/CreateRole.go index 580083379cc..7f4ba891ab3 100644 --- a/go/cloudwatch/CreateRole/CreateRole.go +++ b/go/cloudwatch/CreateRole/CreateRole.go @@ -1,46 +1,39 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cloudwatch.go.create_role] package main // snippet-start:[cloudwatch.go.create_role.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) + // snippet-end:[cloudwatch.go.create_role.imports] // CreateRole creates a role that grants permission to Amazon CloudWatch Events // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// role is the name of the role +// +// sess is the current session, which provides configuration for the SDK's service clients +// role is the name of the role +// // Output: -// If successful, a CreateRoleOutput and nil -// Otherwise, nil and the error from a call to CreateRole +// +// If successful, a CreateRoleOutput and nil +// Otherwise, nil and the error from a call to CreateRole func CreateRole(sess *session.Session, roleName *string, policyName *string) (*iam.CreateRoleOutput, error) { - // Create the service client - // snippet-start:[cloudwatch.go.create_role.client] - svc := iam.New(sess) - // snippet-end:[cloudwatch.go.create_role.client] - - // From: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/cw-example-sending-events.html - // snippet-start:[cloudwatch.go.create_role.role_policy] - rolePolicy := []byte(`{ + // Create the service client + // snippet-start:[cloudwatch.go.create_role.client] + svc := iam.New(sess) + // snippet-end:[cloudwatch.go.create_role.client] + + // From: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/cw-example-sending-events.html + // snippet-start:[cloudwatch.go.create_role.role_policy] + rolePolicy := []byte(`{ "Version": "2012-10-17", "Statement": [ { @@ -58,19 +51,19 @@ func CreateRole(sess *session.Session, roleName *string, policyName *string) (*i ] }`) - policy := string(rolePolicy[:]) + policy := string(rolePolicy[:]) - createPolicyResult, err := svc.CreatePolicy(&iam.CreatePolicyInput{ - PolicyDocument: &policy, - PolicyName: policyName, - }) - // snippet-end:[cloudwatch.go.create_role.role_policy] - if err != nil { - return nil, err - } + createPolicyResult, err := svc.CreatePolicy(&iam.CreatePolicyInput{ + PolicyDocument: &policy, + PolicyName: policyName, + }) + // snippet-end:[cloudwatch.go.create_role.role_policy] + if err != nil { + return nil, err + } - // snippet-start:[cloudwatch.go.create_role.role_trust] - trustRelationship := []byte(`{ + // snippet-start:[cloudwatch.go.create_role.role_trust] + trustRelationship := []byte(`{ "Version": "2012-10-17", "Statement": [ { @@ -83,66 +76,67 @@ func CreateRole(sess *session.Session, roleName *string, policyName *string) (*i ] }`) - trustPolicy := string(trustRelationship[:]) - - createRoleResult, err := svc.CreateRole(&iam.CreateRoleInput{ - AssumeRolePolicyDocument: aws.String(trustPolicy), - RoleName: roleName, - }) - // snippet-end:[cloudwatch.go.create_role.role_trust] - if err != nil { - return nil, err - } - - getUserResult, err := svc.GetUser(nil) - if err != nil { - return nil, err - } - - userName := getUserResult.User.UserName - - // snippet-start:[cloudwatch.go.create_role.attach_user_policy] - _, err = svc.AttachUserPolicy(&iam.AttachUserPolicyInput{ - PolicyArn: createPolicyResult.Policy.Arn, - UserName: userName, - }) - // snippet-end:[cloudwatch.go.create_role.attach_user_policy] - if err != nil { - return nil, err - } - - return createRoleResult, nil + trustPolicy := string(trustRelationship[:]) + + createRoleResult, err := svc.CreateRole(&iam.CreateRoleInput{ + AssumeRolePolicyDocument: aws.String(trustPolicy), + RoleName: roleName, + }) + // snippet-end:[cloudwatch.go.create_role.role_trust] + if err != nil { + return nil, err + } + + getUserResult, err := svc.GetUser(nil) + if err != nil { + return nil, err + } + + userName := getUserResult.User.UserName + + // snippet-start:[cloudwatch.go.create_role.attach_user_policy] + _, err = svc.AttachUserPolicy(&iam.AttachUserPolicyInput{ + PolicyArn: createPolicyResult.Policy.Arn, + UserName: userName, + }) + // snippet-end:[cloudwatch.go.create_role.attach_user_policy] + if err != nil { + return nil, err + } + + return createRoleResult, nil } func main() { - // snippet-start:[cloudwatch.go.create_role.args] - policyName := flag.String("p", "", "The name of the policy") - roleName := flag.String("r", "", "The name of the role") - flag.Parse() - - if *policyName == "" || *roleName == "" { - fmt.Println("You must supply a policy name (-p POLICY) and role name (-r ROLE)") - return - } - // snippet-end:[cloudwatch.go.create_role.args] - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file (~/.aws/credentials) - // snippet-start:[cloudwatch.go.create_role.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[cloudwatch.go.create_role.session] - - result, err := CreateRole(sess, roleName, policyName) - if err != nil { - fmt.Println("Got an error creating the role:") - fmt.Println(err) - return - } - - // snippet-start:[cloudwatch.go.create_role.print] - fmt.Println("Role ARN: " + *result.Role.Arn) - // snippet-end:[cloudwatch.go.create_role.print] + // snippet-start:[cloudwatch.go.create_role.args] + policyName := flag.String("p", "", "The name of the policy") + roleName := flag.String("r", "", "The name of the role") + flag.Parse() + + if *policyName == "" || *roleName == "" { + fmt.Println("You must supply a policy name (-p POLICY) and role name (-r ROLE)") + return + } + // snippet-end:[cloudwatch.go.create_role.args] + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file (~/.aws/credentials) + // snippet-start:[cloudwatch.go.create_role.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[cloudwatch.go.create_role.session] + + result, err := CreateRole(sess, roleName, policyName) + if err != nil { + fmt.Println("Got an error creating the role:") + fmt.Println(err) + return + } + + // snippet-start:[cloudwatch.go.create_role.print] + fmt.Println("Role ARN: " + *result.Role.Arn) + // snippet-end:[cloudwatch.go.create_role.print] } + // snippet-end:[cloudwatch.go.create_role] diff --git a/go/cloudwatch/CreateRole/CreateRole_test.go b/go/cloudwatch/CreateRole/CreateRole_test.go index 8e1b9043021..f19c534e22b 100644 --- a/go/cloudwatch/CreateRole/CreateRole_test.go +++ b/go/cloudwatch/CreateRole/CreateRole_test.go @@ -1,34 +1,23 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/google/uuid" + "encoding/json" + "io/ioutil" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/google/uuid" ) // Config represents the information for the test type Config struct { - PolicyName string `json:"PolicyName"` - RoleName string `json:"RoleName"` + PolicyName string `json:"PolicyName"` + RoleName string `json:"RoleName"` } var configFileName = "config.json" @@ -36,76 +25,76 @@ var configFileName = "config.json" var globalConfig Config func populateConfig(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - id := uuid.New() + id := uuid.New() - if globalConfig.PolicyName == "" { - globalConfig.PolicyName = "TestPolicy-" + id.String() - } + if globalConfig.PolicyName == "" { + globalConfig.PolicyName = "TestPolicy-" + id.String() + } - if globalConfig.RoleName == "" { - globalConfig.RoleName = "TestRole-" + id.String() - } + if globalConfig.RoleName == "" { + globalConfig.RoleName = "TestRole-" + id.String() + } - t.Log("PolicyName: " + globalConfig.PolicyName) - t.Log("RoleName: " + globalConfig.RoleName) + t.Log("PolicyName: " + globalConfig.PolicyName) + t.Log("RoleName: " + globalConfig.RoleName) - return nil + return nil } func deleteRole(sess *session.Session, roleName *string) error { - svc := iam.New(sess) + svc := iam.New(sess) - _, err := svc.DeleteRole(&iam.DeleteRoleInput{ - RoleName: roleName, - }) - if err != nil { - return err - } + _, err := svc.DeleteRole(&iam.DeleteRoleInput{ + RoleName: roleName, + }) + if err != nil { + return err + } - return nil + return nil } func TestCreateEvent(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfig(t) - if err != nil { - t.Fatal(err) - } - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - _, err = CreateRole(sess, &globalConfig.RoleName, &globalConfig.PolicyName) - if err != nil { - t.Fatal(err) - } - - t.Log("Created role " + globalConfig.RoleName) - - err = deleteRole(sess, &globalConfig.RoleName) - if err != nil { - t.Log("You must delete role " + globalConfig.RoleName + " yourself") - t.Fatal(err) - } - - t.Log("Deleted role " + globalConfig.RoleName) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfig(t) + if err != nil { + t.Fatal(err) + } + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + _, err = CreateRole(sess, &globalConfig.RoleName, &globalConfig.PolicyName) + if err != nil { + t.Fatal(err) + } + + t.Log("Created role " + globalConfig.RoleName) + + err = deleteRole(sess, &globalConfig.RoleName) + if err != nil { + t.Log("You must delete role " + globalConfig.RoleName + " yourself") + t.Fatal(err) + } + + t.Log("Deleted role " + globalConfig.RoleName) } diff --git a/go/cloudwatch/CreateRule/CreateRule.go b/go/cloudwatch/CreateRule/CreateRule.go index 38d998e8213..0c6c3e18431 100644 --- a/go/cloudwatch/CreateRule/CreateRule.go +++ b/go/cloudwatch/CreateRule/CreateRule.go @@ -1,86 +1,80 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cloudwatch.go.create_rule] package main // snippet-start:[cloudwatch.go.create_rule.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatchevents" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatchevents" ) + // snippet-end:[cloudwatch.go.create_rule.imports] // CreateRule creates a rule that watches for events on a schedule. // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// ruleName is the name of the rule -// roleARN is the ARN of the role -// schedule is the schedule expression +// +// sess is the current session, which provides configuration for the SDK's service clients +// ruleName is the name of the rule +// roleARN is the ARN of the role +// schedule is the schedule expression +// // Output: -// If successful, a PutRuleOutput and nil -// Otherwise, nil and the error from a call to PutRule +// +// If successful, a PutRuleOutput and nil +// Otherwise, nil and the error from a call to PutRule func CreateRule(sess *session.Session, ruleName *string, roleARN *string, schedule *string) (*cloudwatchevents.PutRuleOutput, error) { - // Create the service client - // snippet-start:[cloudwatch.go.create_rule.call] - svc := cloudwatchevents.New(sess) + // Create the service client + // snippet-start:[cloudwatch.go.create_rule.call] + svc := cloudwatchevents.New(sess) - result, err := svc.PutRule(&cloudwatchevents.PutRuleInput{ - Name: ruleName, - RoleArn: roleARN, - ScheduleExpression: schedule, - }) - // snippet-end:[cloudwatch.go.create_rule.call] - if err != nil { - return nil, err - } + result, err := svc.PutRule(&cloudwatchevents.PutRuleInput{ + Name: ruleName, + RoleArn: roleARN, + ScheduleExpression: schedule, + }) + // snippet-end:[cloudwatch.go.create_rule.call] + if err != nil { + return nil, err + } - return result, nil + return result, nil } func main() { - // snippet-start:[cloudwatch.go.create_rule.args] - ruleName := flag.String("r", "", "The name of the rule") - roleARN := flag.String("a", "", "The ARN of the role") - schedule := flag.String("s", "", "The schedule expression") - flag.Parse() + // snippet-start:[cloudwatch.go.create_rule.args] + ruleName := flag.String("r", "", "The name of the rule") + roleARN := flag.String("a", "", "The ARN of the role") + schedule := flag.String("s", "", "The schedule expression") + flag.Parse() - if *ruleName == "" || *roleARN == "" || *schedule == "" { - fmt.Println("You must supply a rule name (-r RULE), role ARN (-a ROLE-ARN), and schedule expression (-s EXPRESSION)") - return - } - // snippet-end:[cloudwatch.go.create_rule.args] + if *ruleName == "" || *roleARN == "" || *schedule == "" { + fmt.Println("You must supply a rule name (-r RULE), role ARN (-a ROLE-ARN), and schedule expression (-s EXPRESSION)") + return + } + // snippet-end:[cloudwatch.go.create_rule.args] - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file (~/.aws/credentials) - // snippet-start:[cloudwatch.go.create_rule.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[cloudwatch.go.create_rule.session] + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file (~/.aws/credentials) + // snippet-start:[cloudwatch.go.create_rule.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[cloudwatch.go.create_rule.session] - result, err := CreateRule(sess, ruleName, roleARN, schedule) - if err != nil { - fmt.Println("Got an error creating the rule:") - fmt.Println(err) - return - } + result, err := CreateRule(sess, ruleName, roleARN, schedule) + if err != nil { + fmt.Println("Got an error creating the rule:") + fmt.Println(err) + return + } - // snippet-start:[cloudwatch.go.create_rule.print] - fmt.Println("Rule ARN:" + *result.RuleArn) - // snippet-end:[cloudwatch.go.create_rule.print] + // snippet-start:[cloudwatch.go.create_rule.print] + fmt.Println("Rule ARN:" + *result.RuleArn) + // snippet-end:[cloudwatch.go.create_rule.print] } -// snippet-end:[cloudwatch.go.create_rule] \ No newline at end of file + +// snippet-end:[cloudwatch.go.create_rule] diff --git a/go/cloudwatch/CreateRule/CreateRule_test.go b/go/cloudwatch/CreateRule/CreateRule_test.go index 80c8a7475d3..1c4aa6154f0 100644 --- a/go/cloudwatch/CreateRule/CreateRule_test.go +++ b/go/cloudwatch/CreateRule/CreateRule_test.go @@ -1,42 +1,31 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "strconv" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatchevents" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/google/uuid" + "encoding/json" + "io/ioutil" + "strconv" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatchevents" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/google/uuid" ) // Config represents the information for the test type Config struct { - PolicyName string `json:"PolicyName"` - PolicyWait int `json:"PolicyWait"` - RoleARN string `json:"RoleARN"` - RoleName string `json:"RoleName"` - RoleWait int `json:"RoleWait"` - RuleName string `json:"RuleName"` - Schedule string `json:"Schedule"` + PolicyName string `json:"PolicyName"` + PolicyWait int `json:"PolicyWait"` + RoleARN string `json:"RoleARN"` + RoleName string `json:"RoleName"` + RoleWait int `json:"RoleWait"` + RuleName string `json:"RuleName"` + Schedule string `json:"Schedule"` } var configFileName = "config.json" @@ -44,57 +33,57 @@ var configFileName = "config.json" var globalConfig Config func populateConfig(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - id := uuid.New() + id := uuid.New() - if globalConfig.PolicyName == "" { - globalConfig.PolicyName = "TestPolicy-" + id.String() - } + if globalConfig.PolicyName == "" { + globalConfig.PolicyName = "TestPolicy-" + id.String() + } - if globalConfig.RoleName == "" { - globalConfig.RoleName = "TestRole-" + id.String() - } + if globalConfig.RoleName == "" { + globalConfig.RoleName = "TestRole-" + id.String() + } - if globalConfig.RuleName == "" { - globalConfig.RuleName = "TestRule-" + id.String() - } + if globalConfig.RuleName == "" { + globalConfig.RuleName = "TestRule-" + id.String() + } - if globalConfig.Schedule == "" { - globalConfig.Schedule = "rate(5 minutes)" - } + if globalConfig.Schedule == "" { + globalConfig.Schedule = "rate(5 minutes)" + } - t.Log("PolicyName: " + globalConfig.PolicyName) - t.Log("PolicyWait " + strconv.Itoa(globalConfig.PolicyWait)) - t.Log("RoleARN: " + globalConfig.RoleARN) - t.Log("RoleName: " + globalConfig.RoleName) - t.Log("RoleWait: " + strconv.Itoa(globalConfig.RoleWait)) - t.Log("RuleName: " + globalConfig.RuleName) - t.Log("Schedule: " + globalConfig.Schedule) + t.Log("PolicyName: " + globalConfig.PolicyName) + t.Log("PolicyWait " + strconv.Itoa(globalConfig.PolicyWait)) + t.Log("RoleARN: " + globalConfig.RoleARN) + t.Log("RoleName: " + globalConfig.RoleName) + t.Log("RoleWait: " + strconv.Itoa(globalConfig.RoleWait)) + t.Log("RuleName: " + globalConfig.RuleName) + t.Log("Schedule: " + globalConfig.Schedule) - return nil + return nil } func multiplyDuration(factor int64, d time.Duration) time.Duration { - return time.Duration(factor) * d + return time.Duration(factor) * d } func createRole(t *testing.T, sess *session.Session, roleName *string, policyName *string) (*iam.CreateRoleOutput, string, error) { - // Create the service client - svc := iam.New(sess) + // Create the service client + svc := iam.New(sess) - // From: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/cw-example-sending-events.html - rolePolicy := []byte(`{ + // From: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/cw-example-sending-events.html + rolePolicy := []byte(`{ "Version": "2012-10-17", "Statement": [ { @@ -112,30 +101,30 @@ func createRole(t *testing.T, sess *session.Session, roleName *string, policyNam ] }`) - policy := string(rolePolicy[:]) + policy := string(rolePolicy[:]) - createPolicyResult, err := svc.CreatePolicy(&iam.CreatePolicyInput{ - PolicyDocument: &policy, - PolicyName: policyName, - }) - if err != nil { - return nil, "", err - } + createPolicyResult, err := svc.CreatePolicy(&iam.CreatePolicyInput{ + PolicyDocument: &policy, + PolicyName: policyName, + }) + if err != nil { + return nil, "", err + } - policyARN := createPolicyResult.Policy.Arn + policyARN := createPolicyResult.Policy.Arn - err = svc.WaitUntilPolicyExists(&iam.GetPolicyInput{ - PolicyArn: policyARN, - }) - if err != nil { - return nil, "", err - } + err = svc.WaitUntilPolicyExists(&iam.GetPolicyInput{ + PolicyArn: policyARN, + }) + if err != nil { + return nil, "", err + } - t.Log("Waiting " + strconv.Itoa(globalConfig.PolicyWait) + " seconds for policy to be created") - ts := multiplyDuration(int64(globalConfig.PolicyWait), time.Second) - time.Sleep(ts) + t.Log("Waiting " + strconv.Itoa(globalConfig.PolicyWait) + " seconds for policy to be created") + ts := multiplyDuration(int64(globalConfig.PolicyWait), time.Second) + time.Sleep(ts) - trustRelationship := []byte(`{ + trustRelationship := []byte(`{ "Version": "2012-10-17", "Statement": [ { @@ -148,142 +137,142 @@ func createRole(t *testing.T, sess *session.Session, roleName *string, policyNam ] }`) - trustPolicy := string(trustRelationship[:]) - - createRoleResult, err := svc.CreateRole(&iam.CreateRoleInput{ - AssumeRolePolicyDocument: aws.String(trustPolicy), - RoleName: roleName, - }) - if err != nil { - return nil, "", err - } - - err = svc.WaitUntilRoleExists(&iam.GetRoleInput{ - RoleName: roleName, - }) - if err != nil { - return nil, "", err - } - - t.Log("Waiting " + strconv.Itoa(globalConfig.RoleWait) + " seconds for role to be created") - ts = multiplyDuration(int64(globalConfig.RoleWait), time.Second) - time.Sleep(ts) - - _, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{ - PolicyArn: policyARN, - RoleName: roleName, - }) - if err != nil { - return nil, "", err - } - - return createRoleResult, *policyARN, nil + trustPolicy := string(trustRelationship[:]) + + createRoleResult, err := svc.CreateRole(&iam.CreateRoleInput{ + AssumeRolePolicyDocument: aws.String(trustPolicy), + RoleName: roleName, + }) + if err != nil { + return nil, "", err + } + + err = svc.WaitUntilRoleExists(&iam.GetRoleInput{ + RoleName: roleName, + }) + if err != nil { + return nil, "", err + } + + t.Log("Waiting " + strconv.Itoa(globalConfig.RoleWait) + " seconds for role to be created") + ts = multiplyDuration(int64(globalConfig.RoleWait), time.Second) + time.Sleep(ts) + + _, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{ + PolicyArn: policyARN, + RoleName: roleName, + }) + if err != nil { + return nil, "", err + } + + return createRoleResult, *policyARN, nil } func deleteRule(sess *session.Session, ruleName *string) error { - // Create the service client - svc := cloudwatchevents.New(sess) + // Create the service client + svc := cloudwatchevents.New(sess) - _, err := svc.DeleteRule(&cloudwatchevents.DeleteRuleInput{ - Name: ruleName, - }) - if err != nil { - return err - } + _, err := svc.DeleteRule(&cloudwatchevents.DeleteRuleInput{ + Name: ruleName, + }) + if err != nil { + return err + } - return nil + return nil } func detachPolicy(sess *session.Session, policyARN *string, roleName *string) error { - svc := iam.New(sess) + svc := iam.New(sess) - _, err := svc.DetachRolePolicy(&iam.DetachRolePolicyInput{ - PolicyArn: policyARN, - RoleName: roleName, - }) - if err != nil { - return err - } + _, err := svc.DetachRolePolicy(&iam.DetachRolePolicyInput{ + PolicyArn: policyARN, + RoleName: roleName, + }) + if err != nil { + return err + } - return nil + return nil } func deleteRole(sess *session.Session, roleName *string) error { - svc := iam.New(sess) + svc := iam.New(sess) - _, err := svc.DeleteRole(&iam.DeleteRoleInput{ - RoleName: roleName, - }) - if err != nil { - return err - } + _, err := svc.DeleteRole(&iam.DeleteRoleInput{ + RoleName: roleName, + }) + if err != nil { + return err + } - return nil + return nil } func TestCreateEvent(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfig(t) - if err != nil { - t.Fatal(err) - } - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file (~/.aws/credentials) - // and configuration from the shared configuration file (~/.aws/config). - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - roleCreated := false - var roleResult *iam.CreateRoleOutput - policyARN := "" - - if globalConfig.RoleARN == "" { - roleResult, policyARN, err = createRole(t, sess, &globalConfig.RoleName, &globalConfig.PolicyName) - if err != nil { - t.Fatal(err) - } - - roleCreated = true - - globalConfig.RoleARN = *roleResult.Role.Arn - - t.Log("Created role with ARN: " + globalConfig.RoleARN) - } else { - t.Log("Using role with ARN " + globalConfig.RoleARN) - } - - ruleResult, err := CreateRule(sess, &globalConfig.RuleName, &globalConfig.RoleARN, &globalConfig.Schedule) - if err != nil { - t.Fatal(err) - } - - t.Log("Created rule with ARN: " + *ruleResult.RuleArn) - - err = deleteRule(sess, &globalConfig.RuleName) - if err != nil { - t.Fatal(err) - } - - t.Log("Deleted rule " + globalConfig.RuleName) - - if roleCreated { - // Have to detach role policy first - err := detachPolicy(sess, &policyARN, &globalConfig.RoleName) - if err != nil { - t.Fatal(err) - } - - t.Log("Detached policy " + globalConfig.PolicyName) - - err = deleteRole(sess, &globalConfig.RoleName) - if err != nil { - t.Fatal(err) - } - - t.Log("Deleted role " + globalConfig.RoleName) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfig(t) + if err != nil { + t.Fatal(err) + } + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file (~/.aws/credentials) + // and configuration from the shared configuration file (~/.aws/config). + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + roleCreated := false + var roleResult *iam.CreateRoleOutput + policyARN := "" + + if globalConfig.RoleARN == "" { + roleResult, policyARN, err = createRole(t, sess, &globalConfig.RoleName, &globalConfig.PolicyName) + if err != nil { + t.Fatal(err) + } + + roleCreated = true + + globalConfig.RoleARN = *roleResult.Role.Arn + + t.Log("Created role with ARN: " + globalConfig.RoleARN) + } else { + t.Log("Using role with ARN " + globalConfig.RoleARN) + } + + ruleResult, err := CreateRule(sess, &globalConfig.RuleName, &globalConfig.RoleARN, &globalConfig.Schedule) + if err != nil { + t.Fatal(err) + } + + t.Log("Created rule with ARN: " + *ruleResult.RuleArn) + + err = deleteRule(sess, &globalConfig.RuleName) + if err != nil { + t.Fatal(err) + } + + t.Log("Deleted rule " + globalConfig.RuleName) + + if roleCreated { + // Have to detach role policy first + err := detachPolicy(sess, &policyARN, &globalConfig.RoleName) + if err != nil { + t.Fatal(err) + } + + t.Log("Detached policy " + globalConfig.PolicyName) + + err = deleteRole(sess, &globalConfig.RoleName) + if err != nil { + t.Fatal(err) + } + + t.Log("Deleted role " + globalConfig.RoleName) + } } diff --git a/go/cloudwatch/CreateTarget/CreateTarget.go b/go/cloudwatch/CreateTarget/CreateTarget.go index 77ca7ff8845..539e540944b 100644 --- a/go/cloudwatch/CreateTarget/CreateTarget.go +++ b/go/cloudwatch/CreateTarget/CreateTarget.go @@ -1,91 +1,84 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cloudwatch.go.create_target] package main // snippet-start:[cloudwatch.go.create_target.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatchevents" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatchevents" ) + // snippet-end:[cloudwatch.go.create_target.imports] // CreateTarget creates a target that is the resource that is invoked when the rule is triggered // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// rule is the name of the rule -// lambdaARN is the ARN of the Lambda function that is invoked -// targetID is the identifier for the target +// +// sess is the current session, which provides configuration for the SDK's service clients +// rule is the name of the rule +// lambdaARN is the ARN of the Lambda function that is invoked +// targetID is the identifier for the target +// // Output: -// If successful, a PutTargetsOutput and nil -// Otherwise, nil and the error from a call to PutTargets // +// If successful, a PutTargetsOutput and nil +// Otherwise, nil and the error from a call to PutTargets func CreateTarget(sess *session.Session, rule *string, lambdaARN *string, targetID *string) error { - // Create the service client - // snippet-start:[cloudwatch.go.create_target.call] - svc := cloudwatchevents.New(sess) + // Create the service client + // snippet-start:[cloudwatch.go.create_target.call] + svc := cloudwatchevents.New(sess) - _, err := svc.PutTargets(&cloudwatchevents.PutTargetsInput{ - Rule: rule, - Targets: []*cloudwatchevents.Target{ - &cloudwatchevents.Target{ - Arn: lambdaARN, - Id: targetID, - }, - }, - }) - // snippet-end:[cloudwatch.go.create_target.call] - if err != nil { - return err - } + _, err := svc.PutTargets(&cloudwatchevents.PutTargetsInput{ + Rule: rule, + Targets: []*cloudwatchevents.Target{ + &cloudwatchevents.Target{ + Arn: lambdaARN, + Id: targetID, + }, + }, + }) + // snippet-end:[cloudwatch.go.create_target.call] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[cloudwatch.go.create_target.args] - rule := flag.String("r", "", "The name of the rule") - lambdaARN := flag.String("l", "", "The ARN of the Lambda function that is invoked") - targetID := flag.String("t", "", "The identifier for the target") - flag.Parse() + // snippet-start:[cloudwatch.go.create_target.args] + rule := flag.String("r", "", "The name of the rule") + lambdaARN := flag.String("l", "", "The ARN of the Lambda function that is invoked") + targetID := flag.String("t", "", "The identifier for the target") + flag.Parse() - if *rule == "" || *lambdaARN == "" || *targetID == "" { - fmt.Println("You must supply a rule name (-r RULE), Lambda ARN (-l LAMBDA) and target ID (-t TARGET)") - return - } - // snippet-end:[cloudwatch.go.create_target.args] + if *rule == "" || *lambdaARN == "" || *targetID == "" { + fmt.Println("You must supply a rule name (-r RULE), Lambda ARN (-l LAMBDA) and target ID (-t TARGET)") + return + } + // snippet-end:[cloudwatch.go.create_target.args] - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file (~/.aws/credentials) - // snippet-start:[cloudwatch.go.create_target.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[cloudwatch.go.create_target.session] + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file (~/.aws/credentials) + // snippet-start:[cloudwatch.go.create_target.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[cloudwatch.go.create_target.session] - err := CreateTarget(sess, rule, lambdaARN, targetID) - if err != nil { - fmt.Println("Got an error creating a target:") - fmt.Println(err) - return - } + err := CreateTarget(sess, rule, lambdaARN, targetID) + if err != nil { + fmt.Println("Got an error creating a target:") + fmt.Println(err) + return + } - // snippet-start:[cloudwatch.go.create_target.print] - fmt.Println("Target " + *targetID + " created") - // snippet-end:[cloudwatch.go.create_target.print] + // snippet-start:[cloudwatch.go.create_target.print] + fmt.Println("Target " + *targetID + " created") + // snippet-end:[cloudwatch.go.create_target.print] } + // snippet-end:[cloudwatch.go.create_target] diff --git a/go/cloudwatch/CreateTarget/CreateTarget_test.go b/go/cloudwatch/CreateTarget/CreateTarget_test.go index 22be34ba132..4cdf2d94ed9 100644 --- a/go/cloudwatch/CreateTarget/CreateTarget_test.go +++ b/go/cloudwatch/CreateTarget/CreateTarget_test.go @@ -1,45 +1,34 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "errors" - "io/ioutil" - "strconv" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatchevents" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/google/uuid" + "encoding/json" + "errors" + "io/ioutil" + "strconv" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatchevents" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/google/uuid" ) // Config represents the information for the test type Config struct { - LambdaARN string `json:"LambdaARN"` - PolicyName string - PolicyWait int `json:"PolicyWait"` - RoleARN string `json:"RoleARN"` - RoleName string - RoleWait int `json:"RoleWait"` - RuleName string `json:"RuleName"` - Schedule string `json:"Schedule"` - TargetID string `json:"TargetID"` + LambdaARN string `json:"LambdaARN"` + PolicyName string + PolicyWait int `json:"PolicyWait"` + RoleARN string `json:"RoleARN"` + RoleName string + RoleWait int `json:"RoleWait"` + RuleName string `json:"RuleName"` + Schedule string `json:"Schedule"` + TargetID string `json:"TargetID"` } var configFileName = "config.json" @@ -47,44 +36,44 @@ var configFileName = "config.json" var globalConfig Config func populateConfig(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } - - text := string(content) - - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } - - t.Log("LambdaARN: " + globalConfig.LambdaARN) - t.Log("PolicyWait " + strconv.Itoa(globalConfig.PolicyWait)) - t.Log("RoleARN: " + globalConfig.RoleARN) - t.Log("RoleName: " + globalConfig.RoleName) - t.Log("RoleWait: " + strconv.Itoa(globalConfig.RoleWait)) - t.Log("RuleName: " + globalConfig.RuleName) - t.Log("Schedule: " + globalConfig.Schedule) - t.Log("TargetID: " + globalConfig.TargetID) - - if globalConfig.LambdaARN == "" { - return errors.New("No Lambda ARN was configured") - } - - return nil + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } + + text := string(content) + + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } + + t.Log("LambdaARN: " + globalConfig.LambdaARN) + t.Log("PolicyWait " + strconv.Itoa(globalConfig.PolicyWait)) + t.Log("RoleARN: " + globalConfig.RoleARN) + t.Log("RoleName: " + globalConfig.RoleName) + t.Log("RoleWait: " + strconv.Itoa(globalConfig.RoleWait)) + t.Log("RuleName: " + globalConfig.RuleName) + t.Log("Schedule: " + globalConfig.Schedule) + t.Log("TargetID: " + globalConfig.TargetID) + + if globalConfig.LambdaARN == "" { + return errors.New("No Lambda ARN was configured") + } + + return nil } func multiplyDuration(factor int64, d time.Duration) time.Duration { - return time.Duration(factor) * d + return time.Duration(factor) * d } func createRole(t *testing.T, sess *session.Session, roleName *string, policyName *string) (*iam.CreateRoleOutput, string, error) { - // Create the service client - svc := iam.New(sess) + // Create the service client + svc := iam.New(sess) - // From: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/cw-example-sending-events.html - rolePolicy := []byte(`{ + // From: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/cw-example-sending-events.html + rolePolicy := []byte(`{ "Version": "2012-10-17", "Statement": [ { @@ -102,30 +91,30 @@ func createRole(t *testing.T, sess *session.Session, roleName *string, policyNam ] }`) - policy := string(rolePolicy[:]) + policy := string(rolePolicy[:]) - createPolicyResult, err := svc.CreatePolicy(&iam.CreatePolicyInput{ - PolicyDocument: &policy, - PolicyName: policyName, - }) - if err != nil { - return nil, "", err - } + createPolicyResult, err := svc.CreatePolicy(&iam.CreatePolicyInput{ + PolicyDocument: &policy, + PolicyName: policyName, + }) + if err != nil { + return nil, "", err + } - policyARN := createPolicyResult.Policy.Arn + policyARN := createPolicyResult.Policy.Arn - err = svc.WaitUntilPolicyExists(&iam.GetPolicyInput{ - PolicyArn: policyARN, - }) - if err != nil { - return nil, "", err - } + err = svc.WaitUntilPolicyExists(&iam.GetPolicyInput{ + PolicyArn: policyARN, + }) + if err != nil { + return nil, "", err + } - t.Log("Waiting " + strconv.Itoa(globalConfig.PolicyWait) + " seconds for policy to be created") - ts := multiplyDuration(int64(globalConfig.PolicyWait), time.Second) - time.Sleep(ts) + t.Log("Waiting " + strconv.Itoa(globalConfig.PolicyWait) + " seconds for policy to be created") + ts := multiplyDuration(int64(globalConfig.PolicyWait), time.Second) + time.Sleep(ts) - trustRelationship := []byte(`{ + trustRelationship := []byte(`{ "Version": "2012-10-17", "Statement": [ { @@ -138,212 +127,212 @@ func createRole(t *testing.T, sess *session.Session, roleName *string, policyNam ] }`) - trustPolicy := string(trustRelationship[:]) - - createRoleResult, err := svc.CreateRole(&iam.CreateRoleInput{ - AssumeRolePolicyDocument: aws.String(trustPolicy), - RoleName: roleName, - }) - if err != nil { - return nil, "", err - } - - err = svc.WaitUntilRoleExists(&iam.GetRoleInput{ - RoleName: roleName, - }) - if err != nil { - return nil, "", err - } - - t.Log("Waiting " + strconv.Itoa(globalConfig.RoleWait) + " seconds for role to be created") - ts = multiplyDuration(int64(globalConfig.RoleWait), time.Second) - time.Sleep(ts) - - _, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{ - PolicyArn: policyARN, - RoleName: roleName, - }) - if err != nil { - return nil, "", err - } - - return createRoleResult, *policyARN, nil + trustPolicy := string(trustRelationship[:]) + + createRoleResult, err := svc.CreateRole(&iam.CreateRoleInput{ + AssumeRolePolicyDocument: aws.String(trustPolicy), + RoleName: roleName, + }) + if err != nil { + return nil, "", err + } + + err = svc.WaitUntilRoleExists(&iam.GetRoleInput{ + RoleName: roleName, + }) + if err != nil { + return nil, "", err + } + + t.Log("Waiting " + strconv.Itoa(globalConfig.RoleWait) + " seconds for role to be created") + ts = multiplyDuration(int64(globalConfig.RoleWait), time.Second) + time.Sleep(ts) + + _, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{ + PolicyArn: policyARN, + RoleName: roleName, + }) + if err != nil { + return nil, "", err + } + + return createRoleResult, *policyARN, nil } func createRule(sess *session.Session, ruleName *string, roleARN *string, schedule *string) (*cloudwatchevents.PutRuleOutput, error) { - // Create the service client - svc := cloudwatchevents.New(sess) - - result, err := svc.PutRule(&cloudwatchevents.PutRuleInput{ - Name: ruleName, - RoleArn: roleARN, - ScheduleExpression: schedule, - }) - if err != nil { - return nil, err - } - - return result, nil + // Create the service client + svc := cloudwatchevents.New(sess) + + result, err := svc.PutRule(&cloudwatchevents.PutRuleInput{ + Name: ruleName, + RoleArn: roleARN, + ScheduleExpression: schedule, + }) + if err != nil { + return nil, err + } + + return result, nil } func deleteRule(sess *session.Session, ruleName *string) error { - // Create the service client - svc := cloudwatchevents.New(sess) + // Create the service client + svc := cloudwatchevents.New(sess) - _, err := svc.DeleteRule(&cloudwatchevents.DeleteRuleInput{ - Name: ruleName, - }) - if err != nil { - return err - } + _, err := svc.DeleteRule(&cloudwatchevents.DeleteRuleInput{ + Name: ruleName, + }) + if err != nil { + return err + } - return nil + return nil } func detachPolicy(sess *session.Session, policyARN *string, roleName *string) error { - svc := iam.New(sess) + svc := iam.New(sess) - _, err := svc.DetachRolePolicy(&iam.DetachRolePolicyInput{ - PolicyArn: policyARN, - RoleName: roleName, - }) - if err != nil { - return err - } + _, err := svc.DetachRolePolicy(&iam.DetachRolePolicyInput{ + PolicyArn: policyARN, + RoleName: roleName, + }) + if err != nil { + return err + } - return nil + return nil } func deleteRole(sess *session.Session, roleName *string) error { - svc := iam.New(sess) + svc := iam.New(sess) - _, err := svc.DeleteRole(&iam.DeleteRoleInput{ - RoleName: roleName, - }) - if err != nil { - return err - } + _, err := svc.DeleteRole(&iam.DeleteRoleInput{ + RoleName: roleName, + }) + if err != nil { + return err + } - return nil + return nil } func deleteTarget(sess *session.Session, rule *string, targetID *string) error { - svc := cloudwatchevents.New(sess) - - _, err := svc.RemoveTargets(&cloudwatchevents.RemoveTargetsInput{ - Rule: rule, - Ids: []*string{ - targetID, - }, - }) - if err != nil { - return err - } - - return nil + svc := cloudwatchevents.New(sess) + + _, err := svc.RemoveTargets(&cloudwatchevents.RemoveTargetsInput{ + Rule: rule, + Ids: []*string{ + targetID, + }, + }) + if err != nil { + return err + } + + return nil } func TestCreateEvent(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfig(t) - if err != nil { - t.Fatal(err) - } - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - id := uuid.New() - - if globalConfig.Schedule == "" { - globalConfig.Schedule = "rate(5 minutes)" - } - - createdRole := false - var roleResult *iam.CreateRoleOutput - policyARN := "" - - if globalConfig.RoleARN == "" { - globalConfig.RoleName = "TestRole-" + id.String() - globalConfig.PolicyName = "TestPolicy-" + id.String() - - roleResult, policyARN, err = createRole(t, sess, &globalConfig.RoleName, &globalConfig.PolicyName) - if err != nil { - t.Fatal(err) - } - - createdRole = true - - globalConfig.RoleARN = *roleResult.Role.Arn - - t.Log("Created role with ARN: " + globalConfig.RoleARN) - } else { - t.Log("Using role with ARN " + globalConfig.RoleARN) - } - - createdRule := false - - if globalConfig.RuleName == "" { - globalConfig.RuleName = "TestRule-" + id.String() - - ruleResult, err := createRule(sess, &globalConfig.RuleName, &globalConfig.RoleARN, &globalConfig.Schedule) - if err != nil { - t.Fatal(err) - } - - createdRule = true - t.Log("Created rule with ARN: " + *ruleResult.RuleArn) - } - - if globalConfig.TargetID == "" { - globalConfig.TargetID = "MyTargetID-" + id.String() - } - - err = CreateTarget(sess, &globalConfig.RuleName, &globalConfig.LambdaARN, &globalConfig.TargetID) - if err != nil { - t.Fatal(err) - } - - t.Log("Created target") - - // Cleanup - err = deleteTarget(sess, &globalConfig.RuleName, &globalConfig.TargetID) - if err != nil { - t.Fatal(err) - } - - t.Log("Deleted target") - - if createdRule { - err = deleteRule(sess, &globalConfig.RuleName) - if err != nil { - t.Log("You'll have to delete rule " + globalConfig.RuleName + " yourself") - t.Fatal(err) - } - - t.Log("Deleted rule " + globalConfig.RuleName) - } - - if createdRole { - err := detachPolicy(sess, &policyARN, &globalConfig.RoleName) - if err != nil { - t.Fatal(err) - } - - t.Log("Detached policy " + globalConfig.PolicyName) - err = deleteRole(sess, &globalConfig.RoleName) - if err != nil { - t.Log("You must delete role " + globalConfig.RoleName + " yourself") - t.Fatal(err) - } - - t.Log("Deleted role " + globalConfig.RoleName) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfig(t) + if err != nil { + t.Fatal(err) + } + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + id := uuid.New() + + if globalConfig.Schedule == "" { + globalConfig.Schedule = "rate(5 minutes)" + } + + createdRole := false + var roleResult *iam.CreateRoleOutput + policyARN := "" + + if globalConfig.RoleARN == "" { + globalConfig.RoleName = "TestRole-" + id.String() + globalConfig.PolicyName = "TestPolicy-" + id.String() + + roleResult, policyARN, err = createRole(t, sess, &globalConfig.RoleName, &globalConfig.PolicyName) + if err != nil { + t.Fatal(err) + } + + createdRole = true + + globalConfig.RoleARN = *roleResult.Role.Arn + + t.Log("Created role with ARN: " + globalConfig.RoleARN) + } else { + t.Log("Using role with ARN " + globalConfig.RoleARN) + } + + createdRule := false + + if globalConfig.RuleName == "" { + globalConfig.RuleName = "TestRule-" + id.String() + + ruleResult, err := createRule(sess, &globalConfig.RuleName, &globalConfig.RoleARN, &globalConfig.Schedule) + if err != nil { + t.Fatal(err) + } + + createdRule = true + t.Log("Created rule with ARN: " + *ruleResult.RuleArn) + } + + if globalConfig.TargetID == "" { + globalConfig.TargetID = "MyTargetID-" + id.String() + } + + err = CreateTarget(sess, &globalConfig.RuleName, &globalConfig.LambdaARN, &globalConfig.TargetID) + if err != nil { + t.Fatal(err) + } + + t.Log("Created target") + + // Cleanup + err = deleteTarget(sess, &globalConfig.RuleName, &globalConfig.TargetID) + if err != nil { + t.Fatal(err) + } + + t.Log("Deleted target") + + if createdRule { + err = deleteRule(sess, &globalConfig.RuleName) + if err != nil { + t.Log("You'll have to delete rule " + globalConfig.RuleName + " yourself") + t.Fatal(err) + } + + t.Log("Deleted rule " + globalConfig.RuleName) + } + + if createdRole { + err := detachPolicy(sess, &policyARN, &globalConfig.RoleName) + if err != nil { + t.Fatal(err) + } + + t.Log("Detached policy " + globalConfig.PolicyName) + err = deleteRole(sess, &globalConfig.RoleName) + if err != nil { + t.Log("You must delete role " + globalConfig.RoleName + " yourself") + t.Fatal(err) + } + + t.Log("Deleted role " + globalConfig.RoleName) + } } diff --git a/go/cloudwatch/DeleteAlarm/DeleteAlarm.go b/go/cloudwatch/DeleteAlarm/DeleteAlarm.go index d0495f4f960..204a6c82a2f 100644 --- a/go/cloudwatch/DeleteAlarm/DeleteAlarm.go +++ b/go/cloudwatch/DeleteAlarm/DeleteAlarm.go @@ -1,79 +1,73 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cloudwatch.go.delete_alarm] package main // snippet-start:[cloudwatch.go.delete_alarm.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatch" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatch" ) + // snippet-end:[cloudwatch.go.delete_alarm.imports] // DeleteAlarm deletes an alarm // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// alarmName is the name of the alarm +// +// sess is the current session, which provides configuration for the SDK's service clients +// alarmName is the name of the alarm +// // Output: -// If successful, nil -// Otherwise, the error from a call to DeleteAlarms +// +// If successful, nil +// Otherwise, the error from a call to DeleteAlarms func DeleteAlarm(sess *session.Session, alarmName *string) error { - // Create service client - // snippet-start:[cloudwatch.go.delete_alarm.call] - svc := cloudwatch.New(sess) + // Create service client + // snippet-start:[cloudwatch.go.delete_alarm.call] + svc := cloudwatch.New(sess) - _, err := svc.DeleteAlarms(&cloudwatch.DeleteAlarmsInput{ - AlarmNames: []*string{ - alarmName, - }, - }) - // snippet-end:[cloudwatch.go.delete_alarm.call] - if err != nil { - return err - } + _, err := svc.DeleteAlarms(&cloudwatch.DeleteAlarmsInput{ + AlarmNames: []*string{ + alarmName, + }, + }) + // snippet-end:[cloudwatch.go.delete_alarm.call] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[cloudwatch.go.delete_alarm.args] - alarmName := flag.String("a", "", "The name of the alarm to delete") - flag.Parse() + // snippet-start:[cloudwatch.go.delete_alarm.args] + alarmName := flag.String("a", "", "The name of the alarm to delete") + flag.Parse() - if *alarmName == "" { - fmt.Println("You must supply an alarm name to disable") - return - } - // snippet-end:[cloudwatch.go.delete_alarm.args] + if *alarmName == "" { + fmt.Println("You must supply an alarm name to disable") + return + } + // snippet-end:[cloudwatch.go.delete_alarm.args] - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - // snippet-start:[cloudwatch.go.delete_alarm.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[cloudwatch.go.delete_alarm.session] + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + // snippet-start:[cloudwatch.go.delete_alarm.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[cloudwatch.go.delete_alarm.session] - err := DeleteAlarm(sess, alarmName) - if err != nil { - fmt.Println("Could not delete alarm " + *alarmName) - } else { - fmt.Println("Deleted alarm " + *alarmName) - } + err := DeleteAlarm(sess, alarmName) + if err != nil { + fmt.Println("Could not delete alarm " + *alarmName) + } else { + fmt.Println("Deleted alarm " + *alarmName) + } } + // snippet-end:[cloudwatch.go.delete_alarm] diff --git a/go/cloudwatch/DeleteAlarm/DeleteAlarm_test.go b/go/cloudwatch/DeleteAlarm/DeleteAlarm_test.go index c6cb6fa8186..0fd678aba33 100644 --- a/go/cloudwatch/DeleteAlarm/DeleteAlarm_test.go +++ b/go/cloudwatch/DeleteAlarm/DeleteAlarm_test.go @@ -1,38 +1,27 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatch" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/google/uuid" + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatch" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/google/uuid" ) type config struct { - InstanceName string `json:"InstanceName"` - InstanceID string `json:"InstanceID"` - AlarmName string `json:"AlarmName"` + InstanceName string `json:"InstanceName"` + InstanceID string `json:"InstanceID"` + AlarmName string `json:"AlarmName"` } var globalConfig config @@ -40,122 +29,122 @@ var globalConfig config var configFileName = "config.json" func getEc2Info(sess *session.Session, t *testing.T) (string, string, error) { - svc := ec2.New(sess) - - result, err := svc.DescribeInstances(nil) - if err != nil { - return "", "", err - } - - for _, reservation := range result.Reservations { - for _, instance := range reservation.Instances { - id := instance.InstanceId - name := "" - - for _, tag := range instance.Tags { - if *tag.Key == "Name" { - name = *tag.Value - break - } - } - - if *id != "" && name != "" { - return *id, name, nil - } - } - } - - return "", "", errors.New("No EC2 instance found with name and ID") + svc := ec2.New(sess) + + result, err := svc.DescribeInstances(nil) + if err != nil { + return "", "", err + } + + for _, reservation := range result.Reservations { + for _, instance := range reservation.Instances { + id := instance.InstanceId + name := "" + + for _, tag := range instance.Tags { + if *tag.Key == "Name" { + name = *tag.Value + break + } + } + + if *id != "" && name != "" { + return *id, name, nil + } + } + } + + return "", "", errors.New("No EC2 instance found with name and ID") } func populateConfig(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Instance Name: " + globalConfig.InstanceName) - t.Log("Instance ID: " + globalConfig.InstanceID) - t.Log("Alarm name: " + globalConfig.AlarmName) + t.Log("Instance Name: " + globalConfig.InstanceName) + t.Log("Instance ID: " + globalConfig.InstanceID) + t.Log("Alarm name: " + globalConfig.AlarmName) - return nil + return nil } func createAlarm(sess *session.Session, instanceName *string, instanceID *string, alarmName *string) error { - svc := cloudwatch.New(sess) - - _, err := svc.PutMetricAlarm(&cloudwatch.PutMetricAlarmInput{ - AlarmName: alarmName, - ComparisonOperator: aws.String(cloudwatch.ComparisonOperatorGreaterThanThreshold), - EvaluationPeriods: aws.Int64(1), - MetricName: aws.String("CPUUtilization"), - Namespace: aws.String("AWS/EC2"), - Period: aws.Int64(60), - Statistic: aws.String(cloudwatch.StatisticAverage), - Threshold: aws.Float64(70.0), - ActionsEnabled: aws.Bool(true), - AlarmDescription: aws.String("Alarm when server CPU exceeds 70%"), - Unit: aws.String(cloudwatch.StandardUnitSeconds), - AlarmActions: []*string{ - aws.String(fmt.Sprintf("arn:aws:swf:"+*svc.Config.Region+":%s:action/actions/AWS_EC2.InstanceId.Reboot/1.0", *instanceName)), - }, - Dimensions: []*cloudwatch.Dimension{ - { - Name: aws.String("InstanceId"), - Value: instanceID, - }, - }, - }) - if err != nil { - return err - } - - return nil + svc := cloudwatch.New(sess) + + _, err := svc.PutMetricAlarm(&cloudwatch.PutMetricAlarmInput{ + AlarmName: alarmName, + ComparisonOperator: aws.String(cloudwatch.ComparisonOperatorGreaterThanThreshold), + EvaluationPeriods: aws.Int64(1), + MetricName: aws.String("CPUUtilization"), + Namespace: aws.String("AWS/EC2"), + Period: aws.Int64(60), + Statistic: aws.String(cloudwatch.StatisticAverage), + Threshold: aws.Float64(70.0), + ActionsEnabled: aws.Bool(true), + AlarmDescription: aws.String("Alarm when server CPU exceeds 70%"), + Unit: aws.String(cloudwatch.StandardUnitSeconds), + AlarmActions: []*string{ + aws.String(fmt.Sprintf("arn:aws:swf:"+*svc.Config.Region+":%s:action/actions/AWS_EC2.InstanceId.Reboot/1.0", *instanceName)), + }, + Dimensions: []*cloudwatch.Dimension{ + { + Name: aws.String("InstanceId"), + Value: instanceID, + }, + }, + }) + if err != nil { + return err + } + + return nil } func TestDisableAlarmActions(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Started unit test at " + nowString) - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - err := populateConfig(t) - if err != nil { - msg := "Could not get configuration values from " + configFileName - t.Fatal(msg) - } - - if globalConfig.AlarmName == "" { - id := uuid.New() - globalConfig.AlarmName = "Alarm70-" + id.String() - - if globalConfig.InstanceName == "" || globalConfig.InstanceID == "" { - globalConfig.InstanceName, globalConfig.InstanceID, err = getEc2Info(sess, t) - if err != nil { - t.Fatal(err) - } - } - - err := createAlarm(sess, &globalConfig.InstanceName, &globalConfig.InstanceID, &globalConfig.AlarmName) - if err != nil { - t.Fatal(err) - } - } - - err = DeleteAlarm(sess, &globalConfig.AlarmName) - if err != nil { - t.Fatal(err) - } - - t.Log("Deleted alarm " + globalConfig.AlarmName) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Started unit test at " + nowString) + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + err := populateConfig(t) + if err != nil { + msg := "Could not get configuration values from " + configFileName + t.Fatal(msg) + } + + if globalConfig.AlarmName == "" { + id := uuid.New() + globalConfig.AlarmName = "Alarm70-" + id.String() + + if globalConfig.InstanceName == "" || globalConfig.InstanceID == "" { + globalConfig.InstanceName, globalConfig.InstanceID, err = getEc2Info(sess, t) + if err != nil { + t.Fatal(err) + } + } + + err := createAlarm(sess, &globalConfig.InstanceName, &globalConfig.InstanceID, &globalConfig.AlarmName) + if err != nil { + t.Fatal(err) + } + } + + err = DeleteAlarm(sess, &globalConfig.AlarmName) + if err != nil { + t.Fatal(err) + } + + t.Log("Deleted alarm " + globalConfig.AlarmName) } diff --git a/go/cloudwatch/DescribeAlarms/DescribeAlarms.go b/go/cloudwatch/DescribeAlarms/DescribeAlarms.go index f06bb35db8b..b50a5ba60e3 100644 --- a/go/cloudwatch/DescribeAlarms/DescribeAlarms.go +++ b/go/cloudwatch/DescribeAlarms/DescribeAlarms.go @@ -1,70 +1,64 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ -//snippet-start:[cloudwatch.go.describe_alarms] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[cloudwatch.go.describe_alarms] package main -//snippet-start:[cloudwatch.go.describe_alarms.imports] +// snippet-start:[cloudwatch.go.describe_alarms.imports] import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatch" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatch" ) -//snippet-end:[cloudwatch.go.describe_alarms.imports] + +// snippet-end:[cloudwatch.go.describe_alarms.imports] // ListAlarms returns a list of your Amazon CloudWatch alarms // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients +// +// sess is the current session, which provides configuration for the SDK's service clients +// // Output: -// If success, the list of alarms and nil -// Otherwise, nil and an error from the call to DescribeAlarms +// +// If success, the list of alarms and nil +// Otherwise, nil and an error from the call to DescribeAlarms func ListAlarms(sess *session.Session) (*cloudwatch.DescribeAlarmsOutput, error) { - // Create new service client - //snippet-start:[cloudwatch.go.describe_alarms.call] - svc := cloudwatch.New(sess) + // Create new service client + // snippet-start:[cloudwatch.go.describe_alarms.call] + svc := cloudwatch.New(sess) - resp, err := svc.DescribeAlarms(nil) - //snippet-end:[cloudwatch.go.describe_alarms.call] + resp, err := svc.DescribeAlarms(nil) + // snippet-end:[cloudwatch.go.describe_alarms.call] - if err != nil { - return nil, err - } + if err != nil { + return nil, err + } - return resp, nil + return resp, nil } func main() { - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file (~/.aws/credentials) - //snippet-start:[cloudwatch.go.describe_alarms.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - //snippet-end:[cloudwatch.go.describe_alarms.session] + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file (~/.aws/credentials) + // snippet-start:[cloudwatch.go.describe_alarms.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[cloudwatch.go.describe_alarms.session] - resp, err := ListAlarms(sess) - if err != nil { - fmt.Println("Got an error listing alarms:") - fmt.Println(err) - return - } + resp, err := ListAlarms(sess) + if err != nil { + fmt.Println("Got an error listing alarms:") + fmt.Println(err) + return + } - //snippet-start:[cloudwatch.go.describe_alarms.display] - fmt.Println("Alarms:") - for _, alarm := range resp.MetricAlarms { - fmt.Println(" " + *alarm.AlarmName) - } - //snippet-end:[cloudwatch.go.describe_alarms.display] + // snippet-start:[cloudwatch.go.describe_alarms.display] + fmt.Println("Alarms:") + for _, alarm := range resp.MetricAlarms { + fmt.Println(" " + *alarm.AlarmName) + } + // snippet-end:[cloudwatch.go.describe_alarms.display] } -//snippet-end:[cloudwatch.go.describe_alarms] + +// snippet-end:[cloudwatch.go.describe_alarms] diff --git a/go/cloudwatch/DescribeAlarms/DescribeAlarms_test.go b/go/cloudwatch/DescribeAlarms/DescribeAlarms_test.go index be45d6cfcc8..085f3b5a6b8 100644 --- a/go/cloudwatch/DescribeAlarms/DescribeAlarms_test.go +++ b/go/cloudwatch/DescribeAlarms/DescribeAlarms_test.go @@ -1,44 +1,33 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "testing" - "time" + "fmt" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/aws/session" ) func TestCloudWatchOps(t *testing.T) { - // When the test started - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Started unit test at " + nowString) - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Show list of alarms - resp, err := ListAlarms(sess) - if err != nil { - t.Fatal(err) - } - - fmt.Println("Alarms:") - for _, alarm := range resp.MetricAlarms { - fmt.Println(" " + *alarm.AlarmName) - } + // When the test started + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Started unit test at " + nowString) + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Show list of alarms + resp, err := ListAlarms(sess) + if err != nil { + t.Fatal(err) + } + + fmt.Println("Alarms:") + for _, alarm := range resp.MetricAlarms { + fmt.Println(" " + *alarm.AlarmName) + } } diff --git a/go/cloudwatch/DisableAlarm/DisableAlarm.go b/go/cloudwatch/DisableAlarm/DisableAlarm.go index 2646d76d244..ff88035e9ae 100644 --- a/go/cloudwatch/DisableAlarm/DisableAlarm.go +++ b/go/cloudwatch/DisableAlarm/DisableAlarm.go @@ -1,79 +1,73 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cloudwatch.go.disable_alarm] package main // snippet-start:[cloudwatch.go.disable_alarm.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatch" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatch" ) + // snippet-end:[cloudwatch.go.disable_alarm.imports] // DisableAlarm disables an alarm // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// alarmName is the name of the alarm +// +// sess is the current session, which provides configuration for the SDK's service clients +// alarmName is the name of the alarm +// // Output: -// If successful, nil -// Otherwise, the error from a call to DisableAlarmActions +// +// If successful, nil +// Otherwise, the error from a call to DisableAlarmActions func DisableAlarm(sess *session.Session, alarmName *string) error { - // Create new CloudWatch client. - // snippet-start:[cloudwatch.go.disable_call] - svc := cloudwatch.New(sess) + // Create new CloudWatch client. + // snippet-start:[cloudwatch.go.disable_call] + svc := cloudwatch.New(sess) - _, err := svc.DisableAlarmActions(&cloudwatch.DisableAlarmActionsInput{ - AlarmNames: []*string{ - alarmName, - }, - }) - // snippet-end:[cloudwatch.go.disable_call] - if err != nil { - return err - } + _, err := svc.DisableAlarmActions(&cloudwatch.DisableAlarmActionsInput{ + AlarmNames: []*string{ + alarmName, + }, + }) + // snippet-end:[cloudwatch.go.disable_call] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[cloudwatch.go.disable_args] - alarmName := flag.String("a", "", "The name of the alarm to disable") - flag.Parse() + // snippet-start:[cloudwatch.go.disable_args] + alarmName := flag.String("a", "", "The name of the alarm to disable") + flag.Parse() - if *alarmName == "" { - fmt.Println("You must supply an alarm name to disable") - return - } - // snippet-end:[cloudwatch.go.disable_args] + if *alarmName == "" { + fmt.Println("You must supply an alarm name to disable") + return + } + // snippet-end:[cloudwatch.go.disable_args] - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - // snippet-start:[cloudwatch.go.disable_session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[cloudwatch.go.disable_session] + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + // snippet-start:[cloudwatch.go.disable_session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[cloudwatch.go.disable_session] - err := DisableAlarm(sess, alarmName) - if err != nil { - fmt.Println("Could not disable alarm " + *alarmName) - } else { - fmt.Println("Disabled alarm " + *alarmName) - } + err := DisableAlarm(sess, alarmName) + if err != nil { + fmt.Println("Could not disable alarm " + *alarmName) + } else { + fmt.Println("Disabled alarm " + *alarmName) + } } + // snippet-end:[cloudwatch.go.disable_alarm] diff --git a/go/cloudwatch/DisableAlarm/DisableAlarm_test.go b/go/cloudwatch/DisableAlarm/DisableAlarm_test.go index 3c0150fa1e4..0aaae27c064 100644 --- a/go/cloudwatch/DisableAlarm/DisableAlarm_test.go +++ b/go/cloudwatch/DisableAlarm/DisableAlarm_test.go @@ -1,37 +1,26 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatch" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/google/uuid" + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatch" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/google/uuid" ) type config struct { - InstanceName string `json:"InstanceName"` - InstanceID string `json:"InstanceID"` - AlarmName string `json:"AlarmName"` + InstanceName string `json:"InstanceName"` + InstanceID string `json:"InstanceID"` + AlarmName string `json:"AlarmName"` } var globalConfig config @@ -39,181 +28,181 @@ var globalConfig config var configFileName = "config.json" func getEc2Info(sess *session.Session, t *testing.T) (string, string, error) { - svc := ec2.New(sess) - - result, err := svc.DescribeInstances(nil) - if err != nil { - return "", "", err - } - - // Return name and ID of the first EC2 instance with both - for _, reservation := range result.Reservations { - for _, instance := range reservation.Instances { - id := instance.InstanceId - name := "" - - // Name is stashed in a tag - for _, tag := range instance.Tags { - if *tag.Key == "Name" { - name = *tag.Value - break - } - } - - if *id != "" && name != "" { - return *id, name, nil - } - } - } - - return "", "", errors.New("No EC2 instance found with name and ID") + svc := ec2.New(sess) + + result, err := svc.DescribeInstances(nil) + if err != nil { + return "", "", err + } + + // Return name and ID of the first EC2 instance with both + for _, reservation := range result.Reservations { + for _, instance := range reservation.Instances { + id := instance.InstanceId + name := "" + + // Name is stashed in a tag + for _, tag := range instance.Tags { + if *tag.Key == "Name" { + name = *tag.Value + break + } + } + + if *id != "" && name != "" { + return *id, name, nil + } + } + } + + return "", "", errors.New("No EC2 instance found with name and ID") } func populateConfig(sess *session.Session, t *testing.T) error { - // Get and store configuration values - // Get configuration from config.json + // Get and store configuration values + // Get configuration from config.json - // Get entire file as a JSON string - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + // Get entire file as a JSON string + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - // Convert []byte to string - text := string(content) + // Convert []byte to string + text := string(content) - // Marshall JSON string in text into global struct - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + // Marshall JSON string in text into global struct + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Instance Name: " + globalConfig.InstanceName) - t.Log("Instance ID: " + globalConfig.InstanceID) - t.Log("Alarm name: " + globalConfig.AlarmName) + t.Log("Instance Name: " + globalConfig.InstanceName) + t.Log("Instance ID: " + globalConfig.InstanceID) + t.Log("Alarm name: " + globalConfig.AlarmName) - return nil + return nil } func enableAlarm(sess *session.Session, instanceName *string, instanceID *string, alarmName *string) error { - // Create new CloudWatch client - svc := cloudwatch.New(sess) - - _, err := svc.PutMetricAlarm(&cloudwatch.PutMetricAlarmInput{ - AlarmName: alarmName, - ComparisonOperator: aws.String(cloudwatch.ComparisonOperatorGreaterThanThreshold), - EvaluationPeriods: aws.Int64(1), - MetricName: aws.String("CPUUtilization"), - Namespace: aws.String("AWS/EC2"), - Period: aws.Int64(60), - Statistic: aws.String(cloudwatch.StatisticAverage), - Threshold: aws.Float64(70.0), - ActionsEnabled: aws.Bool(true), - AlarmDescription: aws.String("Alarm when server CPU exceeds 70%"), - Unit: aws.String(cloudwatch.StandardUnitSeconds), - AlarmActions: []*string{ - aws.String(fmt.Sprintf("arn:aws:swf:"+*svc.Config.Region+":%s:action/actions/AWS_EC2.InstanceId.Reboot/1.0", *instanceName)), - }, - Dimensions: []*cloudwatch.Dimension{ - { - Name: aws.String("InstanceId"), - Value: instanceID, - }, - }, - }) - if err != nil { - return err - } - - // Enable the alarm for the instance - _, err = svc.EnableAlarmActions(&cloudwatch.EnableAlarmActionsInput{ - AlarmNames: []*string{ - instanceID, - }, - }) - if err != nil { - return err - } - - return nil + // Create new CloudWatch client + svc := cloudwatch.New(sess) + + _, err := svc.PutMetricAlarm(&cloudwatch.PutMetricAlarmInput{ + AlarmName: alarmName, + ComparisonOperator: aws.String(cloudwatch.ComparisonOperatorGreaterThanThreshold), + EvaluationPeriods: aws.Int64(1), + MetricName: aws.String("CPUUtilization"), + Namespace: aws.String("AWS/EC2"), + Period: aws.Int64(60), + Statistic: aws.String(cloudwatch.StatisticAverage), + Threshold: aws.Float64(70.0), + ActionsEnabled: aws.Bool(true), + AlarmDescription: aws.String("Alarm when server CPU exceeds 70%"), + Unit: aws.String(cloudwatch.StandardUnitSeconds), + AlarmActions: []*string{ + aws.String(fmt.Sprintf("arn:aws:swf:"+*svc.Config.Region+":%s:action/actions/AWS_EC2.InstanceId.Reboot/1.0", *instanceName)), + }, + Dimensions: []*cloudwatch.Dimension{ + { + Name: aws.String("InstanceId"), + Value: instanceID, + }, + }, + }) + if err != nil { + return err + } + + // Enable the alarm for the instance + _, err = svc.EnableAlarmActions(&cloudwatch.EnableAlarmActionsInput{ + AlarmNames: []*string{ + instanceID, + }, + }) + if err != nil { + return err + } + + return nil } func deleteAlarm(sess *session.Session, alarmName *string) error { - // Create service client - svc := cloudwatch.New(sess) - - _, err := svc.DeleteAlarms(&cloudwatch.DeleteAlarmsInput{ - AlarmNames: []*string{ - alarmName, - }, - }) - if err != nil { - return err - } - - return nil + // Create service client + svc := cloudwatch.New(sess) + + _, err := svc.DeleteAlarms(&cloudwatch.DeleteAlarmsInput{ + AlarmNames: []*string{ + alarmName, + }, + }) + if err != nil { + return err + } + + return nil } func TestDisableAlarmActions(t *testing.T) { - // When the test started - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Started unit test at " + nowString) - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Get configuration values - err := populateConfig(sess, t) - if err != nil { - t.Fatal(err) - } - - createdAlarm := false - - if globalConfig.AlarmName == "" { - // Create random alarm name - id := uuid.New() - globalConfig.AlarmName = "Alarm70-" + id.String() - - if globalConfig.InstanceName == "" || globalConfig.InstanceID == "" { - // Get EC2 instance name and ID - globalConfig.InstanceName, globalConfig.InstanceID, err = getEc2Info(sess, t) - if err != nil { - return - } - } - - // Create an alarm to disable - err = enableAlarm(sess, &globalConfig.InstanceName, &globalConfig.InstanceID, &globalConfig.AlarmName) - if err != nil { - msg := "Could not create alarm " + globalConfig.AlarmName + " for instance " + globalConfig.InstanceName - t.Fatal(msg) - } - - createdAlarm = true - t.Log("Enabled alarm " + globalConfig.AlarmName + " for instance " + globalConfig.InstanceName) - } - - // Disable alarm - err = DisableAlarm(sess, &globalConfig.AlarmName) - if err != nil { - t.Fatal(err) - } - - t.Log("Disabled alarm " + globalConfig.AlarmName) - - if createdAlarm { - // Delete alarm - err = deleteAlarm(sess, &globalConfig.AlarmName) - if err != nil { - t.Fatal(err) - } - - t.Log("Deleted alarm " + globalConfig.AlarmName) - } + // When the test started + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Started unit test at " + nowString) + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Get configuration values + err := populateConfig(sess, t) + if err != nil { + t.Fatal(err) + } + + createdAlarm := false + + if globalConfig.AlarmName == "" { + // Create random alarm name + id := uuid.New() + globalConfig.AlarmName = "Alarm70-" + id.String() + + if globalConfig.InstanceName == "" || globalConfig.InstanceID == "" { + // Get EC2 instance name and ID + globalConfig.InstanceName, globalConfig.InstanceID, err = getEc2Info(sess, t) + if err != nil { + return + } + } + + // Create an alarm to disable + err = enableAlarm(sess, &globalConfig.InstanceName, &globalConfig.InstanceID, &globalConfig.AlarmName) + if err != nil { + msg := "Could not create alarm " + globalConfig.AlarmName + " for instance " + globalConfig.InstanceName + t.Fatal(msg) + } + + createdAlarm = true + t.Log("Enabled alarm " + globalConfig.AlarmName + " for instance " + globalConfig.InstanceName) + } + + // Disable alarm + err = DisableAlarm(sess, &globalConfig.AlarmName) + if err != nil { + t.Fatal(err) + } + + t.Log("Disabled alarm " + globalConfig.AlarmName) + + if createdAlarm { + // Delete alarm + err = deleteAlarm(sess, &globalConfig.AlarmName) + if err != nil { + t.Fatal(err) + } + + t.Log("Deleted alarm " + globalConfig.AlarmName) + } } diff --git a/go/cloudwatch/EnableAlarm/EnableAlarm.go b/go/cloudwatch/EnableAlarm/EnableAlarm.go index c79352e669a..728b9bf8fb6 100644 --- a/go/cloudwatch/EnableAlarm/EnableAlarm.go +++ b/go/cloudwatch/EnableAlarm/EnableAlarm.go @@ -1,115 +1,109 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cloudwatch.go.enable_alarm] package main // snippet-start:[cloudwatch.go.enable_alarm.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatch" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatch" ) + // snippet-end:[cloudwatch.go.enable_alarm.imports] // EnableAlarm creates an alarm that reboots an EC2 instance whenever the CPU utilization is greater than 70% // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// instanceName is the name of the EC2 instance -// instanceID is the ID of the EC2 instance -// alarmName is the name of the alarm +// +// sess is the current session, which provides configuration for the SDK's service clients +// instanceName is the name of the EC2 instance +// instanceID is the ID of the EC2 instance +// alarmName is the name of the alarm +// // Output: -// If successful, nil -// Otherwise, the error from a call to PutMetricAlarm or EnableAlarmActions +// +// If successful, nil +// Otherwise, the error from a call to PutMetricAlarm or EnableAlarmActions func EnableAlarm(sess *session.Session, instanceName *string, instanceID *string, alarmName *string) error { - // Create new CloudWatch client - // snippet-start:[cloudwatch.go.enable_alarm.put] - svc := cloudwatch.New(sess) + // Create new CloudWatch client + // snippet-start:[cloudwatch.go.enable_alarm.put] + svc := cloudwatch.New(sess) - _, err := svc.PutMetricAlarm(&cloudwatch.PutMetricAlarmInput{ - AlarmName: alarmName, - ComparisonOperator: aws.String(cloudwatch.ComparisonOperatorGreaterThanThreshold), - EvaluationPeriods: aws.Int64(1), - MetricName: aws.String("CPUUtilization"), - Namespace: aws.String("AWS/EC2"), - Period: aws.Int64(60), - Statistic: aws.String(cloudwatch.StatisticAverage), - Threshold: aws.Float64(70.0), - ActionsEnabled: aws.Bool(true), - AlarmDescription: aws.String("Alarm when server CPU exceeds 70%"), - Unit: aws.String(cloudwatch.StandardUnitSeconds), - AlarmActions: []*string{ - aws.String(fmt.Sprintf("arn:aws:swf:"+*svc.Config.Region+":%s:action/actions/AWS_EC2.InstanceId.Reboot/1.0", instanceName)), - }, - Dimensions: []*cloudwatch.Dimension{ - { - Name: aws.String("InstanceId"), - Value: instanceID, - }, - }, - }) - // snippet-end:[cloudwatch.go.enable_alarm.put] - if err != nil { - return err - } + _, err := svc.PutMetricAlarm(&cloudwatch.PutMetricAlarmInput{ + AlarmName: alarmName, + ComparisonOperator: aws.String(cloudwatch.ComparisonOperatorGreaterThanThreshold), + EvaluationPeriods: aws.Int64(1), + MetricName: aws.String("CPUUtilization"), + Namespace: aws.String("AWS/EC2"), + Period: aws.Int64(60), + Statistic: aws.String(cloudwatch.StatisticAverage), + Threshold: aws.Float64(70.0), + ActionsEnabled: aws.Bool(true), + AlarmDescription: aws.String("Alarm when server CPU exceeds 70%"), + Unit: aws.String(cloudwatch.StandardUnitSeconds), + AlarmActions: []*string{ + aws.String(fmt.Sprintf("arn:aws:swf:"+*svc.Config.Region+":%s:action/actions/AWS_EC2.InstanceId.Reboot/1.0", instanceName)), + }, + Dimensions: []*cloudwatch.Dimension{ + { + Name: aws.String("InstanceId"), + Value: instanceID, + }, + }, + }) + // snippet-end:[cloudwatch.go.enable_alarm.put] + if err != nil { + return err + } - // Enable the alarm for the instance - // snippet-start:[cloudwatch.go.enable_alarm.enable] - _, err = svc.EnableAlarmActions(&cloudwatch.EnableAlarmActionsInput{ - AlarmNames: []*string{ - instanceID, - }, - }) - // snippet-end:[cloudwatch.go.enable_alarm.enable] - if err != nil { - return err - } + // Enable the alarm for the instance + // snippet-start:[cloudwatch.go.enable_alarm.enable] + _, err = svc.EnableAlarmActions(&cloudwatch.EnableAlarmActionsInput{ + AlarmNames: []*string{ + instanceID, + }, + }) + // snippet-end:[cloudwatch.go.enable_alarm.enable] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[cloudwatch.go.enable_alarm.args] - instanceName := flag.String("n", "", "The instance name") - instanceID := flag.String("i", "", "The instance ID") - alarmName := flag.String("a", "", "The alarm name") - flag.Parse() + // snippet-start:[cloudwatch.go.enable_alarm.args] + instanceName := flag.String("n", "", "The instance name") + instanceID := flag.String("i", "", "The instance ID") + alarmName := flag.String("a", "", "The alarm name") + flag.Parse() - if *instanceName == "" || *instanceID == "" || *alarmName == "" { - fmt.Println("You must supply an instance name, instance ID, and alarm name") - return - } - // snippet-end:[cloudwatch.go.enable_alarm.args] + if *instanceName == "" || *instanceID == "" || *alarmName == "" { + fmt.Println("You must supply an instance name, instance ID, and alarm name") + return + } + // snippet-end:[cloudwatch.go.enable_alarm.args] - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - // snippet-start:[cloudwatch.go.enable_alarm.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[cloudwatch.go.enable_alarm.session] + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + // snippet-start:[cloudwatch.go.enable_alarm.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[cloudwatch.go.enable_alarm.session] - err := EnableAlarm(sess, instanceName, instanceID, alarmName) - if err != nil { - fmt.Println(err) - } + err := EnableAlarm(sess, instanceName, instanceID, alarmName) + if err != nil { + fmt.Println(err) + } - // snippet-start:[cloudwatch.go.enable_alarm.print] - fmt.Println("Enabled alarm " + *alarmName + " for EC2 instance " + *instanceName) - // snippet-end:[cloudwatch.go.enable_alarm.print] + // snippet-start:[cloudwatch.go.enable_alarm.print] + fmt.Println("Enabled alarm " + *alarmName + " for EC2 instance " + *instanceName) + // snippet-end:[cloudwatch.go.enable_alarm.print] } + // snippet-end:[cloudwatch.go.enable_alarm] diff --git a/go/cloudwatch/EnableAlarm/EnableAlarm_test.go b/go/cloudwatch/EnableAlarm/EnableAlarm_test.go index 4a2d613913b..5594f6218d0 100644 --- a/go/cloudwatch/EnableAlarm/EnableAlarm_test.go +++ b/go/cloudwatch/EnableAlarm/EnableAlarm_test.go @@ -1,35 +1,24 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "errors" - "io/ioutil" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatch" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/google/uuid" + "encoding/json" + "errors" + "io/ioutil" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatch" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/google/uuid" ) type config struct { - InstanceName string `json:"InstanceName"` - InstanceID string `json:"InstanceID"` - AlarmName string `json:"AlarmName"` + InstanceName string `json:"InstanceName"` + InstanceID string `json:"InstanceID"` + AlarmName string `json:"AlarmName"` } var globalConfig config @@ -37,151 +26,151 @@ var globalConfig config var configFileName = "config.json" func getEc2Info(sess *session.Session, t *testing.T) (string, string, error) { - svc := ec2.New(sess) - - result, err := svc.DescribeInstances(nil) - if err != nil { - return "", "", err - } - - // Return name and ID of the first EC2 instance with both - for _, reservation := range result.Reservations { - for _, instance := range reservation.Instances { - id := instance.InstanceId - name := "" - - // Name is stashed in a tag - for _, tag := range instance.Tags { - if *tag.Key == "Name" { - name = *tag.Value - break - } - } - - if *id != "" && name != "" { - return *id, name, nil - } - } - } - - return "", "", errors.New("No EC2 instance found with name and ID") + svc := ec2.New(sess) + + result, err := svc.DescribeInstances(nil) + if err != nil { + return "", "", err + } + + // Return name and ID of the first EC2 instance with both + for _, reservation := range result.Reservations { + for _, instance := range reservation.Instances { + id := instance.InstanceId + name := "" + + // Name is stashed in a tag + for _, tag := range instance.Tags { + if *tag.Key == "Name" { + name = *tag.Value + break + } + } + + if *id != "" && name != "" { + return *id, name, nil + } + } + } + + return "", "", errors.New("No EC2 instance found with name and ID") } func populateConfig(sess *session.Session, t *testing.T) error { - // Get and store configuration values - // Get configuration from config.json - - // Get entire file as a JSON string - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } - - // Convert []byte to string - text := string(content) - - // Marshall JSON string in text into global struct - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } - - if globalConfig.InstanceName == "" || globalConfig.InstanceID == "" { - // Get EC2 instance name and ID - globalConfig.InstanceName, globalConfig.InstanceID, err = getEc2Info(sess, t) - if err != nil { - return err - } - } - - t.Log("Instance Name: " + globalConfig.InstanceName) - t.Log("Instance ID: " + globalConfig.InstanceID) - t.Log("Alarm name: " + globalConfig.AlarmName) - - return nil + // Get and store configuration values + // Get configuration from config.json + + // Get entire file as a JSON string + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } + + // Convert []byte to string + text := string(content) + + // Marshall JSON string in text into global struct + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } + + if globalConfig.InstanceName == "" || globalConfig.InstanceID == "" { + // Get EC2 instance name and ID + globalConfig.InstanceName, globalConfig.InstanceID, err = getEc2Info(sess, t) + if err != nil { + return err + } + } + + t.Log("Instance Name: " + globalConfig.InstanceName) + t.Log("Instance ID: " + globalConfig.InstanceID) + t.Log("Alarm name: " + globalConfig.AlarmName) + + return nil } func disableAlarm(sess *session.Session, alarmName *string) error { - // Create new CloudWatch client. - svc := cloudwatch.New(sess) - - _, err := svc.DisableAlarmActions(&cloudwatch.DisableAlarmActionsInput{ - AlarmNames: []*string{ - alarmName, - }, - }) - if err != nil { - return err - } - - return nil + // Create new CloudWatch client. + svc := cloudwatch.New(sess) + + _, err := svc.DisableAlarmActions(&cloudwatch.DisableAlarmActionsInput{ + AlarmNames: []*string{ + alarmName, + }, + }) + if err != nil { + return err + } + + return nil } func deleteAlarm(sess *session.Session, alarmName *string) error { - // Create service client - svc := cloudwatch.New(sess) - - _, err := svc.DeleteAlarms(&cloudwatch.DeleteAlarmsInput{ - AlarmNames: []*string{ - alarmName, - }, - }) - if err != nil { - return err - } - - return nil + // Create service client + svc := cloudwatch.New(sess) + + _, err := svc.DeleteAlarms(&cloudwatch.DeleteAlarmsInput{ + AlarmNames: []*string{ + alarmName, + }, + }) + if err != nil { + return err + } + + return nil } func TestDisableAlarmActions(t *testing.T) { - // When the test started - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Started unit test at " + nowString) - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Get configuration values - err := populateConfig(sess, t) - if err != nil { - t.Fatal(err) - } - - createdAlarm := false - - if globalConfig.AlarmName == "" { - // Create random alarm name - id := uuid.New() - globalConfig.AlarmName = "Alarm70-" + id.String() - createdAlarm = true - } - - err = EnableAlarm(sess, &globalConfig.InstanceName, &globalConfig.InstanceID, &globalConfig.AlarmName) - if err != nil { - msg := "Could not create alarm " + globalConfig.AlarmName + " for instance " + globalConfig.InstanceName - t.Fatal(msg) - } - - t.Log("Enabled alarm " + globalConfig.AlarmName + " for instance " + globalConfig.InstanceName) - - if createdAlarm { - err = disableAlarm(sess, &globalConfig.AlarmName) - if err != nil { - t.Fatal(err) - } - - t.Log("Disabled alarm " + globalConfig.AlarmName) - - err = deleteAlarm(sess, &globalConfig.AlarmName) - if err != nil { - t.Fatal(err) - } - - t.Log("Deleted alarm " + globalConfig.AlarmName) - } + // When the test started + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Started unit test at " + nowString) + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Get configuration values + err := populateConfig(sess, t) + if err != nil { + t.Fatal(err) + } + + createdAlarm := false + + if globalConfig.AlarmName == "" { + // Create random alarm name + id := uuid.New() + globalConfig.AlarmName = "Alarm70-" + id.String() + createdAlarm = true + } + + err = EnableAlarm(sess, &globalConfig.InstanceName, &globalConfig.InstanceID, &globalConfig.AlarmName) + if err != nil { + msg := "Could not create alarm " + globalConfig.AlarmName + " for instance " + globalConfig.InstanceName + t.Fatal(msg) + } + + t.Log("Enabled alarm " + globalConfig.AlarmName + " for instance " + globalConfig.InstanceName) + + if createdAlarm { + err = disableAlarm(sess, &globalConfig.AlarmName) + if err != nil { + t.Fatal(err) + } + + t.Log("Disabled alarm " + globalConfig.AlarmName) + + err = deleteAlarm(sess, &globalConfig.AlarmName) + if err != nil { + t.Fatal(err) + } + + t.Log("Deleted alarm " + globalConfig.AlarmName) + } } diff --git a/go/cloudwatch/GetLogEvents/GetLogEvents.go b/go/cloudwatch/GetLogEvents/GetLogEvents.go index 270e4119fe3..ec992f60310 100644 --- a/go/cloudwatch/GetLogEvents/GetLogEvents.go +++ b/go/cloudwatch/GetLogEvents/GetLogEvents.go @@ -1,97 +1,91 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cloudwatch.go.getlogevents] package main // snippet-start:[cloudwatch.go.getlogevents.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatchlogs" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatchlogs" ) + // snippet-end:[cloudwatch.go.getlogevents.imports] // GetLogEvents retrieves CloudWatchLog events. // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// limit is the maximum number of log events to retrieve -// logGroupName is the name of the log group -// logStreamName is the name of the log stream +// +// sess is the current session, which provides configuration for the SDK's service clients +// limit is the maximum number of log events to retrieve +// logGroupName is the name of the log group +// logStreamName is the name of the log stream +// // Output: -// If success, a GetLogEventsOutput object containing the events and nil -// Otherwise, nil and an error from the call to GetLogEvents +// +// If success, a GetLogEventsOutput object containing the events and nil +// Otherwise, nil and an error from the call to GetLogEvents func GetLogEvents(sess *session.Session, limit *int64, logGroupName *string, logStreamName *string) (*cloudwatchlogs.GetLogEventsOutput, error) { - // snippet-start:[cloudwatch.go.getlogevents.call] - svc := cloudwatchlogs.New(sess) - - resp, err := svc.GetLogEvents(&cloudwatchlogs.GetLogEventsInput{ - Limit: limit, - LogGroupName: logGroupName, - LogStreamName: logStreamName, - }) - // snippet-end:[cloudwatch.go.getlogevents.call] - if err != nil { - return nil, err - } - - return resp, nil + // snippet-start:[cloudwatch.go.getlogevents.call] + svc := cloudwatchlogs.New(sess) + + resp, err := svc.GetLogEvents(&cloudwatchlogs.GetLogEventsInput{ + Limit: limit, + LogGroupName: logGroupName, + LogStreamName: logStreamName, + }) + // snippet-end:[cloudwatch.go.getlogevents.call] + if err != nil { + return nil, err + } + + return resp, nil } func main() { - // snippet-start:[cloudwatch.go.getlogevents.args] - limit := flag.Int64("l", 100, "The maximum number of events to retrieve") - logGroupName := flag.String("g", "", "The name of the log group") - logStreamName := flag.String("s", "", "The name of the log stream") - flag.Parse() - - if *logGroupName == "" || *logStreamName == "" { - fmt.Println("You must supply a log group name (-g LOG-GROUP) and log stream name (-s LOG-STREAM)") - return - } - // snippet-end:[cloudwatch.go.getlogevents.args] - - // snippet-start:[cloudwatch.go.getlogevents.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[cloudwatch.go.getlogevents.session] - - resp, err := GetLogEvents(sess, limit, logGroupName, logStreamName) - if err != nil { - fmt.Println("Got error getting log events:") - fmt.Println(err) - return - } - - // snippet-start:[cloudwatch.go.getlogevents.print] - fmt.Println("Event messages for stream " + *logStreamName + " in log group " + *logGroupName) - - gotToken := "" - nextToken := "" - - for _, event := range resp.Events { - gotToken = nextToken - nextToken = *resp.NextForwardToken - - if gotToken == nextToken { - break - } - - fmt.Println(" ", *event.Message) - // snippet-end:[cloudwatch.go.getlogevents.print] - } + // snippet-start:[cloudwatch.go.getlogevents.args] + limit := flag.Int64("l", 100, "The maximum number of events to retrieve") + logGroupName := flag.String("g", "", "The name of the log group") + logStreamName := flag.String("s", "", "The name of the log stream") + flag.Parse() + + if *logGroupName == "" || *logStreamName == "" { + fmt.Println("You must supply a log group name (-g LOG-GROUP) and log stream name (-s LOG-STREAM)") + return + } + // snippet-end:[cloudwatch.go.getlogevents.args] + + // snippet-start:[cloudwatch.go.getlogevents.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[cloudwatch.go.getlogevents.session] + + resp, err := GetLogEvents(sess, limit, logGroupName, logStreamName) + if err != nil { + fmt.Println("Got error getting log events:") + fmt.Println(err) + return + } + + // snippet-start:[cloudwatch.go.getlogevents.print] + fmt.Println("Event messages for stream " + *logStreamName + " in log group " + *logGroupName) + + gotToken := "" + nextToken := "" + + for _, event := range resp.Events { + gotToken = nextToken + nextToken = *resp.NextForwardToken + + if gotToken == nextToken { + break + } + + fmt.Println(" ", *event.Message) + // snippet-end:[cloudwatch.go.getlogevents.print] + } } + // snippet-end:[cloudwatch.go.getlogevents] diff --git a/go/cloudwatch/GetLogEvents/GetLogEvents_test.go b/go/cloudwatch/GetLogEvents/GetLogEvents_test.go index d52b73ca816..20e93cf9a47 100644 --- a/go/cloudwatch/GetLogEvents/GetLogEvents_test.go +++ b/go/cloudwatch/GetLogEvents/GetLogEvents_test.go @@ -1,32 +1,21 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "strconv" - "testing" + "encoding/json" + "io/ioutil" + "strconv" + "testing" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatchlogs" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatchlogs" ) type Config struct { - Limit int64 `json:"Limit"` - LogGroupName string `json:"LogGroupName"` - LogStreamName string `json:"LogStreamName"` + Limit int64 `json:"Limit"` + LogGroupName string `json:"LogGroupName"` + LogStreamName string `json:"LogStreamName"` } var configFileName = "config.json" @@ -34,101 +23,101 @@ var configFileName = "config.json" var globalConfig Config func getLogGroupStreamNames(sess *session.Session, groupIndex int) (string, string, error) { - svc := cloudwatchlogs.New(sess) + svc := cloudwatchlogs.New(sess) - resp, err := svc.DescribeLogGroups(nil) - if err != nil { - return "", "", err - } + resp, err := svc.DescribeLogGroups(nil) + if err != nil { + return "", "", err + } - if groupIndex < len(resp.LogGroups) { - logGroupName := resp.LogGroups[groupIndex].LogGroupName + if groupIndex < len(resp.LogGroups) { + logGroupName := resp.LogGroups[groupIndex].LogGroupName - result, err := svc.DescribeLogStreams(&cloudwatchlogs.DescribeLogStreamsInput{ - LogGroupName: logGroupName, - }) - if err != nil { - return "", "", err - } + result, err := svc.DescribeLogStreams(&cloudwatchlogs.DescribeLogStreamsInput{ + LogGroupName: logGroupName, + }) + if err != nil { + return "", "", err + } - return *logGroupName, *result.LogStreams[0].LogStreamName, nil - } + return *logGroupName, *result.LogStreams[0].LogStreamName, nil + } - return "", "", nil + return "", "", nil } func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Limit: " + strconv.Itoa(int(globalConfig.Limit))) - t.Log("LogGroupName: " + globalConfig.LogGroupName) - t.Log("LogStreamName: " + globalConfig.LogStreamName) + t.Log("Limit: " + strconv.Itoa(int(globalConfig.Limit))) + t.Log("LogGroupName: " + globalConfig.LogGroupName) + t.Log("LogStreamName: " + globalConfig.LogStreamName) - return nil + return nil } func TestGetLogEvents(t *testing.T) { - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - if globalConfig.Limit < 1 { - globalConfig.Limit = 1 - } - - if globalConfig.Limit > 100 { - globalConfig.Limit = 100 - } - - logGroupIndex := 0 - gotEvents := false - var Resp *cloudwatchlogs.GetLogEventsOutput - - for !gotEvents { - globalConfig.LogGroupName, globalConfig.LogStreamName, err = getLogGroupStreamNames(sess, logGroupIndex) - if err != nil { - t.Fatal(err) - } - - Resp, err = GetLogEvents(sess, &globalConfig.Limit, &globalConfig.LogGroupName, &globalConfig.LogStreamName) - if err != nil { - t.Fatal(err) - } - - length := len(Resp.Events) - - if length > 0 { - gotEvents = true - } else { - globalConfig.LogGroupName = "" - globalConfig.LogStreamName = "" - gotEvents = false - logGroupIndex++ - } - } - - t.Log("Event messages for stream " + globalConfig.LogStreamName + " in log group " + globalConfig.LogGroupName) - - for _, event := range Resp.Events { - if nil != event.Message { - t.Log(" ", *event.Message) - } - } - - t.Log("Got " + strconv.Itoa(len(Resp.Events)) + " event(s) for log stream " + globalConfig.LogStreamName + " in log group " + globalConfig.LogGroupName) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + if globalConfig.Limit < 1 { + globalConfig.Limit = 1 + } + + if globalConfig.Limit > 100 { + globalConfig.Limit = 100 + } + + logGroupIndex := 0 + gotEvents := false + var Resp *cloudwatchlogs.GetLogEventsOutput + + for !gotEvents { + globalConfig.LogGroupName, globalConfig.LogStreamName, err = getLogGroupStreamNames(sess, logGroupIndex) + if err != nil { + t.Fatal(err) + } + + Resp, err = GetLogEvents(sess, &globalConfig.Limit, &globalConfig.LogGroupName, &globalConfig.LogStreamName) + if err != nil { + t.Fatal(err) + } + + length := len(Resp.Events) + + if length > 0 { + gotEvents = true + } else { + globalConfig.LogGroupName = "" + globalConfig.LogStreamName = "" + gotEvents = false + logGroupIndex++ + } + } + + t.Log("Event messages for stream " + globalConfig.LogStreamName + " in log group " + globalConfig.LogGroupName) + + for _, event := range Resp.Events { + if nil != event.Message { + t.Log(" ", *event.Message) + } + } + + t.Log("Got " + strconv.Itoa(len(Resp.Events)) + " event(s) for log stream " + globalConfig.LogStreamName + " in log group " + globalConfig.LogGroupName) } diff --git a/go/cloudwatch/Lambda/main.go b/go/cloudwatch/Lambda/main.go index 08b54f5b640..02300e3d1af 100644 --- a/go/cloudwatch/Lambda/main.go +++ b/go/cloudwatch/Lambda/main.go @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cloudwatch.go.lambda_main] package main diff --git a/go/cloudwatch/Lambda/packageLambda.sh b/go/cloudwatch/Lambda/packageLambda.sh index 51c1054a7e3..7294503985c 100644 --- a/go/cloudwatch/Lambda/packageLambda.sh +++ b/go/cloudwatch/Lambda/packageLambda.sh @@ -1,4 +1,6 @@ #!/usr/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 # Build and zip up Lambda code in main.go GOOS=linux diff --git a/go/cloudwatch/ListMetrics/ListMetrics.go b/go/cloudwatch/ListMetrics/ListMetrics.go index 5bf07a00183..b0097dff619 100644 --- a/go/cloudwatch/ListMetrics/ListMetrics.go +++ b/go/cloudwatch/ListMetrics/ListMetrics.go @@ -1,82 +1,76 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cloudwatch.go.list_metrice] package main // snippet-start:[cloudwatch.go.list_metrice.imports] import ( - "fmt" - "strconv" + "fmt" + "strconv" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatch" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatch" ) + // snippet-end:[cloudwatch.go.list_metrice.imports] // GetMetrics gets the name, namespace, and dimension name of your Amazon CloudWatch metrics // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients +// +// sess is the current session, which provides configuration for the SDK's service clients +// // Output: -// If successful, the metrics and nil -// Otherwise, nil and an error from a call to ListMetrics +// +// If successful, the metrics and nil +// Otherwise, nil and an error from a call to ListMetrics func GetMetrics(sess *session.Session) (*cloudwatch.ListMetricsOutput, error) { - // snippet-start:[cloudwatch.go.list_metrice.call] - // Create CloudWatch client - svc := cloudwatch.New(sess) + // snippet-start:[cloudwatch.go.list_metrice.call] + // Create CloudWatch client + svc := cloudwatch.New(sess) - result, err := svc.ListMetrics(nil) - // snippet-end:[cloudwatch.go.list_metrice.call] - if err != nil { - return nil, err - } + result, err := svc.ListMetrics(nil) + // snippet-end:[cloudwatch.go.list_metrice.call] + if err != nil { + return nil, err + } - return result, nil + return result, nil } func main() { - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - // snippet-start:[cloudwatch.go.list_metrice.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[cloudwatch.go.list_metrice.session] - - result, err := GetMetrics(sess) - if err != nil { - fmt.Println("Could not get metrics") - return - } + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + // snippet-start:[cloudwatch.go.list_metrice.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[cloudwatch.go.list_metrice.session] + + result, err := GetMetrics(sess) + if err != nil { + fmt.Println("Could not get metrics") + return + } - // snippet-start:[cloudwatch.go.list_metrice.print] - fmt.Println("Metrics:") - numMetrics := 0 + // snippet-start:[cloudwatch.go.list_metrice.print] + fmt.Println("Metrics:") + numMetrics := 0 - for _, m := range result.Metrics { - fmt.Println(" Metric Name: " + *m.MetricName) - fmt.Println(" Namespace: " + *m.Namespace) - fmt.Println(" Dimensions:") - for _, d := range m.Dimensions { - fmt.Println(" " + *d.Name + ": " + *d.Value) - } + for _, m := range result.Metrics { + fmt.Println(" Metric Name: " + *m.MetricName) + fmt.Println(" Namespace: " + *m.Namespace) + fmt.Println(" Dimensions:") + for _, d := range m.Dimensions { + fmt.Println(" " + *d.Name + ": " + *d.Value) + } - fmt.Println("") - numMetrics++ - } + fmt.Println("") + numMetrics++ + } - fmt.Println("Found " + strconv.Itoa(numMetrics) + " metrics") - // snippet-end:[cloudwatch.go.list_metrice.print] + fmt.Println("Found " + strconv.Itoa(numMetrics) + " metrics") + // snippet-end:[cloudwatch.go.list_metrice.print] } -// snippet-end:[cloudwatch.go.list_metrice] \ No newline at end of file + +// snippet-end:[cloudwatch.go.list_metrice] diff --git a/go/cloudwatch/ListMetrics/ListMetrics_test.go b/go/cloudwatch/ListMetrics/ListMetrics_test.go index 924e7e5e76d..447f1922476 100644 --- a/go/cloudwatch/ListMetrics/ListMetrics_test.go +++ b/go/cloudwatch/ListMetrics/ListMetrics_test.go @@ -1,45 +1,34 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "strconv" - "testing" - "time" + "strconv" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/aws/session" ) func TestCloudWatchOps(t *testing.T) { - // When the test started - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Started unit test at " + nowString) - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Show list of metrics - result, err := GetMetrics(sess) - if err != nil { - t.Fatal(err) - } - - numMetrics := len(result.Metrics) - t.Log("Found " + strconv.Itoa(numMetrics) + " metrics") + // When the test started + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Started unit test at " + nowString) + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Show list of metrics + result, err := GetMetrics(sess) + if err != nil { + t.Fatal(err) + } + + numMetrics := len(result.Metrics) + t.Log("Found " + strconv.Itoa(numMetrics) + " metrics") } diff --git a/go/cloudwatch/SendEvent/SendEvent.go b/go/cloudwatch/SendEvent/SendEvent.go index b12ee32b529..dcbd2558773 100644 --- a/go/cloudwatch/SendEvent/SendEvent.go +++ b/go/cloudwatch/SendEvent/SendEvent.go @@ -1,143 +1,135 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cloudwatch.go.create_event] package main // snippet-start:[cloudwatch.go.create_event.imports] import ( - "encoding/json" - "flag" - "fmt" - "io/ioutil" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatchevents" + "encoding/json" + "flag" + "fmt" + "io/ioutil" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatchevents" ) + // snippet-end:[cloudwatch.go.create_event.imports] // Event represents the information for a new event // snippet-start:[cloudwatch.go.create_event.event_struct] type Event struct { - Details []struct { - Key string `json:"Key"` - Value string `json:"Value"` - } `json:"Details"` - DetailType string `json:"DetailType"` - Source string `json:"Source"` + Details []struct { + Key string `json:"Key"` + Value string `json:"Value"` + } `json:"Details"` + DetailType string `json:"DetailType"` + Source string `json:"Source"` } var eventFile = "event.json" func getEventInfo() (Event, error) { - var e Event + var e Event - content, err := ioutil.ReadFile(eventFile) - if err != nil { - return e, err - } + content, err := ioutil.ReadFile(eventFile) + if err != nil { + return e, err + } - // Convert []byte to string - text := string(content) + // Convert []byte to string + text := string(content) - // Marshall JSON string in text into global struct - err = json.Unmarshal([]byte(text), &e) - if err != nil { - return e, err - } + // Marshall JSON string in text into global struct + err = json.Unmarshal([]byte(text), &e) + if err != nil { + return e, err + } - // Make sure we got the info we need - if e.DetailType == "" { - e.DetailType = "appRequestSubmitted" - } + // Make sure we got the info we need + if e.DetailType == "" { + e.DetailType = "appRequestSubmitted" + } - if e.Source == "" { - e.Source = "com.mycompany.myapp" - } + if e.Source == "" { + e.Source = "com.mycompany.myapp" + } - if e.Details == nil { - d := []byte(`"{ "key1": "value1", "key2": "value2" }`) - e.DetailType = string(d[:]) - } + if e.Details == nil { + d := []byte(`"{ "key1": "value1", "key2": "value2" }`) + e.DetailType = string(d[:]) + } - return e, nil + return e, nil } + // snippet-end:[cloudwatch.go.create_event.event_struct] // CreateEvent creates an event func CreateEvent(sess *session.Session, lambdaARN *string, event Event) error { - myDetails := "{ " - for _, d := range event.Details { - myDetails = myDetails + "\"" + d.Key + "\": \"" + d.Value + "\"," - } - - myDetails = myDetails + " }" - - // snippet-start:[cloudwatch.go.create_event.call] - svc := cloudwatchevents.New(sess) - - _, err := svc.PutEvents(&cloudwatchevents.PutEventsInput{ - Entries: []*cloudwatchevents.PutEventsRequestEntry{ - &cloudwatchevents.PutEventsRequestEntry{ - Detail: aws.String(myDetails), - DetailType: aws.String(event.DetailType), - Resources: []*string{ - lambdaARN, - }, - Source: aws.String(event.Source), - }, - }, - }) - // snippet-end:[cloudwatch.go.create_event.call] - if err != nil { - return err - } - - return nil + myDetails := "{ " + for _, d := range event.Details { + myDetails = myDetails + "\"" + d.Key + "\": \"" + d.Value + "\"," + } + + myDetails = myDetails + " }" + + // snippet-start:[cloudwatch.go.create_event.call] + svc := cloudwatchevents.New(sess) + + _, err := svc.PutEvents(&cloudwatchevents.PutEventsInput{ + Entries: []*cloudwatchevents.PutEventsRequestEntry{ + &cloudwatchevents.PutEventsRequestEntry{ + Detail: aws.String(myDetails), + DetailType: aws.String(event.DetailType), + Resources: []*string{ + lambdaARN, + }, + Source: aws.String(event.Source), + }, + }, + }) + // snippet-end:[cloudwatch.go.create_event.call] + if err != nil { + return err + } + + return nil } func main() { - // snippet-start:[cloudwatch.go.create_event.args] - lambdaARN := flag.String("l", "", "The ARN of the Lambda function") - flag.Parse() - - if *lambdaARN == "" { - fmt.Println("You must supply a Lambda ARN with -l LAMBDA-ARN") - return - } - // snippet-end:[cloudwatch.go.create_event.args] - - // snippet-start:[cloudwatch.go.create_event.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[cloudwatch.go.create_event.session] - - event, err := getEventInfo() - if err != nil { - fmt.Println("Got an error calling getEventInfo:") - fmt.Println(err) - return - } - - err = CreateEvent(sess, lambdaARN, event) - if err != nil { - fmt.Println("Could not create event:") - fmt.Println(err) - return - } - - fmt.Println("Created event") + // snippet-start:[cloudwatch.go.create_event.args] + lambdaARN := flag.String("l", "", "The ARN of the Lambda function") + flag.Parse() + + if *lambdaARN == "" { + fmt.Println("You must supply a Lambda ARN with -l LAMBDA-ARN") + return + } + // snippet-end:[cloudwatch.go.create_event.args] + + // snippet-start:[cloudwatch.go.create_event.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[cloudwatch.go.create_event.session] + + event, err := getEventInfo() + if err != nil { + fmt.Println("Got an error calling getEventInfo:") + fmt.Println(err) + return + } + + err = CreateEvent(sess, lambdaARN, event) + if err != nil { + fmt.Println("Could not create event:") + fmt.Println(err) + return + } + + fmt.Println("Created event") } + // snippet-end:[cloudwatch.go.create_event] diff --git a/go/cloudwatch/SendEvent/SendEvent_test.go b/go/cloudwatch/SendEvent/SendEvent_test.go index 4f77914eeea..b75e4e2236d 100644 --- a/go/cloudwatch/SendEvent/SendEvent_test.go +++ b/go/cloudwatch/SendEvent/SendEvent_test.go @@ -1,46 +1,35 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "errors" - "io/ioutil" - "strconv" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatchevents" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/google/uuid" + "encoding/json" + "errors" + "io/ioutil" + "strconv" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatchevents" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/google/uuid" ) // Config represents the information for the test type Config struct { - LambdaARN string `json:"LambdaARN"` - PolicyName string `json:"PolicyName"` - PolicyWait int `json:"PolicyWait"` - RoleARN string `json:"RoleARN"` - RoleName string `json:"RoleName"` - RoleWait int `json:"RoleWait"` - RuleName string `json:"RuleName"` - Schedule string `json:"Schedule"` - TargetID string `json:"TargetID"` - TargetWait int `json:"TargetWait"` + LambdaARN string `json:"LambdaARN"` + PolicyName string `json:"PolicyName"` + PolicyWait int `json:"PolicyWait"` + RoleARN string `json:"RoleARN"` + RoleName string `json:"RoleName"` + RoleWait int `json:"RoleWait"` + RuleName string `json:"RuleName"` + Schedule string `json:"Schedule"` + TargetID string `json:"TargetID"` + TargetWait int `json:"TargetWait"` } var configFileName = "config.json" @@ -48,68 +37,68 @@ var configFileName = "config.json" var globalConfig Config func populateConfig(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } - - text := string(content) - - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } - - id := uuid.New() - - if globalConfig.PolicyName == "" { - globalConfig.PolicyName = "TestPolicy-" + id.String() - } - - if globalConfig.RoleName == "" { - globalConfig.RoleName = "TestRole-" + id.String() - } - - if globalConfig.RuleName == "" { - globalConfig.RuleName = "TestRule-" + id.String() - } - - if globalConfig.Schedule == "" { - globalConfig.Schedule = "rate(5 minutes)" - } - - if globalConfig.TargetID == "" { - globalConfig.TargetID = "TestTarget-" + id.String() - } - - t.Log("LambdaARN: " + globalConfig.LambdaARN) - t.Log("PolicyName: " + globalConfig.PolicyName) - t.Log("PolicyWait: " + strconv.Itoa(int(globalConfig.PolicyWait))) - t.Log("RoleARN: " + globalConfig.RoleARN) - t.Log("RoleName: " + globalConfig.RoleName) - t.Log("RoleWait: " + strconv.Itoa(int(globalConfig.RoleWait))) - t.Log("RuleName: " + globalConfig.RuleName) - t.Log("Schedule: " + globalConfig.Schedule) - t.Log("TargetID: " + globalConfig.TargetID) - t.Log("TargetWait: " + strconv.Itoa(int(globalConfig.TargetWait))) - - if globalConfig.LambdaARN == "" { - return errors.New("No Lambda ARN was configured") - } - - return nil + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } + + text := string(content) + + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } + + id := uuid.New() + + if globalConfig.PolicyName == "" { + globalConfig.PolicyName = "TestPolicy-" + id.String() + } + + if globalConfig.RoleName == "" { + globalConfig.RoleName = "TestRole-" + id.String() + } + + if globalConfig.RuleName == "" { + globalConfig.RuleName = "TestRule-" + id.String() + } + + if globalConfig.Schedule == "" { + globalConfig.Schedule = "rate(5 minutes)" + } + + if globalConfig.TargetID == "" { + globalConfig.TargetID = "TestTarget-" + id.String() + } + + t.Log("LambdaARN: " + globalConfig.LambdaARN) + t.Log("PolicyName: " + globalConfig.PolicyName) + t.Log("PolicyWait: " + strconv.Itoa(int(globalConfig.PolicyWait))) + t.Log("RoleARN: " + globalConfig.RoleARN) + t.Log("RoleName: " + globalConfig.RoleName) + t.Log("RoleWait: " + strconv.Itoa(int(globalConfig.RoleWait))) + t.Log("RuleName: " + globalConfig.RuleName) + t.Log("Schedule: " + globalConfig.Schedule) + t.Log("TargetID: " + globalConfig.TargetID) + t.Log("TargetWait: " + strconv.Itoa(int(globalConfig.TargetWait))) + + if globalConfig.LambdaARN == "" { + return errors.New("No Lambda ARN was configured") + } + + return nil } func multiplyDuration(factor int64, d time.Duration) time.Duration { - return time.Duration(factor) * d + return time.Duration(factor) * d } func createRole(t *testing.T, sess *session.Session, roleName *string, policyName *string) (*iam.CreateRoleOutput, string, error) { - // Create the service client - svc := iam.New(sess) + // Create the service client + svc := iam.New(sess) - // From: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/cw-example-sending-events.html - rolePolicy := []byte(`{ + // From: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/cw-example-sending-events.html + rolePolicy := []byte(`{ "Version": "2012-10-17", "Statement": [ { @@ -127,30 +116,30 @@ func createRole(t *testing.T, sess *session.Session, roleName *string, policyNam ] }`) - policy := string(rolePolicy[:]) + policy := string(rolePolicy[:]) - createPolicyResult, err := svc.CreatePolicy(&iam.CreatePolicyInput{ - PolicyDocument: &policy, - PolicyName: policyName, - }) - if err != nil { - return nil, "", err - } + createPolicyResult, err := svc.CreatePolicy(&iam.CreatePolicyInput{ + PolicyDocument: &policy, + PolicyName: policyName, + }) + if err != nil { + return nil, "", err + } - policyARN := createPolicyResult.Policy.Arn + policyARN := createPolicyResult.Policy.Arn - err = svc.WaitUntilPolicyExists(&iam.GetPolicyInput{ - PolicyArn: policyARN, - }) - if err != nil { - return nil, "", err - } + err = svc.WaitUntilPolicyExists(&iam.GetPolicyInput{ + PolicyArn: policyARN, + }) + if err != nil { + return nil, "", err + } - t.Log("Waiting " + strconv.Itoa(globalConfig.PolicyWait) + " seconds for policy to be created") - ts := multiplyDuration(int64(globalConfig.PolicyWait), time.Second) - time.Sleep(ts) + t.Log("Waiting " + strconv.Itoa(globalConfig.PolicyWait) + " seconds for policy to be created") + ts := multiplyDuration(int64(globalConfig.PolicyWait), time.Second) + time.Sleep(ts) - trustRelationship := []byte(`{ + trustRelationship := []byte(`{ "Version": "2012-10-17", "Statement": [ { @@ -163,218 +152,218 @@ func createRole(t *testing.T, sess *session.Session, roleName *string, policyNam ] }`) - trustPolicy := string(trustRelationship[:]) - - createRoleResult, err := svc.CreateRole(&iam.CreateRoleInput{ - AssumeRolePolicyDocument: aws.String(trustPolicy), - RoleName: roleName, - }) - if err != nil { - return nil, "", err - } - - err = svc.WaitUntilRoleExists(&iam.GetRoleInput{ - RoleName: roleName, - }) - if err != nil { - return nil, "", err - } - - t.Log("Waiting " + strconv.Itoa(globalConfig.RoleWait) + " seconds for role to be created") - ts = multiplyDuration(int64(globalConfig.RoleWait), time.Second) - time.Sleep(ts) - - _, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{ - PolicyArn: policyARN, - RoleName: roleName, - }) - if err != nil { - return nil, "", err - } - - return createRoleResult, *policyARN, nil + trustPolicy := string(trustRelationship[:]) + + createRoleResult, err := svc.CreateRole(&iam.CreateRoleInput{ + AssumeRolePolicyDocument: aws.String(trustPolicy), + RoleName: roleName, + }) + if err != nil { + return nil, "", err + } + + err = svc.WaitUntilRoleExists(&iam.GetRoleInput{ + RoleName: roleName, + }) + if err != nil { + return nil, "", err + } + + t.Log("Waiting " + strconv.Itoa(globalConfig.RoleWait) + " seconds for role to be created") + ts = multiplyDuration(int64(globalConfig.RoleWait), time.Second) + time.Sleep(ts) + + _, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{ + PolicyArn: policyARN, + RoleName: roleName, + }) + if err != nil { + return nil, "", err + } + + return createRoleResult, *policyARN, nil } func createRule(sess *session.Session, ruleName *string, roleARN *string, schedule *string) (*cloudwatchevents.PutRuleOutput, error) { - svc := cloudwatchevents.New(sess) - - result, err := svc.PutRule(&cloudwatchevents.PutRuleInput{ - Name: ruleName, - RoleArn: roleARN, - ScheduleExpression: schedule, - }) - if err != nil { - return nil, err - } - - return result, nil + svc := cloudwatchevents.New(sess) + + result, err := svc.PutRule(&cloudwatchevents.PutRuleInput{ + Name: ruleName, + RoleArn: roleARN, + ScheduleExpression: schedule, + }) + if err != nil { + return nil, err + } + + return result, nil } func createTarget(sess *session.Session, rule *string, lambdaARN *string, targetID *string) error { - // Create the service client - svc := cloudwatchevents.New(sess) - - _, err := svc.PutTargets(&cloudwatchevents.PutTargetsInput{ - Rule: rule, - Targets: []*cloudwatchevents.Target{ - &cloudwatchevents.Target{ - Arn: lambdaARN, - Id: targetID, - }, - }, - }) - if err != nil { - return err - } - - return nil + // Create the service client + svc := cloudwatchevents.New(sess) + + _, err := svc.PutTargets(&cloudwatchevents.PutTargetsInput{ + Rule: rule, + Targets: []*cloudwatchevents.Target{ + &cloudwatchevents.Target{ + Arn: lambdaARN, + Id: targetID, + }, + }, + }) + if err != nil { + return err + } + + return nil } func deleteTargets(t *testing.T, sess *session.Session, rule *string) error { - svc := cloudwatchevents.New(sess) - - // Get targets so we can remove them - resp, err := svc.ListTargetsByRule(&cloudwatchevents.ListTargetsByRuleInput{ - Rule: rule, - }) - if err != nil { - return err - } - - // Build list of target IDs - var targetIDs []*string - for _, target := range resp.Targets { - targetIDs = append(targetIDs, target.Id) - } - - // Now remove targets - _, err = svc.RemoveTargets(&cloudwatchevents.RemoveTargetsInput{ - Ids: targetIDs, - Rule: rule, - }) - if err != nil { - return err - } - - return nil + svc := cloudwatchevents.New(sess) + + // Get targets so we can remove them + resp, err := svc.ListTargetsByRule(&cloudwatchevents.ListTargetsByRuleInput{ + Rule: rule, + }) + if err != nil { + return err + } + + // Build list of target IDs + var targetIDs []*string + for _, target := range resp.Targets { + targetIDs = append(targetIDs, target.Id) + } + + // Now remove targets + _, err = svc.RemoveTargets(&cloudwatchevents.RemoveTargetsInput{ + Ids: targetIDs, + Rule: rule, + }) + if err != nil { + return err + } + + return nil } func deleteRule(sess *session.Session, ruleName *string) error { - // Create the service client - svc := cloudwatchevents.New(sess) + // Create the service client + svc := cloudwatchevents.New(sess) - _, err := svc.DeleteRule(&cloudwatchevents.DeleteRuleInput{ - Name: ruleName, - }) - if err != nil { - return err - } + _, err := svc.DeleteRule(&cloudwatchevents.DeleteRuleInput{ + Name: ruleName, + }) + if err != nil { + return err + } - return nil + return nil } func detachPolicy(sess *session.Session, policyARN *string, roleName *string) error { - svc := iam.New(sess) + svc := iam.New(sess) - _, err := svc.DetachRolePolicy(&iam.DetachRolePolicyInput{ - PolicyArn: policyARN, - RoleName: roleName, - }) - if err != nil { - return err - } + _, err := svc.DetachRolePolicy(&iam.DetachRolePolicyInput{ + PolicyArn: policyARN, + RoleName: roleName, + }) + if err != nil { + return err + } - return nil + return nil } func deleteRole(sess *session.Session, roleName *string) error { - svc := iam.New(sess) + svc := iam.New(sess) - _, err := svc.DeleteRole(&iam.DeleteRoleInput{ - RoleName: roleName, - }) - if err != nil { - return err - } + _, err := svc.DeleteRole(&iam.DeleteRoleInput{ + RoleName: roleName, + }) + if err != nil { + return err + } - return nil + return nil } func TestCreateEvent(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfig(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - var roleResult *iam.CreateRoleOutput - policyARN := "" - - if globalConfig.RoleARN == "" { - roleResult, policyARN, err = createRole(t, sess, &globalConfig.RoleName, &globalConfig.PolicyName) - if err != nil { - t.Fatal(err) - } - - globalConfig.RoleARN = *roleResult.Role.Arn - - t.Log("Created role with ARN: " + globalConfig.RoleARN) - } else { - t.Log("Using role with ARN " + globalConfig.RoleARN) - } - - _, err = createRule(sess, &globalConfig.RuleName, &globalConfig.RoleARN, &globalConfig.Schedule) - if err != nil { - t.Fatal(err) - } - - err = createTarget(sess, &globalConfig.RuleName, &globalConfig.LambdaARN, &globalConfig.RoleName) - if err != nil { - t.Fatal(err) - } - - event, err := getEventInfo() - if err != nil { - t.Fatal(err) - } - - err = CreateEvent(sess, &globalConfig.LambdaARN, event) - if err != nil { - t.Fatal(err) - } - - t.Log("Created event") - - err = deleteTargets(t, sess, &globalConfig.RuleName) - if err != nil { - t.Fatal(err) - } - - t.Log("Deleted target " + globalConfig.TargetID) - - err = deleteRule(sess, &globalConfig.RuleName) - if err != nil { - t.Log("You'll have to delete the rule " + globalConfig.RuleName + " yourself") - t.Fatal(err) - } - - err = detachPolicy(sess, &policyARN, &globalConfig.RoleName) - if err != nil { - t.Fatal(err) - } - - t.Log("Detached policy " + globalConfig.PolicyName) - - err = deleteRole(sess, &globalConfig.RoleName) - if err != nil { - t.Log("You'll have to delete the role " + globalConfig.RoleName + " yourself") - t.Fatal(err) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfig(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + var roleResult *iam.CreateRoleOutput + policyARN := "" + + if globalConfig.RoleARN == "" { + roleResult, policyARN, err = createRole(t, sess, &globalConfig.RoleName, &globalConfig.PolicyName) + if err != nil { + t.Fatal(err) + } + + globalConfig.RoleARN = *roleResult.Role.Arn + + t.Log("Created role with ARN: " + globalConfig.RoleARN) + } else { + t.Log("Using role with ARN " + globalConfig.RoleARN) + } + + _, err = createRule(sess, &globalConfig.RuleName, &globalConfig.RoleARN, &globalConfig.Schedule) + if err != nil { + t.Fatal(err) + } + + err = createTarget(sess, &globalConfig.RuleName, &globalConfig.LambdaARN, &globalConfig.RoleName) + if err != nil { + t.Fatal(err) + } + + event, err := getEventInfo() + if err != nil { + t.Fatal(err) + } + + err = CreateEvent(sess, &globalConfig.LambdaARN, event) + if err != nil { + t.Fatal(err) + } + + t.Log("Created event") + + err = deleteTargets(t, sess, &globalConfig.RuleName) + if err != nil { + t.Fatal(err) + } + + t.Log("Deleted target " + globalConfig.TargetID) + + err = deleteRule(sess, &globalConfig.RuleName) + if err != nil { + t.Log("You'll have to delete the rule " + globalConfig.RuleName + " yourself") + t.Fatal(err) + } + + err = detachPolicy(sess, &policyARN, &globalConfig.RoleName) + if err != nil { + t.Fatal(err) + } + + t.Log("Detached policy " + globalConfig.PolicyName) + + err = deleteRole(sess, &globalConfig.RoleName) + if err != nil { + t.Log("You'll have to delete the role " + globalConfig.RoleName + " yourself") + t.Fatal(err) + } } diff --git a/go/codebuild/BuildProject/BuildProject_test.go b/go/codebuild/BuildProject/BuildProject_test.go index 3c7a85b5883..3effe29bb12 100644 --- a/go/codebuild/BuildProject/BuildProject_test.go +++ b/go/codebuild/BuildProject/BuildProject_test.go @@ -1,45 +1,46 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/codebuild" - "github.com/aws/aws-sdk-go/service/codebuild/codebuildiface" + "github.com/aws/aws-sdk-go/service/codebuild" + "github.com/aws/aws-sdk-go/service/codebuild/codebuildiface" ) // Define a mock struct to use in unit tests type mockCodeBuildClient struct { - codebuildiface.CodeBuildAPI + codebuildiface.CodeBuildAPI } func (m *mockCodeBuildClient) StartBuild(input *codebuild.StartBuildInput) (*codebuild.StartBuildOutput, error) { - // Check that required inputs exist - if input.ProjectName == nil || *input.ProjectName == "" { - return nil, errors.New("StartBuildInput.ProjectName is nil or an empty string") - } + // Check that required inputs exist + if input.ProjectName == nil || *input.ProjectName == "" { + return nil, errors.New("StartBuildInput.ProjectName is nil or an empty string") + } - resp := codebuild.StartBuildOutput{} - return &resp, nil + resp := codebuild.StartBuildOutput{} + return &resp, nil } func TestBuildProject(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - project := "test-project" + // mock resource + project := "test-project" - mockSvc := &mockCodeBuildClient{} + mockSvc := &mockCodeBuildClient{} - err := BldProject(mockSvc, &project) - if err != nil { - t.Fatal(err) - } + err := BldProject(mockSvc, &project) + if err != nil { + t.Fatal(err) + } - t.Log("Built project " + project) + t.Log("Built project " + project) } diff --git a/go/codebuild/ListBuilds/ListBuilds_test.go b/go/codebuild/ListBuilds/ListBuilds_test.go index e580f4f5290..a01a44c0aa2 100644 --- a/go/codebuild/ListBuilds/ListBuilds_test.go +++ b/go/codebuild/ListBuilds/ListBuilds_test.go @@ -1,28 +1,29 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "strconv" - "testing" - "time" + "strconv" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/aws/session" ) func TestListBuilds(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - result, err := GetBuilds(sess) - if err != nil { - t.Fatal(err) - } + result, err := GetBuilds(sess) + if err != nil { + t.Fatal(err) + } - t.Log("Retrieved " + strconv.Itoa(len(result.Builds)) + " builds") + t.Log("Retrieved " + strconv.Itoa(len(result.Builds)) + " builds") } diff --git a/go/codebuild/ListProjects/ListProjects_test.go b/go/codebuild/ListProjects/ListProjects_test.go index b808bd90f31..646a427c33f 100644 --- a/go/codebuild/ListProjects/ListProjects_test.go +++ b/go/codebuild/ListProjects/ListProjects_test.go @@ -1,28 +1,29 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "strconv" - "testing" - "time" + "strconv" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/aws/session" ) func TestListProjects(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - result, err := GetProjects(sess) - if err != nil { - t.Fatal(err) - } + result, err := GetProjects(sess) + if err != nil { + t.Fatal(err) + } - t.Log("Got " + strconv.Itoa(len(result.Projects)) + " project(s)") + t.Log("Got " + strconv.Itoa(len(result.Projects)) + " project(s)") } diff --git a/go/dynamodb/CreateTable/CreateTable.go b/go/dynamodb/CreateTable/CreateTable.go index c2d7230a8e5..28294473ae0 100644 --- a/go/dynamodb/CreateTable/CreateTable.go +++ b/go/dynamodb/CreateTable/CreateTable.go @@ -1,97 +1,103 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[dynamodb.go.create_new_table] package main // snippet-start:[dynamodb.go.create_new_table.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" ) + // snippet-end:[dynamodb.go.create_new_table.imports] // MakeTable creates an Amazon DynamoDB table // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// attributeDefinitions describe the table's attributes -// keySchema defines the table schema -// provisionedThroughput defines the throughput -// tableName is the name of the table +// +// sess is the current session, which provides configuration for the SDK's service clients +// attributeDefinitions describe the table's attributes +// keySchema defines the table schema +// provisionedThroughput defines the throughput +// tableName is the name of the table +// // Output: -// If success, nil -// Otherwise, an error from the call to CreateTable +// +// If success, nil +// Otherwise, an error from the call to CreateTable func MakeTable(svc dynamodbiface.DynamoDBAPI, attributeDefinitions []*dynamodb.AttributeDefinition, keySchema []*dynamodb.KeySchemaElement, provisionedThroughput *dynamodb.ProvisionedThroughput, tableName *string) error { - // snippet-start:[dynamodb.go.create_new_table.call] + // snippet-start:[dynamodb.go.create_new_table.call] - _, err := svc.CreateTable(&dynamodb.CreateTableInput{ - AttributeDefinitions: attributeDefinitions, - KeySchema: keySchema, - ProvisionedThroughput: provisionedThroughput, - TableName: tableName, - }) - // snippet-end:[dynamodb.go.create_new_table.call] - return err + _, err := svc.CreateTable(&dynamodb.CreateTableInput{ + AttributeDefinitions: attributeDefinitions, + KeySchema: keySchema, + ProvisionedThroughput: provisionedThroughput, + TableName: tableName, + }) + // snippet-end:[dynamodb.go.create_new_table.call] + return err } func main() { - // snippet-start:[dynamodb.go.create_new_table.args] - tableName := flag.String("t", "", "The name of the table") - flag.Parse() + // snippet-start:[dynamodb.go.create_new_table.args] + tableName := flag.String("t", "", "The name of the table") + flag.Parse() - if *tableName == "" { - fmt.Println("You must supply a table name (-t TABLE)") - return - } - // snippet-end:[dynamodb.go.create_new_table.args] + if *tableName == "" { + fmt.Println("You must supply a table name (-t TABLE)") + return + } + // snippet-end:[dynamodb.go.create_new_table.args] - // snippet-start:[dynamodb.go.create_new_table.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + // snippet-start:[dynamodb.go.create_new_table.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - svc := dynamodb.New(sess) - // snippet-end:[dynamodb.go.create_new_table.session] + svc := dynamodb.New(sess) + // snippet-end:[dynamodb.go.create_new_table.session] - // snippet-start:[dynamodb.go.create_new_table.create_input] - attributeDefinitions := []*dynamodb.AttributeDefinition{ - { - AttributeName: aws.String("Year"), - AttributeType: aws.String("N"), - }, - { - AttributeName: aws.String("Title"), - AttributeType: aws.String("S"), - }, - } + // snippet-start:[dynamodb.go.create_new_table.create_input] + attributeDefinitions := []*dynamodb.AttributeDefinition{ + { + AttributeName: aws.String("Year"), + AttributeType: aws.String("N"), + }, + { + AttributeName: aws.String("Title"), + AttributeType: aws.String("S"), + }, + } - keySchema := []*dynamodb.KeySchemaElement{ - { - AttributeName: aws.String("Year"), - KeyType: aws.String("HASH"), - }, - { - AttributeName: aws.String("Title"), - KeyType: aws.String("RANGE"), - }, - } + keySchema := []*dynamodb.KeySchemaElement{ + { + AttributeName: aws.String("Year"), + KeyType: aws.String("HASH"), + }, + { + AttributeName: aws.String("Title"), + KeyType: aws.String("RANGE"), + }, + } - provisionedThroughput := &dynamodb.ProvisionedThroughput{ - ReadCapacityUnits: aws.Int64(10), - WriteCapacityUnits: aws.Int64(10), - } - // snippet-end:[dynamodb.go.create_new_table.create_input] + provisionedThroughput := &dynamodb.ProvisionedThroughput{ + ReadCapacityUnits: aws.Int64(10), + WriteCapacityUnits: aws.Int64(10), + } + // snippet-end:[dynamodb.go.create_new_table.create_input] - err := MakeTable(svc, attributeDefinitions, keySchema, provisionedThroughput, tableName) - if err != nil { - fmt.Println("Got error calling CreateTable:") - fmt.Println(err) - return - } + err := MakeTable(svc, attributeDefinitions, keySchema, provisionedThroughput, tableName) + if err != nil { + fmt.Println("Got error calling CreateTable:") + fmt.Println(err) + return + } - fmt.Println("Created the table", *tableName) + fmt.Println("Created the table", *tableName) } + // snippet-end:[dynamodb.go.create_new_table] diff --git a/go/dynamodb/CreateTable/CreateTable_test.go b/go/dynamodb/CreateTable/CreateTable_test.go index 695da390b13..554c6c6da34 100644 --- a/go/dynamodb/CreateTable/CreateTable_test.go +++ b/go/dynamodb/CreateTable/CreateTable_test.go @@ -1,48 +1,49 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "errors" - "io/ioutil" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" - - // For mocking - "github.com/google/uuid" // For creating a random, unique resource name + "encoding/json" + "errors" + "io/ioutil" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" + + // For mocking + "github.com/google/uuid" // For creating a random, unique resource name ) // Define a mock struct to use in unit tests type mockDynamodbClient struct { - dynamodbiface.DynamoDBAPI + dynamodbiface.DynamoDBAPI } func (m *mockDynamodbClient) CreateTable(input *dynamodb.CreateTableInput) (*dynamodb.CreateTableOutput, error) { - result := dynamodb.CreateTableOutput{} + result := dynamodb.CreateTableOutput{} - if input.AttributeDefinitions == nil { - return &result, errors.New("Missing required field CreateTableInput.AttributeDefinitions") - } + if input.AttributeDefinitions == nil { + return &result, errors.New("Missing required field CreateTableInput.AttributeDefinitions") + } - if input.KeySchema == nil { - return &result, errors.New("Missing required field CreateTableInput.KeySchema") - } + if input.KeySchema == nil { + return &result, errors.New("Missing required field CreateTableInput.KeySchema") + } - if input.TableName == nil || *input.TableName == "" { - return &result, errors.New("Missing required field CreateTableInput.TableName") - } + if input.TableName == nil || *input.TableName == "" { + return &result, errors.New("Missing required field CreateTableInput.TableName") + } - return &result, nil + return &result, nil } type Config struct { - Table string `json:"Table"` + Table string `json:"Table"` } var configFileName = "config.json" @@ -50,83 +51,83 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Table: " + globalConfig.Table) + t.Log("Table: " + globalConfig.Table) - return nil + return nil } func TestCreateTable(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - attributeDefinitions := []*dynamodb.AttributeDefinition{ - { - AttributeName: aws.String("Year"), - AttributeType: aws.String("N"), - }, - { - AttributeName: aws.String("Title"), - AttributeType: aws.String("S"), - }, - } - - keySchema := []*dynamodb.KeySchemaElement{ - { - AttributeName: aws.String("Year"), - KeyType: aws.String("HASH"), - }, - { - AttributeName: aws.String("Title"), - KeyType: aws.String("RANGE"), - }, - } - - provisionedThroughput := &dynamodb.ProvisionedThroughput{ - ReadCapacityUnits: aws.Int64(10), - WriteCapacityUnits: aws.Int64(10), - } - - if globalConfig.Table == "" { - // mock resources - id := uuid.New() - globalConfig.Table = "test-table-" + id.String() - - mockSvc := &mockDynamodbClient{} - - err = MakeTable(mockSvc, attributeDefinitions, keySchema, provisionedThroughput, &globalConfig.Table) - if err != nil { - t.Fatal(err) - } - } else { - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := dynamodb.New(sess) - - err = MakeTable(svc, attributeDefinitions, keySchema, provisionedThroughput, &globalConfig.Table) - if err != nil { - t.Fatal(err) - } - } - - t.Log("Created table " + globalConfig.Table) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + attributeDefinitions := []*dynamodb.AttributeDefinition{ + { + AttributeName: aws.String("Year"), + AttributeType: aws.String("N"), + }, + { + AttributeName: aws.String("Title"), + AttributeType: aws.String("S"), + }, + } + + keySchema := []*dynamodb.KeySchemaElement{ + { + AttributeName: aws.String("Year"), + KeyType: aws.String("HASH"), + }, + { + AttributeName: aws.String("Title"), + KeyType: aws.String("RANGE"), + }, + } + + provisionedThroughput := &dynamodb.ProvisionedThroughput{ + ReadCapacityUnits: aws.Int64(10), + WriteCapacityUnits: aws.Int64(10), + } + + if globalConfig.Table == "" { + // mock resources + id := uuid.New() + globalConfig.Table = "test-table-" + id.String() + + mockSvc := &mockDynamodbClient{} + + err = MakeTable(mockSvc, attributeDefinitions, keySchema, provisionedThroughput, &globalConfig.Table) + if err != nil { + t.Fatal(err) + } + } else { + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := dynamodb.New(sess) + + err = MakeTable(svc, attributeDefinitions, keySchema, provisionedThroughput, &globalConfig.Table) + if err != nil { + t.Fatal(err) + } + } + + t.Log("Created table " + globalConfig.Table) } diff --git a/go/dynamodb/CreateTableItem/CreateTableItem_test.go b/go/dynamodb/CreateTableItem/CreateTableItem_test.go index 09d85d4460f..3beea13a63c 100644 --- a/go/dynamodb/CreateTableItem/CreateTableItem_test.go +++ b/go/dynamodb/CreateTableItem/CreateTableItem_test.go @@ -1,48 +1,49 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "errors" - "io/ioutil" - "strconv" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" - - // For mocking - "github.com/google/uuid" // For creating a random, unique resource name + "encoding/json" + "errors" + "io/ioutil" + "strconv" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" + + // For mocking + "github.com/google/uuid" // For creating a random, unique resource name ) // Define a mock struct to use in unit tests type mockDynamodbClient struct { - dynamodbiface.DynamoDBAPI + dynamodbiface.DynamoDBAPI } func (m *mockDynamodbClient) PutItem(input *dynamodb.PutItemInput) (*dynamodb.PutItemOutput, error) { - result := dynamodb.PutItemOutput{} + result := dynamodb.PutItemOutput{} - if input.Item == nil { - return &result, errors.New("Missing required field PutItemInput.Item") - } + if input.Item == nil { + return &result, errors.New("Missing required field PutItemInput.Item") + } - if input.TableName == nil || *input.TableName == "" { - return &result, errors.New("Missing required field CreateTableInput.TableName") - } + if input.TableName == nil || *input.TableName == "" { + return &result, errors.New("Missing required field CreateTableInput.TableName") + } - return &result, nil + return &result, nil } type Config struct { - Table string `json:"Table"` - Year int `json:"Year"` - Title string `json:"Title"` - Plot string `json:"Plot"` - Rating float64 `json:"float"` + Table string `json:"Table"` + Year int `json:"Year"` + Title string `json:"Title"` + Plot string `json:"Plot"` + Rating float64 `json:"float"` } var configFileName = "config.json" @@ -50,76 +51,76 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Table: " + globalConfig.Table) - t.Log("Year: " + strconv.Itoa(globalConfig.Year)) - t.Log("Title: " + globalConfig.Title) - t.Log("Plot: " + globalConfig.Plot) - t.Log("Rating: " + strconv.Itoa(int(globalConfig.Rating))) + t.Log("Table: " + globalConfig.Table) + t.Log("Year: " + strconv.Itoa(globalConfig.Year)) + t.Log("Title: " + globalConfig.Title) + t.Log("Plot: " + globalConfig.Plot) + t.Log("Rating: " + strconv.Itoa(int(globalConfig.Rating))) - return nil + return nil } func TestCreateTable(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - if globalConfig.Year == 0 { - globalConfig.Year = 1999 - } - - if globalConfig.Plot == "" { - globalConfig.Plot = "Not much happening" - } - - if globalConfig.Rating == 0.0 { - globalConfig.Rating = 5.0 - } - - if globalConfig.Title == "" { - globalConfig.Title = "The Big Nada" - } - - if globalConfig.Table == "" { - // mock resources - id := uuid.New() - globalConfig.Table = "test-table-" + id.String() - - mockSvc := &mockDynamodbClient{} - - err = AddTableItem(mockSvc, &globalConfig.Year, &globalConfig.Table, &globalConfig.Title, &globalConfig.Plot, &globalConfig.Rating) - if err != nil { - t.Fatal(err) - } - } else { - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := dynamodb.New(sess) - - err = AddTableItem(svc, &globalConfig.Year, &globalConfig.Table, &globalConfig.Title, &globalConfig.Plot, &globalConfig.Rating) - if err != nil { - t.Fatal(err) - } - } - - t.Log("Successfully added '"+globalConfig.Title+"' ("+strconv.Itoa(globalConfig.Year)+") to table "+globalConfig.Table+" with rating", globalConfig.Rating) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + if globalConfig.Year == 0 { + globalConfig.Year = 1999 + } + + if globalConfig.Plot == "" { + globalConfig.Plot = "Not much happening" + } + + if globalConfig.Rating == 0.0 { + globalConfig.Rating = 5.0 + } + + if globalConfig.Title == "" { + globalConfig.Title = "The Big Nada" + } + + if globalConfig.Table == "" { + // mock resources + id := uuid.New() + globalConfig.Table = "test-table-" + id.String() + + mockSvc := &mockDynamodbClient{} + + err = AddTableItem(mockSvc, &globalConfig.Year, &globalConfig.Table, &globalConfig.Title, &globalConfig.Plot, &globalConfig.Rating) + if err != nil { + t.Fatal(err) + } + } else { + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := dynamodb.New(sess) + + err = AddTableItem(svc, &globalConfig.Year, &globalConfig.Table, &globalConfig.Title, &globalConfig.Plot, &globalConfig.Rating) + if err != nil { + t.Fatal(err) + } + } + + t.Log("Successfully added '"+globalConfig.Title+"' ("+strconv.Itoa(globalConfig.Year)+") to table "+globalConfig.Table+" with rating", globalConfig.Rating) } diff --git a/go/dynamodb/DeleteItem/DeleteItem_test.go b/go/dynamodb/DeleteItem/DeleteItem_test.go index de9dfb3354a..d697068d350 100644 --- a/go/dynamodb/DeleteItem/DeleteItem_test.go +++ b/go/dynamodb/DeleteItem/DeleteItem_test.go @@ -1,43 +1,44 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "testing" - "time" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" + "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" ) // Define a mock struct to use in unit tests type mockDynamodbClient struct { - dynamodbiface.DynamoDBAPI + dynamodbiface.DynamoDBAPI } func (m *mockDynamodbClient) DeleteItem(input *dynamodb.DeleteItemInput) (*dynamodb.DeleteItemOutput, error) { - // Check that required inputs exist - resp := dynamodb.DeleteItemOutput{} + // Check that required inputs exist + resp := dynamodb.DeleteItemOutput{} - return &resp, nil + return &resp, nil } func TestDeleteItem(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - table := "test-table" - movie := "test-movie" - year := "1999" + // mock resource + table := "test-table" + movie := "test-movie" + year := "1999" - mockSvc := &mockDynamodbClient{} + mockSvc := &mockDynamodbClient{} - err := DeleteTableItem(mockSvc, &table, &movie, &year) - if err != nil { - t.Fatal(err) - } + err := DeleteTableItem(mockSvc, &table, &movie, &year) + if err != nil { + t.Fatal(err) + } - t.Log("Deleted movie " + movie + " from table " + table) + t.Log("Deleted movie " + movie + " from table " + table) } diff --git a/go/dynamodb/GetItem/GetItem_test.go b/go/dynamodb/GetItem/GetItem_test.go index e71a34bd9ea..8fe7c287762 100644 --- a/go/dynamodb/GetItem/GetItem_test.go +++ b/go/dynamodb/GetItem/GetItem_test.go @@ -1,65 +1,66 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" + "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" + "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" - "github.com/google/uuid" + "github.com/google/uuid" ) type mockDynamodbClient struct { - dynamodbiface.DynamoDBAPI + dynamodbiface.DynamoDBAPI } var title = "this is a test" var year = 1999 func (m *mockDynamodbClient) GetItem(input *dynamodb.GetItemInput) (*dynamodb.GetItemOutput, error) { - result := dynamodb.GetItemOutput{} + result := dynamodb.GetItemOutput{} - if input.TableName == nil || *input.TableName == "" { - return &result, errors.New("You must supply a table name") - } + if input.TableName == nil || *input.TableName == "" { + return &result, errors.New("You must supply a table name") + } - item := Item{ - Year: year, - Title: title, - } + item := Item{ + Year: year, + Title: title, + } - av, err := dynamodbattribute.MarshalMap(item) - if err != nil { - return &result, err - } + av, err := dynamodbattribute.MarshalMap(item) + if err != nil { + return &result, err + } - result = dynamodb.GetItemOutput{ - Item: av, - } + result = dynamodb.GetItemOutput{ + Item: av, + } - return &result, nil + return &result, nil } func TestGetItem(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resources - id := uuid.New() - table := "test-table-" + id.String() + // mock resources + id := uuid.New() + table := "test-table-" + id.String() - mockSvc := &mockDynamodbClient{} + mockSvc := &mockDynamodbClient{} - item, err := GetTableItem(mockSvc, &table, &title, &year) - if err != nil { - t.Fatal(err) - } + item, err := GetTableItem(mockSvc, &table, &title, &year) + if err != nil { + t.Fatal(err) + } - t.Log("Retrieved movie '" + item.Title + "' from table ") + t.Log("Retrieved movie '" + item.Title + "' from table ") } diff --git a/go/dynamodb/ListTables/ListTables.go b/go/dynamodb/ListTables/ListTables.go index cd978a2d590..835f68a34ba 100644 --- a/go/dynamodb/ListTables/ListTables.go +++ b/go/dynamodb/ListTables/ListTables.go @@ -1,65 +1,71 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[dynamodb.go.list_all_tables] package main // snippet-start:[dynamodb.go.list_all_tables.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" ) + // snippet-end:[dynamodb.go.list_all_tables.imports] // GetTables retrieves a list of your Amazon DynamoDB tables // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// limit is the maximum number of tables to return +// +// sess is the current session, which provides configuration for the SDK's service clients +// limit is the maximum number of tables to return +// // Output: -// If success, a list of the tables and nil -// Otherwise, nil and an error from the call to ListTables +// +// If success, a list of the tables and nil +// Otherwise, nil and an error from the call to ListTables func GetTables(sess *session.Session, limit *int64) ([]*string, error) { - // snippet-start:[dynamodb.go.list_all_tables.call] - svc := dynamodb.New(sess) + // snippet-start:[dynamodb.go.list_all_tables.call] + svc := dynamodb.New(sess) - result, err := svc.ListTables(&dynamodb.ListTablesInput{ - Limit: limit, - }) - // snippet-end:[dynamodb.go.list_all_tables.call] - if err != nil { - return nil, err - } + result, err := svc.ListTables(&dynamodb.ListTablesInput{ + Limit: limit, + }) + // snippet-end:[dynamodb.go.list_all_tables.call] + if err != nil { + return nil, err + } - return result.TableNames, nil + return result.TableNames, nil } func main() { - // snippet-start:[dynamodb.go.list_all_tables.args] - limit := flag.Int64("l", 100, "How many tables to return") - flag.Parse() + // snippet-start:[dynamodb.go.list_all_tables.args] + limit := flag.Int64("l", 100, "How many tables to return") + flag.Parse() - if *limit < int64(0) { - *limit = int64(10) - } - // snippet-end:[dynamodb.go.list_all_tables.args] + if *limit < int64(0) { + *limit = int64(10) + } + // snippet-end:[dynamodb.go.list_all_tables.args] - // snippet-start:[dynamodb.go.list_all_tables.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[dynamodb.go.list_all_tables.session] + // snippet-start:[dynamodb.go.list_all_tables.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[dynamodb.go.list_all_tables.session] - tables, err := GetTables(sess, limit) - if err != nil { - fmt.Println("Got an error retrieving table names:") - fmt.Println(err) - return - } + tables, err := GetTables(sess, limit) + if err != nil { + fmt.Println("Got an error retrieving table names:") + fmt.Println(err) + return + } - // Get up to limit tables - for _, n := range tables { - fmt.Println(*n) - } + // Get up to limit tables + for _, n := range tables { + fmt.Println(*n) + } } + // snippet-end:[dynamodb.go.list_all_tables] diff --git a/go/dynamodb/ListTables/ListTables_test.go b/go/dynamodb/ListTables/ListTables_test.go index e2ea953652a..60dca4aebea 100644 --- a/go/dynamodb/ListTables/ListTables_test.go +++ b/go/dynamodb/ListTables/ListTables_test.go @@ -1,19 +1,20 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "strconv" - "testing" - "time" + "encoding/json" + "io/ioutil" + "strconv" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/aws/session" ) type Config struct { - Limit int64 `json:"Limit"` + Limit int64 `json:"Limit"` } var configFileName = "config.json" @@ -21,48 +22,48 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Limit: " + strconv.Itoa(int(globalConfig.Limit))) + t.Log("Limit: " + strconv.Itoa(int(globalConfig.Limit))) - return nil + return nil } func TestListTables(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - if globalConfig.Limit < int64(0) { - globalConfig.Limit = int64(10) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - tables, err := GetTables(sess, &globalConfig.Limit) - if err != nil { - t.Fatal(err) - } - - // Get up to globalConfig.Limit tables - for _, n := range tables { - t.Log(*n) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + if globalConfig.Limit < int64(0) { + globalConfig.Limit = int64(10) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + tables, err := GetTables(sess, &globalConfig.Limit) + if err != nil { + t.Fatal(err) + } + + // Get up to globalConfig.Limit tables + for _, n := range tables { + t.Log(*n) + } } diff --git a/go/dynamodb/LoadTableItems/LoadTableItems_test.go b/go/dynamodb/LoadTableItems/LoadTableItems_test.go index 6fd6bedc634..5412e763efd 100644 --- a/go/dynamodb/LoadTableItems/LoadTableItems_test.go +++ b/go/dynamodb/LoadTableItems/LoadTableItems_test.go @@ -1,44 +1,45 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "errors" - "io/ioutil" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" - - "github.com/google/uuid" + "encoding/json" + "errors" + "io/ioutil" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" + "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" + + "github.com/google/uuid" ) // Define a mock struct to use in unit tests type mockDynamodbClient struct { - dynamodbiface.DynamoDBAPI + dynamodbiface.DynamoDBAPI } func (m *mockDynamodbClient) PutItem(input *dynamodb.PutItemInput) (*dynamodb.PutItemOutput, error) { - result := dynamodb.PutItemOutput{} + result := dynamodb.PutItemOutput{} - if input.Item == nil { - return &result, errors.New("Missing required field PutItemInput.Item") - } + if input.Item == nil { + return &result, errors.New("Missing required field PutItemInput.Item") + } - if input.TableName == nil || *input.TableName == "" { - return &result, errors.New("Missing required field CreateTableInput.TableName") - } + if input.TableName == nil || *input.TableName == "" { + return &result, errors.New("Missing required field CreateTableInput.TableName") + } - return &result, nil + return &result, nil } type Config struct { - JSONFile string `json:"JsonFile"` - Table string `json:"Table"` + JSONFile string `json:"JsonFile"` + Table string `json:"Table"` } var configFileName = "config.json" @@ -46,98 +47,98 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("JsonFile: " + globalConfig.JSONFile) - t.Log("Table: " + globalConfig.Table) + t.Log("JsonFile: " + globalConfig.JSONFile) + t.Log("Table: " + globalConfig.Table) - return nil + return nil } func TestCreateTable(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - if globalConfig.JSONFile == "" { - t.Fatal("You must supply the name of the JSON file (JsonFile) in config.json") - } - - if globalConfig.Table == "" { - // mock resources - id := uuid.New() - globalConfig.Table = "test-table-" + id.String() - - mockSvc := &mockDynamodbClient{} - - items, err := GetItems(&globalConfig.JSONFile) - if err != nil { - t.Fatal(err) - } - - for _, item := range items { - av, err := dynamodbattribute.MarshalMap(item) - if err != nil { - t.Fatal(err) - } - - err = AddTableItem(mockSvc, av, &globalConfig.Table) - if err != nil { - t.Fatal(err) - } - - title, err := GetMovieName(av) - if err != nil { - t.Fatal(err) - } - - t.Log("Added movie " + title + " to table " + globalConfig.Table) - } - } else { - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := dynamodb.New(sess) - - items, err := GetItems(&globalConfig.JSONFile) - if err != nil { - t.Fatal(err) - } - - for _, item := range items { - av, err := dynamodbattribute.MarshalMap(item) - if err != nil { - t.Fatal(err) - } - - err = AddTableItem(svc, av, &globalConfig.Table) - if err != nil { - t.Fatal(err) - } - - title, err := GetMovieName(av) - if err != nil { - t.Fatal(err) - } - - t.Log("Added movie " + title + " to table " + globalConfig.Table) - } - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + if globalConfig.JSONFile == "" { + t.Fatal("You must supply the name of the JSON file (JsonFile) in config.json") + } + + if globalConfig.Table == "" { + // mock resources + id := uuid.New() + globalConfig.Table = "test-table-" + id.String() + + mockSvc := &mockDynamodbClient{} + + items, err := GetItems(&globalConfig.JSONFile) + if err != nil { + t.Fatal(err) + } + + for _, item := range items { + av, err := dynamodbattribute.MarshalMap(item) + if err != nil { + t.Fatal(err) + } + + err = AddTableItem(mockSvc, av, &globalConfig.Table) + if err != nil { + t.Fatal(err) + } + + title, err := GetMovieName(av) + if err != nil { + t.Fatal(err) + } + + t.Log("Added movie " + title + " to table " + globalConfig.Table) + } + } else { + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := dynamodb.New(sess) + + items, err := GetItems(&globalConfig.JSONFile) + if err != nil { + t.Fatal(err) + } + + for _, item := range items { + av, err := dynamodbattribute.MarshalMap(item) + if err != nil { + t.Fatal(err) + } + + err = AddTableItem(svc, av, &globalConfig.Table) + if err != nil { + t.Fatal(err) + } + + title, err := GetMovieName(av) + if err != nil { + t.Fatal(err) + } + + t.Log("Added movie " + title + " to table " + globalConfig.Table) + } + } } diff --git a/go/dynamodb/ScanItems/ScanItems_test.go b/go/dynamodb/ScanItems/ScanItems_test.go index fa2988280e6..377e100cc05 100644 --- a/go/dynamodb/ScanItems/ScanItems_test.go +++ b/go/dynamodb/ScanItems/ScanItems_test.go @@ -1,21 +1,22 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "strconv" - "testing" - "time" + "encoding/json" + "io/ioutil" + "strconv" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/aws/session" ) type Config struct { - Table string `json:"Table"` - MinRating float64 `json:"MinRating"` - Year int `json:"Year"` + Table string `json:"Table"` + MinRating float64 `json:"MinRating"` + Year int `json:"Year"` } var configFileName = "config.json" @@ -23,47 +24,47 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Table: " + globalConfig.Table) - t.Log("Year: " + strconv.Itoa(globalConfig.Year)) - t.Log("MinRating: " + strconv.Itoa(int(globalConfig.MinRating))) + t.Log("Table: " + globalConfig.Table) + t.Log("Year: " + strconv.Itoa(globalConfig.Year)) + t.Log("MinRating: " + strconv.Itoa(int(globalConfig.MinRating))) - return nil + return nil } func TestScanItems(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } - if globalConfig.Table == "" || globalConfig.Year < 1900 || globalConfig.MinRating < 0.0 { - t.Fatal("Missing Table name, year < 1900, or MinRating < 0.0 in config.json") - } + if globalConfig.Table == "" || globalConfig.Year < 1900 || globalConfig.MinRating < 0.0 { + t.Fatal("Missing Table name, year < 1900, or MinRating < 0.0 in config.json") + } - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - result, err := ScanTableItems(sess, &globalConfig.Year, &globalConfig.Table, &globalConfig.MinRating) - if err != nil { - t.Fatal(err) - } + result, err := ScanTableItems(sess, &globalConfig.Year, &globalConfig.Table, &globalConfig.MinRating) + if err != nil { + t.Fatal(err) + } - t.Log("Found", strconv.Itoa(len(*result)), "movie(s) with a rating above", globalConfig.MinRating, "in", globalConfig.Year) + t.Log("Found", strconv.Itoa(len(*result)), "movie(s) with a rating above", globalConfig.MinRating, "in", globalConfig.Year) } diff --git a/go/ec2/AllocateAddress/AllocateAddress_test.go b/go/ec2/AllocateAddress/AllocateAddress_test.go index ac704cae126..f1055f79d09 100644 --- a/go/ec2/AllocateAddress/AllocateAddress_test.go +++ b/go/ec2/AllocateAddress/AllocateAddress_test.go @@ -1,61 +1,62 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/aws/aws-sdk-go/service/ec2/ec2iface" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/service/ec2/ec2iface" ) type mockEC2Client struct { - ec2iface.EC2API + ec2iface.EC2API } func (m *mockEC2Client) AllocateAddress(input *ec2.AllocateAddressInput) (*ec2.AllocateAddressOutput, error) { - // Check that required inputs exist - if input.Domain == nil || *input.Domain == "" { - return nil, errors.New("AllocateAddressInput.Domain is nil or an empty string") - } - - resp := ec2.AllocateAddressOutput{ - PublicIp: aws.String("test-public-IP"), - AllocationId: aws.String("test-allocation-ID"), - } - return &resp, nil + // Check that required inputs exist + if input.Domain == nil || *input.Domain == "" { + return nil, errors.New("AllocateAddressInput.Domain is nil or an empty string") + } + + resp := ec2.AllocateAddressOutput{ + PublicIp: aws.String("test-public-IP"), + AllocationId: aws.String("test-allocation-ID"), + } + return &resp, nil } func (m *mockEC2Client) AssociateAddress(input *ec2.AssociateAddressInput) (*ec2.AssociateAddressOutput, error) { - // Check that required inputs exist - if input.AllocationId == nil || *input.AllocationId == "" || input.InstanceId == nil || *input.InstanceId == "" { - return nil, errors.New("AssociateAddressInput.AllocationId or AssociateAddressInput.InstanceId is nil or an empty string") - } - - resp := ec2.AssociateAddressOutput{ - AssociationId: aws.String("test-association-ID"), - } - return &resp, nil + // Check that required inputs exist + if input.AllocationId == nil || *input.AllocationId == "" || input.InstanceId == nil || *input.InstanceId == "" { + return nil, errors.New("AssociateAddressInput.AllocationId or AssociateAddressInput.InstanceId is nil or an empty string") + } + + resp := ec2.AssociateAddressOutput{ + AssociationId: aws.String("test-association-ID"), + } + return &resp, nil } func TestAllocateAddress(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - instanceID := "test-instance-ID" + // mock resource + instanceID := "test-instance-ID" - mockSvc := &mockEC2Client{} + mockSvc := &mockEC2Client{} - allocRes, assocRes, err := AllocateAndAssociate(mockSvc, &instanceID) - if err != nil { - t.Fatal(err) - } + allocRes, assocRes, err := AllocateAndAssociate(mockSvc, &instanceID) + if err != nil { + t.Fatal(err) + } - t.Log("Allocated IP address", *allocRes.PublicIp, "with instance", instanceID) - t.Log("Allocation id:", *allocRes.AllocationId, "association id: ", *assocRes.AssociationId) + t.Log("Allocated IP address", *allocRes.PublicIp, "with instance", instanceID) + t.Log("Allocation id:", *allocRes.AllocationId, "association id: ", *assocRes.AssociationId) } diff --git a/go/ec2/CreateImage/CreateImage_test.go b/go/ec2/CreateImage/CreateImage_test.go index d662fc915e9..59d545d7f9b 100644 --- a/go/ec2/CreateImage/CreateImage_test.go +++ b/go/ec2/CreateImage/CreateImage_test.go @@ -1,50 +1,51 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/aws/aws-sdk-go/service/ec2/ec2iface" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/service/ec2/ec2iface" ) // Define a mock struct to use in unit tests type mockEC2Client struct { - ec2iface.EC2API + ec2iface.EC2API } func (m *mockEC2Client) CreateImage(input *ec2.CreateImageInput) (*ec2.CreateImageOutput, error) { - // Check that required inputs exist - if input.Name == nil || *input.Name == "" { - return nil, errors.New("CreateImageInput.name is nil or an empty string") - } - - resp := ec2.CreateImageOutput{ - ImageId: aws.String("test-image-id"), - } - return &resp, nil + // Check that required inputs exist + if input.Name == nil || *input.Name == "" { + return nil, errors.New("CreateImageInput.name is nil or an empty string") + } + + resp := ec2.CreateImageOutput{ + ImageId: aws.String("test-image-id"), + } + return &resp, nil } func TestCreateImage(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resources - imageDescription := "test-image-description" - instanceID := "test-instance-ID" - imageName := "test-image-name" + // mock resources + imageDescription := "test-image-description" + instanceID := "test-instance-ID" + imageName := "test-image-name" - mockSvc := &mockEC2Client{} + mockSvc := &mockEC2Client{} - resp, err := MakeImage(mockSvc, &imageDescription, &instanceID, &imageName) - if err != nil { - t.Fatal(err) - } + resp, err := MakeImage(mockSvc, &imageDescription, &instanceID, &imageName) + if err != nil { + t.Fatal(err) + } - t.Log("Created image with ID: " + *resp.ImageId) + t.Log("Created image with ID: " + *resp.ImageId) } diff --git a/go/ec2/CreateInstance/CreateInstance_test.go b/go/ec2/CreateInstance/CreateInstance_test.go index 3c89f7b65ce..b14240a51b1 100644 --- a/go/ec2/CreateInstance/CreateInstance_test.go +++ b/go/ec2/CreateInstance/CreateInstance_test.go @@ -1,64 +1,65 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/aws/aws-sdk-go/service/ec2/ec2iface" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/service/ec2/ec2iface" ) // Define a mock struct to use in unit tests type mockEC2Client struct { - ec2iface.EC2API + ec2iface.EC2API } func (m *mockEC2Client) RunInstances(input *ec2.RunInstancesInput) (*ec2.Reservation, error) { - // Check that required inputs exist - if input.MaxCount == nil || *input.MaxCount < int64(0) || input.MinCount == nil || *input.MinCount < int64(0) { - return nil, errors.New("RunInstancesInput.MaxCount or RunInstancesInput.MinCount is nil or less than zero") - } + // Check that required inputs exist + if input.MaxCount == nil || *input.MaxCount < int64(0) || input.MinCount == nil || *input.MinCount < int64(0) { + return nil, errors.New("RunInstancesInput.MaxCount or RunInstancesInput.MinCount is nil or less than zero") + } - resp := ec2.Reservation{ - Instances: []*ec2.Instance{&ec2.Instance{ - InstanceId: aws.String("test-instance-id"), - }}, - } - return &resp, nil + resp := ec2.Reservation{ + Instances: []*ec2.Instance{&ec2.Instance{ + InstanceId: aws.String("test-instance-id"), + }}, + } + return &resp, nil } func (m *mockEC2Client) CreateTags(input *ec2.CreateTagsInput) (*ec2.CreateTagsOutput, error) { - if input.Tags == nil { - return nil, errors.New("CreateTagsInput.Tags is nil") - } + if input.Tags == nil { + return nil, errors.New("CreateTagsInput.Tags is nil") + } - if input.Tags[0].Key == nil || *input.Tags[0].Key == "" || input.Tags[0].Value == nil || *input.Tags[0].Value == "" { - return nil, errors.New("CreateTagsInput.Tags[0].Tag or CreateTagsInput.Tags[0].Value is nil or an empty string") - } + if input.Tags[0].Key == nil || *input.Tags[0].Key == "" || input.Tags[0].Value == nil || *input.Tags[0].Value == "" { + return nil, errors.New("CreateTagsInput.Tags[0].Tag or CreateTagsInput.Tags[0].Value is nil or an empty string") + } - resp := ec2.CreateTagsOutput{} - return &resp, nil + resp := ec2.CreateTagsOutput{} + return &resp, nil } func TestCreateInstance(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resources - InstanceName := "test-instance" - InstanceValue := "text-value" + // mock resources + InstanceName := "test-instance" + InstanceValue := "text-value" - mockSvc := &mockEC2Client{} + mockSvc := &mockEC2Client{} - result, err := MakeInstance(mockSvc, &InstanceName, &InstanceValue) - if err != nil { - t.Fatal("Got an error creating an instance with tag " + InstanceName) - } + result, err := MakeInstance(mockSvc, &InstanceName, &InstanceValue) + if err != nil { + t.Fatal("Got an error creating an instance with tag " + InstanceName) + } - t.Log("Created tagged instance with ID " + *result.Instances[0].InstanceId) + t.Log("Created tagged instance with ID " + *result.Instances[0].InstanceId) } diff --git a/go/ec2/CreateKeyPair/CreateKeyPair_test.go b/go/ec2/CreateKeyPair/CreateKeyPair_test.go index ad3800de8f7..ea65d3a4ffa 100644 --- a/go/ec2/CreateKeyPair/CreateKeyPair_test.go +++ b/go/ec2/CreateKeyPair/CreateKeyPair_test.go @@ -1,4 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main diff --git a/go/ec2/CreateSecurityGroup/CreateSecurityGroup_test.go b/go/ec2/CreateSecurityGroup/CreateSecurityGroup_test.go index 6fe191d4cdb..334ae70208e 100644 --- a/go/ec2/CreateSecurityGroup/CreateSecurityGroup_test.go +++ b/go/ec2/CreateSecurityGroup/CreateSecurityGroup_test.go @@ -1,64 +1,65 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "testing" - "time" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/aws/aws-sdk-go/service/ec2/ec2iface" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/service/ec2/ec2iface" ) // Define a mock struct to use in unit tests type mockEC2Client struct { - ec2iface.EC2API + ec2iface.EC2API } func (m *mockEC2Client) DescribeVpcs(input *ec2.DescribeVpcsInput) (*ec2.DescribeVpcsOutput, error) { - resp := ec2.DescribeVpcsOutput{ - Vpcs: []*ec2.Vpc{ - { - VpcId: aws.String("test-vpc-id"), - }, - }, - } - return &resp, nil + resp := ec2.DescribeVpcsOutput{ + Vpcs: []*ec2.Vpc{ + { + VpcId: aws.String("test-vpc-id"), + }, + }, + } + return &resp, nil } func (m *mockEC2Client) CreateSecurityGroup(input *ec2.CreateSecurityGroupInput) (*ec2.CreateSecurityGroupOutput, error) { - // Check that required inputs exist + // Check that required inputs exist - resp := ec2.CreateSecurityGroupOutput{ - GroupId: aws.String("test-group-id"), - } - return &resp, nil + resp := ec2.CreateSecurityGroupOutput{ + GroupId: aws.String("test-group-id"), + } + return &resp, nil } func (m *mockEC2Client) AuthorizeSecurityGroupIngress(input *ec2.AuthorizeSecurityGroupIngressInput) (*ec2.AuthorizeSecurityGroupIngressOutput, error) { - // Check that required inputs exist + // Check that required inputs exist - resp := ec2.AuthorizeSecurityGroupIngressOutput{} - return &resp, nil + resp := ec2.AuthorizeSecurityGroupIngressOutput{} + return &resp, nil } func TestCreateSecurityGroup(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resources - name := "test-security-group" - description := "A very important security group" - vpcID := "my-test-vpc-id" + // mock resources + name := "test-security-group" + description := "A very important security group" + vpcID := "my-test-vpc-id" - mockSvc := &mockEC2Client{} + mockSvc := &mockEC2Client{} - vID, gID, err := MakeSecurityGroup(mockSvc, &name, &description, &vpcID) - if err != nil { - t.Fatal(err) - } + vID, gID, err := MakeSecurityGroup(mockSvc, &name, &description, &vpcID) + if err != nil { + t.Fatal(err) + } - t.Log("Created security group with ID " + gID + " with VPC with ID " + vID) + t.Log("Created security group with ID " + gID + " with VPC with ID " + vID) } diff --git a/go/ec2/DeleteKeyPair/DeleteKeyPair_test.go b/go/ec2/DeleteKeyPair/DeleteKeyPair_test.go index fdc1b7f6f79..966078b786e 100644 --- a/go/ec2/DeleteKeyPair/DeleteKeyPair_test.go +++ b/go/ec2/DeleteKeyPair/DeleteKeyPair_test.go @@ -1,4 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main diff --git a/go/ec2/DeleteSecurityGroup/DeleteSecurityGroup_test.go b/go/ec2/DeleteSecurityGroup/DeleteSecurityGroup_test.go index 5abe204a666..341511e4b4c 100644 --- a/go/ec2/DeleteSecurityGroup/DeleteSecurityGroup_test.go +++ b/go/ec2/DeleteSecurityGroup/DeleteSecurityGroup_test.go @@ -1,4 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main diff --git a/go/ec2/DescribeAddresses/DescribeAddresses_test.go b/go/ec2/DescribeAddresses/DescribeAddresses_test.go index df874385da3..0404fa595cb 100644 --- a/go/ec2/DescribeAddresses/DescribeAddresses_test.go +++ b/go/ec2/DescribeAddresses/DescribeAddresses_test.go @@ -1,33 +1,34 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "testing" - "time" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/aws/session" ) func TestDescribeAddresses(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - result, err := GetAddresses(sess) - if err != nil { - t.Fatal(err) - } + result, err := GetAddresses(sess) + if err != nil { + t.Fatal(err) + } - for _, addr := range result.Addresses { - t.Log("IP address: ", *addr.PublicIp) - t.Log("Allocation ID:", *addr.AllocationId) - if addr.InstanceId != nil { - t.Log("Instance ID: ", *addr.InstanceId) - } - } + for _, addr := range result.Addresses { + t.Log("IP address: ", *addr.PublicIp) + t.Log("Allocation ID:", *addr.AllocationId) + if addr.InstanceId != nil { + t.Log("Instance ID: ", *addr.InstanceId) + } + } } diff --git a/go/ec2/DescribeInstances/DescribeInstances_test.go b/go/ec2/DescribeInstances/DescribeInstances_test.go index 87cd544f93a..5acb8bc56b0 100644 --- a/go/ec2/DescribeInstances/DescribeInstances_test.go +++ b/go/ec2/DescribeInstances/DescribeInstances_test.go @@ -1,35 +1,36 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "testing" - "time" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/aws/session" ) func TestDescribeInstances(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - result, err := GetInstances(sess) - if err != nil { - t.Fatal(err) - } - - for _, r := range result.Reservations { - t.Log("Reservation ID: " + *r.ReservationId) - t.Log("Instance IDs:") - for _, i := range r.Instances { - t.Log(" " + *i.InstanceId) - } - - t.Log("") - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + result, err := GetInstances(sess) + if err != nil { + t.Fatal(err) + } + + for _, r := range result.Reservations { + t.Log("Reservation ID: " + *r.ReservationId) + t.Log("Instance IDs:") + for _, i := range r.Instances { + t.Log(" " + *i.InstanceId) + } + + t.Log("") + } } diff --git a/go/ec2/DescribeKeyPairs/DescribeKeyPairs_test.go b/go/ec2/DescribeKeyPairs/DescribeKeyPairs_test.go index 83af0748e20..d1ecd27200b 100644 --- a/go/ec2/DescribeKeyPairs/DescribeKeyPairs_test.go +++ b/go/ec2/DescribeKeyPairs/DescribeKeyPairs_test.go @@ -1,27 +1,28 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "testing" - "time" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/aws/session" ) func TestDescribeKeyPairs(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - _, err := GetKeyPairs(sess) - if err != nil { - t.Fatal(err) - } + _, err := GetKeyPairs(sess) + if err != nil { + t.Fatal(err) + } - t.Log("Retrieved key pairs") + t.Log("Retrieved key pairs") } diff --git a/go/ec2/DescribeSecurityGroups/DescribeSecurityGroups_test.go b/go/ec2/DescribeSecurityGroups/DescribeSecurityGroups_test.go index 4996da9f183..4c21fb12772 100644 --- a/go/ec2/DescribeSecurityGroups/DescribeSecurityGroups_test.go +++ b/go/ec2/DescribeSecurityGroups/DescribeSecurityGroups_test.go @@ -1,27 +1,28 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "testing" - "time" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/aws/session" ) func TestDescribeSecurityGroups(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - result, err := GetSecurityGroupInfo(sess) - if err != nil { - t.Fatal(err) - } + result, err := GetSecurityGroupInfo(sess) + if err != nil { + t.Fatal(err) + } - t.Log("Found", len(result.SecurityGroups), "security groups") + t.Log("Found", len(result.SecurityGroups), "security groups") } diff --git a/go/ec2/MonitorInstances/MonitorInstances_test.go b/go/ec2/MonitorInstances/MonitorInstances_test.go index eee29bc76c7..2b20d74e0f4 100644 --- a/go/ec2/MonitorInstances/MonitorInstances_test.go +++ b/go/ec2/MonitorInstances/MonitorInstances_test.go @@ -1,62 +1,63 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/aws/aws-sdk-go/service/ec2/ec2iface" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/service/ec2/ec2iface" ) // Define a mock struct to use in unit tests type mockEC2Client struct { - ec2iface.EC2API + ec2iface.EC2API } func (m *mockEC2Client) MonitorInstances(input *ec2.MonitorInstancesInput) (*ec2.MonitorInstancesOutput, error) { - // Check that required inputs exist - if input.InstanceIds == nil || *input.InstanceIds[0] == "" { - return nil, errors.New("MonitorInstancesInput.InstanceIds is nil or MonitorInstancesInput.InstanceIds[0] is an empty string") - } + // Check that required inputs exist + if input.InstanceIds == nil || *input.InstanceIds[0] == "" { + return nil, errors.New("MonitorInstancesInput.InstanceIds is nil or MonitorInstancesInput.InstanceIds[0] is an empty string") + } - resp := ec2.MonitorInstancesOutput{} - return &resp, nil + resp := ec2.MonitorInstancesOutput{} + return &resp, nil } func (m *mockEC2Client) UnmonitorInstances(input *ec2.UnmonitorInstancesInput) (*ec2.UnmonitorInstancesOutput, error) { - // Check that required inputs exist - if input.InstanceIds == nil || *input.InstanceIds[0] == "" { - return nil, errors.New("UnmonitorInstancesInput.InstanceIds is nil or UnmonitorInstancesInput.InstanceIds[0] is an empty string") - } + // Check that required inputs exist + if input.InstanceIds == nil || *input.InstanceIds[0] == "" { + return nil, errors.New("UnmonitorInstancesInput.InstanceIds is nil or UnmonitorInstancesInput.InstanceIds[0] is an empty string") + } - resp := ec2.UnmonitorInstancesOutput{} - return &resp, nil + resp := ec2.UnmonitorInstancesOutput{} + return &resp, nil } func TestMonitorInstances(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resources - instanceID := "test-instance-id" + // mock resources + instanceID := "test-instance-id" - mockSvc := &mockEC2Client{} + mockSvc := &mockEC2Client{} - _, err := EnableMonitoring(mockSvc, &instanceID) - if err != nil { - t.Fatal(err) - } + _, err := EnableMonitoring(mockSvc, &instanceID) + if err != nil { + t.Fatal(err) + } - t.Log("Enabled monitoring for instance with ID: " + instanceID) + t.Log("Enabled monitoring for instance with ID: " + instanceID) - _, err = DisableMonitoring(mockSvc, &instanceID) - if err != nil { - t.Fatal(err) - } + _, err = DisableMonitoring(mockSvc, &instanceID) + if err != nil { + t.Fatal(err) + } - t.Log("Disabled monitoring for instance with ID: " + instanceID) + t.Log("Disabled monitoring for instance with ID: " + instanceID) } diff --git a/go/ec2/RebootInstances/RebootInstances_test.go b/go/ec2/RebootInstances/RebootInstances_test.go index da2ae46cf77..2b100bc1056 100644 --- a/go/ec2/RebootInstances/RebootInstances_test.go +++ b/go/ec2/RebootInstances/RebootInstances_test.go @@ -1,45 +1,46 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/aws/aws-sdk-go/service/ec2/ec2iface" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/service/ec2/ec2iface" ) // Define a mock struct to use in unit tests type mockEC2Client struct { - ec2iface.EC2API + ec2iface.EC2API } func (m *mockEC2Client) RebootInstances(input *ec2.RebootInstancesInput) (*ec2.RebootInstancesOutput, error) { - // Check that required inputs exist - if input.InstanceIds[0] == nil || *input.InstanceIds[0] == "" { - return nil, errors.New("RebootInstancesInput.InstanceIds[0] is nil or an empty string") - } + // Check that required inputs exist + if input.InstanceIds[0] == nil || *input.InstanceIds[0] == "" { + return nil, errors.New("RebootInstancesInput.InstanceIds[0] is nil or an empty string") + } - resp := ec2.RebootInstancesOutput{} - return &resp, nil + resp := ec2.RebootInstancesOutput{} + return &resp, nil } func TestRebootInstances(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - instanceID := "test-instance-id" + // mock resource + instanceID := "test-instance-id" - mockSvc := &mockEC2Client{} + mockSvc := &mockEC2Client{} - err := RestartInstance(mockSvc, &instanceID) - if err != nil { - t.Fatal(err) - } + err := RestartInstance(mockSvc, &instanceID) + if err != nil { + t.Fatal(err) + } - t.Log("Rebooted instance with ID " + instanceID) + t.Log("Rebooted instance with ID " + instanceID) } diff --git a/go/ec2/RegionsAndZones/RegionsAndZones_test.go b/go/ec2/RegionsAndZones/RegionsAndZones_test.go index 299d7cf53ef..4199f7d0d46 100644 --- a/go/ec2/RegionsAndZones/RegionsAndZones_test.go +++ b/go/ec2/RegionsAndZones/RegionsAndZones_test.go @@ -1,32 +1,33 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "testing" - "time" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/aws/session" ) func TestRegionsAndZones(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - resultRegions, err := GetRegions(sess) - if err != nil { - t.Fatal(err) - } + resultRegions, err := GetRegions(sess) + if err != nil { + t.Fatal(err) + } - resultAvalZones, err := GetZones(sess) - if err != nil { - t.Fatal(err) - } + resultAvalZones, err := GetZones(sess) + if err != nil { + t.Fatal(err) + } - t.Log("Found", len(resultRegions.Regions), "regions; found", len(resultAvalZones.AvailabilityZones), "availability zones", "in", *sess.Config.Region) + t.Log("Found", len(resultRegions.Regions), "regions; found", len(resultAvalZones.AvailabilityZones), "availability zones", "in", *sess.Config.Region) } diff --git a/go/ec2/ReleaseAddress/ReleaseAddress_test.go b/go/ec2/ReleaseAddress/ReleaseAddress_test.go index 06976ecef15..3801a38a7da 100644 --- a/go/ec2/ReleaseAddress/ReleaseAddress_test.go +++ b/go/ec2/ReleaseAddress/ReleaseAddress_test.go @@ -1,45 +1,46 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/aws/aws-sdk-go/service/ec2/ec2iface" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/service/ec2/ec2iface" ) // Define a mock struct to use in unit tests type mockEC2Client struct { - ec2iface.EC2API + ec2iface.EC2API } func (m *mockEC2Client) ReleaseAddress(input *ec2.ReleaseAddressInput) (*ec2.ReleaseAddressOutput, error) { - // Check that required inputs exist - if input.AllocationId == nil || *input.AllocationId == "" { - return nil, errors.New("ReleaseAddressInput.AllocationId is nil or an empty string") - } + // Check that required inputs exist + if input.AllocationId == nil || *input.AllocationId == "" { + return nil, errors.New("ReleaseAddressInput.AllocationId is nil or an empty string") + } - resp := ec2.ReleaseAddressOutput{} - return &resp, nil + resp := ec2.ReleaseAddressOutput{} + return &resp, nil } func TestReleaseAddress(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - allocationID := "test-allocation-ID" + // mock resource + allocationID := "test-allocation-ID" - mockSvc := &mockEC2Client{} + mockSvc := &mockEC2Client{} - err := ClearAddress(mockSvc, &allocationID) - if err != nil { - t.Fatal(err) - } + err := ClearAddress(mockSvc, &allocationID) + if err != nil { + t.Fatal(err) + } - t.Log("Released allocated address") + t.Log("Released allocated address") } diff --git a/go/ec2/StartStopInstances/StartStopInstances_test.go b/go/ec2/StartStopInstances/StartStopInstances_test.go index 4bb678f99a4..0bb0f89d0e6 100644 --- a/go/ec2/StartStopInstances/StartStopInstances_test.go +++ b/go/ec2/StartStopInstances/StartStopInstances_test.go @@ -1,62 +1,63 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/ec2" - "github.com/aws/aws-sdk-go/service/ec2/ec2iface" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/service/ec2/ec2iface" ) // Define a mock struct to use in unit tests type mockEC2Client struct { - ec2iface.EC2API + ec2iface.EC2API } func (m *mockEC2Client) StartInstances(input *ec2.StartInstancesInput) (*ec2.StartInstancesOutput, error) { - // Check that required inputs exist - if input.InstanceIds == nil || *input.InstanceIds[0] == "" { - return nil, errors.New("StartInstances.Ids is nil or StartInstances.Ids[0] is an empty string") - } + // Check that required inputs exist + if input.InstanceIds == nil || *input.InstanceIds[0] == "" { + return nil, errors.New("StartInstances.Ids is nil or StartInstances.Ids[0] is an empty string") + } - resp := ec2.StartInstancesOutput{} - return &resp, nil + resp := ec2.StartInstancesOutput{} + return &resp, nil } func (m *mockEC2Client) StopInstances(input *ec2.StopInstancesInput) (*ec2.StopInstancesOutput, error) { - // Check that required inputs exist - if input.InstanceIds == nil || *input.InstanceIds[0] == "" { - return nil, errors.New("StopInstances.Ids is nil or StopInstances.Ids[0] is an empty string") - } + // Check that required inputs exist + if input.InstanceIds == nil || *input.InstanceIds[0] == "" { + return nil, errors.New("StopInstances.Ids is nil or StopInstances.Ids[0] is an empty string") + } - resp := ec2.StopInstancesOutput{} - return &resp, nil + resp := ec2.StopInstancesOutput{} + return &resp, nil } func TestStartStopInstance(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - instanceID := "test-RESOURCE" + // mock resource + instanceID := "test-RESOURCE" - mockSvc := &mockEC2Client{} + mockSvc := &mockEC2Client{} - err := StartInstance(mockSvc, &instanceID) - if err != nil { - t.Fatal(err) - } + err := StartInstance(mockSvc, &instanceID) + if err != nil { + t.Fatal(err) + } - t.Log("Started instance with ID " + instanceID) + t.Log("Started instance with ID " + instanceID) - err = StopInstance(mockSvc, &instanceID) - if err != nil { - t.Fatal(err) - } + err = StopInstance(mockSvc, &instanceID) + if err != nil { + t.Fatal(err) + } - t.Log("Stopped instance with ID " + instanceID) + t.Log("Stopped instance with ID " + instanceID) } diff --git a/go/example_code/cloudformation/CfnCrudOps.go b/go/example_code/cloudformation/CfnCrudOps.go index bcfdabfe377..3d5dcba9060 100644 --- a/go/example_code/cloudformation/CfnCrudOps.go +++ b/go/example_code/cloudformation/CfnCrudOps.go @@ -1,167 +1,156 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "flag" - "fmt" - "io/ioutil" + "flag" + "fmt" + "io/ioutil" - "github.com/google/uuid" + "github.com/google/uuid" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudformation" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudformation" ) // CreateStack creates a CloudFormation stack func CreateStack(sess *session.Session, stackName string, template string) error { - svc := cloudformation.New(sess) - // Open file template - // Get entire file as a string - content, err := ioutil.ReadFile(template) - if err != nil { - return err - } - - // Convert []byte to string - templateBody := string(content) - - input := &cloudformation.CreateStackInput{TemplateBody: aws.String(templateBody), StackName: aws.String(stackName)} - - _, err = svc.CreateStack(input) - if err != nil { - return err - } - - // Wait until stack is created - desInput := &cloudformation.DescribeStacksInput{StackName: aws.String(stackName)} - return svc.WaitUntilStackCreateComplete(desInput) + svc := cloudformation.New(sess) + // Open file template + // Get entire file as a string + content, err := ioutil.ReadFile(template) + if err != nil { + return err + } + + // Convert []byte to string + templateBody := string(content) + + input := &cloudformation.CreateStackInput{TemplateBody: aws.String(templateBody), StackName: aws.String(stackName)} + + _, err = svc.CreateStack(input) + if err != nil { + return err + } + + // Wait until stack is created + desInput := &cloudformation.DescribeStacksInput{StackName: aws.String(stackName)} + return svc.WaitUntilStackCreateComplete(desInput) } // GetStackSummaries gets a list of summary information about all stacks or those with status func GetStackSummaries(sess *session.Session, status string) ([]*cloudformation.StackSummary, error) { - svc := cloudformation.New(sess) - var stackSummaries []*cloudformation.StackSummary + svc := cloudformation.New(sess) + var stackSummaries []*cloudformation.StackSummary - var filter []*string + var filter []*string - if status != "all" { - filter = append(filter, aws.String(status)) - } + if status != "all" { + filter = append(filter, aws.String(status)) + } - input := &cloudformation.ListStacksInput{StackStatusFilter: filter} + input := &cloudformation.ListStacksInput{StackStatusFilter: filter} - resp, err := svc.ListStacks(input) - if err != nil { - return stackSummaries, err - } + resp, err := svc.ListStacks(input) + if err != nil { + return stackSummaries, err + } - return resp.StackSummaries, nil + return resp.StackSummaries, nil } // DeleteStack deletes the specified stack func DeleteStack(sess *session.Session, name string) error { - svc := cloudformation.New(sess) - delInput := &cloudformation.DeleteStackInput{StackName: aws.String(name)} - _, err := svc.DeleteStack(delInput) - if err != nil { - return err - } - - // Wait until stack is created - desInput := &cloudformation.DescribeStacksInput{StackName: aws.String(name)} - return svc.WaitUntilStackDeleteComplete(desInput) + svc := cloudformation.New(sess) + delInput := &cloudformation.DeleteStackInput{StackName: aws.String(name)} + _, err := svc.DeleteStack(delInput) + if err != nil { + return err + } + + // Wait until stack is created + desInput := &cloudformation.DescribeStacksInput{StackName: aws.String(name)} + return svc.WaitUntilStackDeleteComplete(desInput) } func main() { - operationPtr := flag.String("o", "", "The operation to perform: create, list, delete, or all in that order") - stackNamePtr := flag.String("n", "", "The name of the stack to create or delete") - templateFilePtr := flag.String("t", "", "The name of the file containing the CloudFormation template") - flag.Parse() - operation := *operationPtr - stackName := *stackNamePtr - templateFile := *templateFilePtr - - if (operation == "create" || operation == "delete" || operation == "all") && stackName == "" { - // Create dummy name using guid - // Create a unique GUID for stack name - id := uuid.New() - stackName = "stack-" + id.String() - } - - if (operation == "create" || operation == "all") && templateFile == "" { - fmt.Println("You must supply the name of the template to use to create a stack") - return - } - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - switch operation { - case "all": - // Create stack - err := CreateStack(sess, stackName, templateFile) - if err != nil { - fmt.Println("Could not create stack " + stackName) - } - - // Get all stacks - summaries, err := GetStackSummaries(sess, "all") - if err != nil { - fmt.Println("Could not list stack summary info") - return - } - - for _, s := range summaries { - fmt.Println(*s.StackName + ", Status: " + *s.StackStatus) - } - - fmt.Println("") - - // Delete stack - err = DeleteStack(sess, stackName) - if err != nil { - fmt.Println("Could not delete stack " + stackName) - } - case "create": - err := CreateStack(sess, stackName, templateFile) - if err != nil { - fmt.Println("Could not create stack " + stackName) - } - case "list": - summaries, err := GetStackSummaries(sess, "all") - if err != nil { - fmt.Println("Could not list stack summary info") - return - } - - for _, s := range summaries { - fmt.Println(*s.StackName + ", Status: " + *s.StackStatus) - } - - fmt.Println("") - case "delete": - err := DeleteStack(sess, stackName) - if err != nil { - fmt.Println("Could not delete stack " + stackName) - } - default: - fmt.Println("Unrecognized operation: " + operation) - } + operationPtr := flag.String("o", "", "The operation to perform: create, list, delete, or all in that order") + stackNamePtr := flag.String("n", "", "The name of the stack to create or delete") + templateFilePtr := flag.String("t", "", "The name of the file containing the CloudFormation template") + flag.Parse() + operation := *operationPtr + stackName := *stackNamePtr + templateFile := *templateFilePtr + + if (operation == "create" || operation == "delete" || operation == "all") && stackName == "" { + // Create dummy name using guid + // Create a unique GUID for stack name + id := uuid.New() + stackName = "stack-" + id.String() + } + + if (operation == "create" || operation == "all") && templateFile == "" { + fmt.Println("You must supply the name of the template to use to create a stack") + return + } + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + switch operation { + case "all": + // Create stack + err := CreateStack(sess, stackName, templateFile) + if err != nil { + fmt.Println("Could not create stack " + stackName) + } + + // Get all stacks + summaries, err := GetStackSummaries(sess, "all") + if err != nil { + fmt.Println("Could not list stack summary info") + return + } + + for _, s := range summaries { + fmt.Println(*s.StackName + ", Status: " + *s.StackStatus) + } + + fmt.Println("") + + // Delete stack + err = DeleteStack(sess, stackName) + if err != nil { + fmt.Println("Could not delete stack " + stackName) + } + case "create": + err := CreateStack(sess, stackName, templateFile) + if err != nil { + fmt.Println("Could not create stack " + stackName) + } + case "list": + summaries, err := GetStackSummaries(sess, "all") + if err != nil { + fmt.Println("Could not list stack summary info") + return + } + + for _, s := range summaries { + fmt.Println(*s.StackName + ", Status: " + *s.StackStatus) + } + + fmt.Println("") + case "delete": + err := DeleteStack(sess, stackName) + if err != nil { + fmt.Println("Could not delete stack " + stackName) + } + default: + fmt.Println("Unrecognized operation: " + operation) + } } diff --git a/go/example_code/cloudformation/CfnCrudOps_test.go b/go/example_code/cloudformation/CfnCrudOps_test.go index 6c132d5084b..ae7bcfdb9e6 100644 --- a/go/example_code/cloudformation/CfnCrudOps_test.go +++ b/go/example_code/cloudformation/CfnCrudOps_test.go @@ -1,32 +1,21 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "testing" - "time" + "encoding/json" + "io/ioutil" + "testing" + "time" - "github.com/google/uuid" + "github.com/google/uuid" - "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/aws/session" ) // Config stores our global configuration values (replace env values with these) type Config struct { - TemplateFile string `json:"TemplateFile"` + TemplateFile string `json:"TemplateFile"` } var configFileName = "config.json" @@ -35,96 +24,96 @@ var configFileName = "config.json" var globalConfig Config func PopulateConfiguration() error { - // Get and store configuration values from config.json + // Get and store configuration values from config.json - // Get entire file as a JSON string - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + // Get entire file as a JSON string + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - // Convert []byte to string - text := string(content) + // Convert []byte to string + text := string(content) - // Marshall JSON string in text into global struct - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + // Marshall JSON string in text into global struct + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - return nil + return nil } func isStackComplete(sess *session.Session, stackName string, status string) (bool, error) { - stacks, err := GetStackSummaries(sess, status) - if err != nil { - return false, err - } - - for _, s := range stacks { - if *s.StackName == stackName { - return true, nil - } - } - - return false, nil + stacks, err := GetStackSummaries(sess, status) + if err != nil { + return false, err + } + + for _, s := range stacks { + if *s.StackName == stackName { + return true, nil + } + } + + return false, nil } func TestCfnCrudOps(t *testing.T) { - // When the test started - thisTime := time.Now() - nowString := thisTime.Format("20060102150405") - t.Log("Started unit test at " + nowString) - - err := PopulateConfiguration() - if err != nil { - t.Fatal(err) - } - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file (~/.aws/credentials) - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create a unique GUID for stack name - id := uuid.New() - stackName := "stack-" + id.String() - - t.Log("Creating stack " + stackName) - - // Create stack - err = CreateStack(sess, stackName, globalConfig.TemplateFile) - if err != nil { - t.Fatal(err) - } - - // Double-check that stack is created - t.Log("Confirming whether stack was created") - created, err := isStackComplete(sess, stackName, "CREATE_COMPLETE") - if err != nil { - t.Fatal(err) - } - - if !created { - t.Fatal("Could not verify " + stackName + " was created") - } - - // Delete stack - t.Log("Deleting stack " + stackName) - err = DeleteStack(sess, stackName) - if err != nil { - t.Fatal(err) - } - - // Double-check that stack is deleted - t.Log("Confirming whether stack was deleted") - deleted, err := isStackComplete(sess, stackName, "DELETE_COMPLETE") - if err != nil { - t.Fatal(err) - } - - if !deleted { - t.Fatal("Could not verify " + stackName + " was deleted") - } + // When the test started + thisTime := time.Now() + nowString := thisTime.Format("20060102150405") + t.Log("Started unit test at " + nowString) + + err := PopulateConfiguration() + if err != nil { + t.Fatal(err) + } + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file (~/.aws/credentials) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create a unique GUID for stack name + id := uuid.New() + stackName := "stack-" + id.String() + + t.Log("Creating stack " + stackName) + + // Create stack + err = CreateStack(sess, stackName, globalConfig.TemplateFile) + if err != nil { + t.Fatal(err) + } + + // Double-check that stack is created + t.Log("Confirming whether stack was created") + created, err := isStackComplete(sess, stackName, "CREATE_COMPLETE") + if err != nil { + t.Fatal(err) + } + + if !created { + t.Fatal("Could not verify " + stackName + " was created") + } + + // Delete stack + t.Log("Deleting stack " + stackName) + err = DeleteStack(sess, stackName) + if err != nil { + t.Fatal(err) + } + + // Double-check that stack is deleted + t.Log("Confirming whether stack was deleted") + deleted, err := isStackComplete(sess, stackName, "DELETE_COMPLETE") + if err != nil { + t.Fatal(err) + } + + if !deleted { + t.Fatal("Could not verify " + stackName + " was deleted") + } } diff --git a/go/example_code/cloudtrail/create_trail.go b/go/example_code/cloudtrail/create_trail.go index b99e0bcd120..e8e560a8eb3 100644 --- a/go/example_code/cloudtrail/create_trail.go +++ b/go/example_code/cloudtrail/create_trail.go @@ -1,152 +1,130 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[create_trail.go demonstrates how to create a CloudTrail trail.] -// snippet-keyword:[Amazon CloudTrail] -// snippet-keyword:[CreateTrail function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[cloudtrail] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-1-6] -/* - Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cloudtrail.go.create_trail.complete] package main // snippet-start:[cloudtrail.go.create_trail.imports] import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudtrail" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/sts" - - "encoding/json" - "flag" - "fmt" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudtrail" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/sts" + + "encoding/json" + "flag" + "fmt" ) // snippet-end:[cloudtrail.go.create_trail.imports] func main() { - // Get required trail name and bucket name - // snippet-start:[cloudtrail.go.create_trail.vars] - trailNamePtr := flag.String("n", "", "The name of the trail") - bucketNamePtr := flag.String("b", "", "the name of the bucket to which the trails are uploaded") - addPolicyPtr := flag.Bool("p", false, "Whether to add the CloudTrail policy to the bucket") - - flag.Parse() - - if *trailNamePtr == "" || *bucketNamePtr == "" { - fmt.Println("You must supply a trail name and bucket name.") - return - } - // snippet-end:[cloudtrail.go.create_trail.vars] - - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - // snippet-start:[cloudtrail.go.create_trail.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[cloudtrail.go.create_trail.session] - - // snippet-start:[cloudtrail.go.create_trail.policy] - if *addPolicyPtr { - svc := sts.New(sess) - input := &sts.GetCallerIdentityInput{} - - result, err := svc.GetCallerIdentity(input) - if err != nil { - fmt.Println("Got error snarfing caller identity:") - fmt.Println(err.Error()) - return - } - - accountID := aws.StringValue(result.Account) - - s3Policy := map[string]interface{}{ - "Version": "2012-10-17", - "Statement": []map[string]interface{}{ - { - "Sid": "AWSCloudTrailAclCheck20150319", - "Effect": "Allow", - "Principal": map[string]interface{}{ - "Service": "cloudtrail.amazonaws.com", - }, - "Action": "s3:GetBucketAcl", - "Resource": "arn:aws:s3:::" + *bucketNamePtr, - }, - { - "Sid": "AWSCloudTrailWrite20150319", - "Effect": "Allow", - "Principal": map[string]interface{}{ - "Service": "cloudtrail.amazonaws.com", - }, - "Action": "s3:PutObject", - "Resource": "arn:aws:s3:::" + *bucketNamePtr + "/AWSLogs/" + accountID + "/*", - "Condition": map[string]interface{}{ - "StringEquals": map[string]interface{}{ - "s3:x-amz-acl": "bucket-owner-full-control", - }, - }, - }, - }, - } - - policy, err := json.Marshal(s3Policy) - if err != nil { - fmt.Println("Error marshalling request") - return - } - - // Create S3 service - s3Svc := s3.New(sess) - - // Now set the policy on the bucket - _, err = s3Svc.PutBucketPolicy(&s3.PutBucketPolicyInput{ - Bucket: aws.String(*bucketNamePtr), - Policy: aws.String(string(policy)), - }) - if err != nil { - fmt.Print("Got error adding bucket policy:") - fmt.Print(err.Error()) - return - } - - fmt.Printf("Successfully set bucket %q's policy\n", *bucketNamePtr) - } - // snippet-end:[cloudtrail.go.create_trail.policy] - - // snippet-start:[cloudtrail.go.create_trail.create] - svc := cloudtrail.New(sess) - - input := &cloudtrail.CreateTrailInput{ - Name: aws.String(*trailNamePtr), - S3BucketName: aws.String(*bucketNamePtr), - } - - _, err := svc.CreateTrail(input) - if err != nil { - fmt.Println("Got error calling CreateTrail:") - fmt.Println(err.Error()) - return - } - - fmt.Println("Created the trail", *trailNamePtr, "for bucket", *bucketNamePtr) - // snippet-end:[cloudtrail.go.create_trail.create] + // Get required trail name and bucket name + // snippet-start:[cloudtrail.go.create_trail.vars] + trailNamePtr := flag.String("n", "", "The name of the trail") + bucketNamePtr := flag.String("b", "", "the name of the bucket to which the trails are uploaded") + addPolicyPtr := flag.Bool("p", false, "Whether to add the CloudTrail policy to the bucket") + + flag.Parse() + + if *trailNamePtr == "" || *bucketNamePtr == "" { + fmt.Println("You must supply a trail name and bucket name.") + return + } + // snippet-end:[cloudtrail.go.create_trail.vars] + + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + // snippet-start:[cloudtrail.go.create_trail.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[cloudtrail.go.create_trail.session] + + // snippet-start:[cloudtrail.go.create_trail.policy] + if *addPolicyPtr { + svc := sts.New(sess) + input := &sts.GetCallerIdentityInput{} + + result, err := svc.GetCallerIdentity(input) + if err != nil { + fmt.Println("Got error snarfing caller identity:") + fmt.Println(err.Error()) + return + } + + accountID := aws.StringValue(result.Account) + + s3Policy := map[string]interface{}{ + "Version": "2012-10-17", + "Statement": []map[string]interface{}{ + { + "Sid": "AWSCloudTrailAclCheck20150319", + "Effect": "Allow", + "Principal": map[string]interface{}{ + "Service": "cloudtrail.amazonaws.com", + }, + "Action": "s3:GetBucketAcl", + "Resource": "arn:aws:s3:::" + *bucketNamePtr, + }, + { + "Sid": "AWSCloudTrailWrite20150319", + "Effect": "Allow", + "Principal": map[string]interface{}{ + "Service": "cloudtrail.amazonaws.com", + }, + "Action": "s3:PutObject", + "Resource": "arn:aws:s3:::" + *bucketNamePtr + "/AWSLogs/" + accountID + "/*", + "Condition": map[string]interface{}{ + "StringEquals": map[string]interface{}{ + "s3:x-amz-acl": "bucket-owner-full-control", + }, + }, + }, + }, + } + + policy, err := json.Marshal(s3Policy) + if err != nil { + fmt.Println("Error marshalling request") + return + } + + // Create S3 service + s3Svc := s3.New(sess) + + // Now set the policy on the bucket + _, err = s3Svc.PutBucketPolicy(&s3.PutBucketPolicyInput{ + Bucket: aws.String(*bucketNamePtr), + Policy: aws.String(string(policy)), + }) + if err != nil { + fmt.Print("Got error adding bucket policy:") + fmt.Print(err.Error()) + return + } + + fmt.Printf("Successfully set bucket %q's policy\n", *bucketNamePtr) + } + // snippet-end:[cloudtrail.go.create_trail.policy] + + // snippet-start:[cloudtrail.go.create_trail.create] + svc := cloudtrail.New(sess) + + input := &cloudtrail.CreateTrailInput{ + Name: aws.String(*trailNamePtr), + S3BucketName: aws.String(*bucketNamePtr), + } + + _, err := svc.CreateTrail(input) + if err != nil { + fmt.Println("Got error calling CreateTrail:") + fmt.Println(err.Error()) + return + } + + fmt.Println("Created the trail", *trailNamePtr, "for bucket", *bucketNamePtr) + // snippet-end:[cloudtrail.go.create_trail.create] } // snippet-end:[cloudtrail.go.create_trail.complete] diff --git a/go/example_code/cloudtrail/delete_trail.go b/go/example_code/cloudtrail/delete_trail.go index 372defe3589..a3e97441f26 100644 --- a/go/example_code/cloudtrail/delete_trail.go +++ b/go/example_code/cloudtrail/delete_trail.go @@ -1,75 +1,53 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Deletes an AWS CloudTrail trail.] -// snippet-keyword:[AWS CloudTrail] -// snippet-keyword:[DeleteTrail function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[cloudtrail] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-1-6] -/* - Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cloudtrail.go.delete_trail.complete] package main // snippet-start:[cloudtrail.go.delete_trail.imports] import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudtrail" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudtrail" - "flag" - "fmt" + "flag" + "fmt" ) // snippet-end:[cloudtrail.go.delete_trail.imports] func main() { - // Trail name required - // snippet-start:[cloudtrail.go.delete_trail.vars] - trailNamePtr := flag.String("n", "", "The name of the trail to delete") - - flag.Parse() - - if *trailNamePtr == "" { - fmt.Println("You must supply a trail name") - return - } - // snippet-end:[cloudtrail.go.delete_trail.vars] - - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - // snippet-start:[cloudtrail.go.delete_trail.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[cloudtrail.go.delete_trail.session] - - // snippet-start:[cloudtrail.go.delete_trail.delete] - svc := cloudtrail.New(sess) - - _, err := svc.DeleteTrail(&cloudtrail.DeleteTrailInput{Name: aws.String(*trailNamePtr)}) - if err != nil { - fmt.Println("Got error calling CreateTrail:") - fmt.Println(err.Error()) - return - } - - fmt.Println("Successfully deleted trail", *trailNamePtr) - // snippet-end:[cloudtrail.go.delete_trail.delete] + // Trail name required + // snippet-start:[cloudtrail.go.delete_trail.vars] + trailNamePtr := flag.String("n", "", "The name of the trail to delete") + + flag.Parse() + + if *trailNamePtr == "" { + fmt.Println("You must supply a trail name") + return + } + // snippet-end:[cloudtrail.go.delete_trail.vars] + + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + // snippet-start:[cloudtrail.go.delete_trail.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[cloudtrail.go.delete_trail.session] + + // snippet-start:[cloudtrail.go.delete_trail.delete] + svc := cloudtrail.New(sess) + + _, err := svc.DeleteTrail(&cloudtrail.DeleteTrailInput{Name: aws.String(*trailNamePtr)}) + if err != nil { + fmt.Println("Got error calling CreateTrail:") + fmt.Println(err.Error()) + return + } + + fmt.Println("Successfully deleted trail", *trailNamePtr) + // snippet-end:[cloudtrail.go.delete_trail.delete] } // snippet-end:[cloudtrail.go.delete_trail.complete] diff --git a/go/example_code/cloudtrail/describe_trails.go b/go/example_code/cloudtrail/describe_trails.go index 6a59e3502e5..fc535314f29 100644 --- a/go/example_code/cloudtrail/describe_trails.go +++ b/go/example_code/cloudtrail/describe_trails.go @@ -1,60 +1,38 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Lists the AWS CloudTrail trails.] -// snippet-keyword:[AWS CloudTrail] -// snippet-keyword:[DescribeTrails function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[cloudtrail] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudtrail" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudtrail" ) func main() { - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create CloudTrail client - svc := cloudtrail.New(sess) - - resp, err := svc.DescribeTrails(&cloudtrail.DescribeTrailsInput{TrailNameList: nil}) - if err != nil { - fmt.Println("Got error calling CreateTrail:") - fmt.Println(err.Error()) - return - } - - fmt.Println("Found", len(resp.TrailList), "trail(s)") - fmt.Println("") - - for _, trail := range resp.TrailList { - fmt.Println("Trail name: " + *trail.Name) - fmt.Println("Bucket name: " + *trail.S3BucketName) - fmt.Println("") - } + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create CloudTrail client + svc := cloudtrail.New(sess) + + resp, err := svc.DescribeTrails(&cloudtrail.DescribeTrailsInput{TrailNameList: nil}) + if err != nil { + fmt.Println("Got error calling CreateTrail:") + fmt.Println(err.Error()) + return + } + + fmt.Println("Found", len(resp.TrailList), "trail(s)") + fmt.Println("") + + for _, trail := range resp.TrailList { + fmt.Println("Trail name: " + *trail.Name) + fmt.Println("Bucket name: " + *trail.S3BucketName) + fmt.Println("") + } } diff --git a/go/example_code/cloudtrail/lookup_events.go b/go/example_code/cloudtrail/lookup_events.go index 2db22639430..279ab3aaff0 100644 --- a/go/example_code/cloudtrail/lookup_events.go +++ b/go/example_code/cloudtrail/lookup_events.go @@ -1,96 +1,74 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Lists the AWS CloudTrail events.] -// snippet-keyword:[AWS CloudTrail] -// snippet-keyword:[LookupEvents function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[cloudtrail] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-1-6] -/* - Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cloudtrail.go.lookup_events.complete] package main // snippet-start:[cloudtrail.go.lookup_events.imports] import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudtrail" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudtrail" - "flag" - "fmt" - "time" + "flag" + "fmt" + "time" ) // snippet-end:[cloudtrail.go.lookup_events.imports] func main() { - // Trail name required - // snippet-start:[cloudtrail.go.lookup_events.vars] - trailNamePtr := flag.String("n", "", "The name of the trail") - - flag.Parse() - - if *trailNamePtr == "" { - fmt.Println("You must supply a trail name") - return - } - // snippet-end:[cloudtrail.go.lookup_events.vars] - - // snippet-start:[cloudtrail.go.lookup_events.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[cloudtrail.go.lookup_events.session] - - // snippet-start:[cloudtrail.go.lookup_events.lookup] - svc := cloudtrail.New(sess) - - input := &cloudtrail.LookupEventsInput{EndTime: aws.Time(time.Now())} - - resp, err := svc.LookupEvents(input) - if err != nil { - fmt.Println("Got error calling CreateTrail:") - fmt.Println(err.Error()) - return - } - - fmt.Println("Found", len(resp.Events), "events before now") - fmt.Println("") - - for _, event := range resp.Events { - fmt.Println("Event:") - fmt.Println(aws.StringValue(event.CloudTrailEvent)) - fmt.Println("") - fmt.Println("Name ", aws.StringValue(event.EventName)) - fmt.Println("ID: ", aws.StringValue(event.EventId)) - fmt.Println("Time: ", aws.TimeValue(event.EventTime)) - fmt.Println("User: ", aws.StringValue(event.Username)) - - fmt.Println("Resources:") - - for _, resource := range event.Resources { - fmt.Println(" Name:", aws.StringValue(resource.ResourceName)) - fmt.Println(" Type:", aws.StringValue(resource.ResourceType)) - } - - fmt.Println("") - // snippet-end:[cloudtrail.go.lookup_events.lookup] - } + // Trail name required + // snippet-start:[cloudtrail.go.lookup_events.vars] + trailNamePtr := flag.String("n", "", "The name of the trail") + + flag.Parse() + + if *trailNamePtr == "" { + fmt.Println("You must supply a trail name") + return + } + // snippet-end:[cloudtrail.go.lookup_events.vars] + + // snippet-start:[cloudtrail.go.lookup_events.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[cloudtrail.go.lookup_events.session] + + // snippet-start:[cloudtrail.go.lookup_events.lookup] + svc := cloudtrail.New(sess) + + input := &cloudtrail.LookupEventsInput{EndTime: aws.Time(time.Now())} + + resp, err := svc.LookupEvents(input) + if err != nil { + fmt.Println("Got error calling CreateTrail:") + fmt.Println(err.Error()) + return + } + + fmt.Println("Found", len(resp.Events), "events before now") + fmt.Println("") + + for _, event := range resp.Events { + fmt.Println("Event:") + fmt.Println(aws.StringValue(event.CloudTrailEvent)) + fmt.Println("") + fmt.Println("Name ", aws.StringValue(event.EventName)) + fmt.Println("ID: ", aws.StringValue(event.EventId)) + fmt.Println("Time: ", aws.TimeValue(event.EventTime)) + fmt.Println("User: ", aws.StringValue(event.Username)) + + fmt.Println("Resources:") + + for _, resource := range event.Resources { + fmt.Println(" Name:", aws.StringValue(resource.ResourceName)) + fmt.Println(" Type:", aws.StringValue(resource.ResourceType)) + } + + fmt.Println("") + // snippet-end:[cloudtrail.go.lookup_events.lookup] + } } // snippet-end:[cloudtrail.go.lookup_events.complete] diff --git a/go/example_code/cloudwatch/create_enable_alarms.go b/go/example_code/cloudwatch/create_enable_alarms.go index 092bf71c92e..2a06d7aae82 100644 --- a/go/example_code/cloudwatch/create_enable_alarms.go +++ b/go/example_code/cloudwatch/create_enable_alarms.go @@ -1,102 +1,79 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Creates and enables an action on an alarm.] -// snippet-keyword:[AWS CloudWatch] -// snippet-keyword:[EnableAlarmActions function] -// snippet-keyword:[PutMetricAlarm function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[cloudwatch] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatch" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatch" - "fmt" - "os" + "fmt" + "os" ) func main() { - if len(os.Args) != 4 { - fmt.Println("You must supply an instance name, value, and alarm name") - os.Exit(1) - } + if len(os.Args) != 4 { + fmt.Println("You must supply an instance name, value, and alarm name") + os.Exit(1) + } + + instance := os.Args[1] + value := os.Args[2] + name := os.Args[3] - instance := os.Args[1] - value := os.Args[2] - name := os.Args[3] - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - // Create new CloudWatch client. - svc := cloudwatch.New(sess) + // Create new CloudWatch client. + svc := cloudwatch.New(sess) - // Create a metric alarm that reboots an instance if its CPU utilization is - // greater than 70.0%. - _, err := svc.PutMetricAlarm(&cloudwatch.PutMetricAlarmInput{ - AlarmName: aws.String(name), - ComparisonOperator: aws.String(cloudwatch.ComparisonOperatorGreaterThanThreshold), - EvaluationPeriods: aws.Int64(1), - MetricName: aws.String("CPUUtilization"), - Namespace: aws.String("AWS/EC2"), - Period: aws.Int64(60), - Statistic: aws.String(cloudwatch.StatisticAverage), - Threshold: aws.Float64(70.0), - ActionsEnabled: aws.Bool(true), - AlarmDescription: aws.String("Alarm when server CPU exceeds 70%"), - Unit: aws.String(cloudwatch.StandardUnitSeconds), + // Create a metric alarm that reboots an instance if its CPU utilization is + // greater than 70.0%. + _, err := svc.PutMetricAlarm(&cloudwatch.PutMetricAlarmInput{ + AlarmName: aws.String(name), + ComparisonOperator: aws.String(cloudwatch.ComparisonOperatorGreaterThanThreshold), + EvaluationPeriods: aws.Int64(1), + MetricName: aws.String("CPUUtilization"), + Namespace: aws.String("AWS/EC2"), + Period: aws.Int64(60), + Statistic: aws.String(cloudwatch.StatisticAverage), + Threshold: aws.Float64(70.0), + ActionsEnabled: aws.Bool(true), + AlarmDescription: aws.String("Alarm when server CPU exceeds 70%"), + Unit: aws.String(cloudwatch.StandardUnitSeconds), - // This is apart of the default workflow actions. This one will reboot the instance, if the - // alarm is triggered. - AlarmActions: []*string{ - aws.String(fmt.Sprintf("arn:aws:swf:us-east-1:%s:action/actions/AWS_EC2.InstanceId.Reboot/1.0", instance)), - }, - Dimensions: []*cloudwatch.Dimension{ - { - Name: aws.String("InstanceId"), - Value: aws.String(value), - }, - }, - }) - if err != nil { - fmt.Println("Error", err) - return - } + // This is apart of the default workflow actions. This one will reboot the instance, if the + // alarm is triggered. + AlarmActions: []*string{ + aws.String(fmt.Sprintf("arn:aws:swf:us-east-1:%s:action/actions/AWS_EC2.InstanceId.Reboot/1.0", instance)), + }, + Dimensions: []*cloudwatch.Dimension{ + { + Name: aws.String("InstanceId"), + Value: aws.String(value), + }, + }, + }) + if err != nil { + fmt.Println("Error", err) + return + } - // This will enable the alarm to our instance. - result, err := svc.EnableAlarmActions(&cloudwatch.EnableAlarmActionsInput{ - AlarmNames: []*string{ - aws.String(name), - }, - }) - if err != nil { - fmt.Println("Error", err) - return - } + // This will enable the alarm to our instance. + result, err := svc.EnableAlarmActions(&cloudwatch.EnableAlarmActionsInput{ + AlarmNames: []*string{ + aws.String(name), + }, + }) + if err != nil { + fmt.Println("Error", err) + return + } - fmt.Println("Alarm action enabled", result) + fmt.Println("Alarm action enabled", result) } diff --git a/go/example_code/cloudwatch/custom_metrics.go b/go/example_code/cloudwatch/custom_metrics.go index 6e4882a58e0..91bb36ba63d 100644 --- a/go/example_code/cloudwatch/custom_metrics.go +++ b/go/example_code/cloudwatch/custom_metrics.go @@ -1,108 +1,85 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Ret.] -// snippet-keyword:[AWS CloudWatch] -// snippet-keyword:[ListMetrics function] -// snippet-keyword:[PutMetricData function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[cloudwatch] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatch" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatch" - "fmt" + "fmt" ) func main() { - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - // Create new cloudwatch client. - svc := cloudwatch.New(sess) + // Create new cloudwatch client. + svc := cloudwatch.New(sess) - _, err := svc.PutMetricData(&cloudwatch.PutMetricDataInput{ - Namespace: aws.String("Site/Traffic"), - MetricData: []*cloudwatch.MetricDatum{ - &cloudwatch.MetricDatum{ - MetricName: aws.String("UniqueVisitors"), - Unit: aws.String("Count"), - Value: aws.Float64(5885.0), - Dimensions: []*cloudwatch.Dimension{ - &cloudwatch.Dimension{ - Name: aws.String("SiteName"), - Value: aws.String("example.com"), - }, - }, - }, - &cloudwatch.MetricDatum{ - MetricName: aws.String("UniqueVisits"), - Unit: aws.String("Count"), - Value: aws.Float64(8628.0), - Dimensions: []*cloudwatch.Dimension{ - &cloudwatch.Dimension{ - Name: aws.String("SiteName"), - Value: aws.String("example.com"), - }, - }, - }, - &cloudwatch.MetricDatum{ - MetricName: aws.String("PageViews"), - Unit: aws.String("Count"), - Value: aws.Float64(18057.0), - Dimensions: []*cloudwatch.Dimension{ - &cloudwatch.Dimension{ - Name: aws.String("PageURL"), - Value: aws.String("my-page.html"), - }, - }, - }, - }, - }) - if err != nil { - fmt.Println("Error adding metrics:", err.Error()) - return - } + _, err := svc.PutMetricData(&cloudwatch.PutMetricDataInput{ + Namespace: aws.String("Site/Traffic"), + MetricData: []*cloudwatch.MetricDatum{ + &cloudwatch.MetricDatum{ + MetricName: aws.String("UniqueVisitors"), + Unit: aws.String("Count"), + Value: aws.Float64(5885.0), + Dimensions: []*cloudwatch.Dimension{ + &cloudwatch.Dimension{ + Name: aws.String("SiteName"), + Value: aws.String("example.com"), + }, + }, + }, + &cloudwatch.MetricDatum{ + MetricName: aws.String("UniqueVisits"), + Unit: aws.String("Count"), + Value: aws.Float64(8628.0), + Dimensions: []*cloudwatch.Dimension{ + &cloudwatch.Dimension{ + Name: aws.String("SiteName"), + Value: aws.String("example.com"), + }, + }, + }, + &cloudwatch.MetricDatum{ + MetricName: aws.String("PageViews"), + Unit: aws.String("Count"), + Value: aws.Float64(18057.0), + Dimensions: []*cloudwatch.Dimension{ + &cloudwatch.Dimension{ + Name: aws.String("PageURL"), + Value: aws.String("my-page.html"), + }, + }, + }, + }, + }) + if err != nil { + fmt.Println("Error adding metrics:", err.Error()) + return + } - // Get information about metrics - result, err := svc.ListMetrics(&cloudwatch.ListMetricsInput{ - Namespace: aws.String("Site/Traffic"), - }) - if err != nil { - fmt.Println("Error getting metrics:", err.Error()) - return - } + // Get information about metrics + result, err := svc.ListMetrics(&cloudwatch.ListMetricsInput{ + Namespace: aws.String("Site/Traffic"), + }) + if err != nil { + fmt.Println("Error getting metrics:", err.Error()) + return + } - for _, metric := range result.Metrics { - fmt.Println(*metric.MetricName) + for _, metric := range result.Metrics { + fmt.Println(*metric.MetricName) - for _, dim := range metric.Dimensions { - fmt.Println(*dim.Name + ":", *dim.Value) - fmt.Println() - } - } + for _, dim := range metric.Dimensions { + fmt.Println(*dim.Name+":", *dim.Value) + fmt.Println() + } + } } diff --git a/go/example_code/cloudwatch/delete_alarms.go b/go/example_code/cloudwatch/delete_alarms.go index 9c3d52280b9..b073f223ad6 100644 --- a/go/example_code/cloudwatch/delete_alarms.go +++ b/go/example_code/cloudwatch/delete_alarms.go @@ -1,60 +1,38 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Deletes a CloudWatch alarm.] -// snippet-keyword:[Amazon CloudWatch] -// snippet-keyword:[DeleteAlarms function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[cloudwatch] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatch" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatch" - "fmt" + "fmt" ) func main() { - sess, err := session.NewSession() - if err != nil { - fmt.Println("failed to create session,", err) - return - } - - svc := cloudwatch.New(sess) - - params := &cloudwatch.DeleteAlarmsInput{ - AlarmNames: []*string{ - aws.String("AlarmName"), - // More values... - }} - - resp, err := svc.DeleteAlarms(params) - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) + sess, err := session.NewSession() + if err != nil { + fmt.Println("failed to create session,", err) + return + } + + svc := cloudwatch.New(sess) + + params := &cloudwatch.DeleteAlarmsInput{ + AlarmNames: []*string{ + aws.String("AlarmName"), + // More values... + }} + + resp, err := svc.DeleteAlarms(params) + if err != nil { + // Print the error, cast err to awserr.Error to get the Code and + // Message from an error. + fmt.Println(err.Error()) + return + } + + // Pretty-print the response data. + fmt.Println(resp) } diff --git a/go/example_code/cloudwatch/describe_alarm_history.go b/go/example_code/cloudwatch/describe_alarm_history.go index beed130d1ea..0827431f059 100644 --- a/go/example_code/cloudwatch/describe_alarm_history.go +++ b/go/example_code/cloudwatch/describe_alarm_history.go @@ -1,65 +1,42 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Gets the history for a CloudWatch alarm.] -// snippet-keyword:[Amazon CloudWatch] -// snippet-keyword:[DescribeAlarmHistory function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[cloudwatch] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatch" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatch" - "fmt" - "os" + "fmt" + "os" ) func main() { - // Must have one arg, the name of the alarm - if len(os.Args) != 2 { - fmt.Println("You must supply an alarm name") - os.Exit(1) - } + // Must have one arg, the name of the alarm + if len(os.Args) != 2 { + fmt.Println("You must supply an alarm name") + os.Exit(1) + } - alarmName := os.Args[1] + alarmName := os.Args[1] - sess, err := session.NewSession() - if err != nil { - fmt.Println("failed to create session,", err) - os.Exit(1) - } + sess, err := session.NewSession() + if err != nil { + fmt.Println("failed to create session,", err) + os.Exit(1) + } - svc := cloudwatch.New(sess, &aws.Config{Region: aws.String("us-west-2")}) + svc := cloudwatch.New(sess, &aws.Config{Region: aws.String("us-west-2")}) - params := &cloudwatch.DescribeAlarmHistoryInput{ - AlarmName: aws.String(alarmName), + params := &cloudwatch.DescribeAlarmHistoryInput{ + AlarmName: aws.String(alarmName), + } - } - - resp, err := svc.DescribeAlarmHistory(params) - if err != nil { - fmt.Println(err.Error()) - os.Exit(1) - } + resp, err := svc.DescribeAlarmHistory(params) + if err != nil { + fmt.Println(err.Error()) + os.Exit(1) + } - fmt.Println(resp) + fmt.Println(resp) } diff --git a/go/example_code/cloudwatch/describe_alarms.go b/go/example_code/cloudwatch/describe_alarms.go index d4f246a05fa..3d7135ef2e1 100644 --- a/go/example_code/cloudwatch/describe_alarms.go +++ b/go/example_code/cloudwatch/describe_alarms.go @@ -1,55 +1,33 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Describes the Amazon Cloudwatch alarms.] -// snippet-keyword:[Amazon CloudWatch] -// snippet-keyword:[DescribeAlarms function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[cloudwatch] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatch" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatch" - "fmt" - "os" + "fmt" + "os" ) func main() { - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := cloudwatch.New(sess) - - resp, err := svc.DescribeAlarms(nil) - if err != nil { - fmt.Println("Got error getting alarm descriptions:") - fmt.Println(err.Error()) - os.Exit(1) - } - - for _, alarm := range resp.MetricAlarms { - fmt.Println(*alarm.AlarmName) - } + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := cloudwatch.New(sess) + + resp, err := svc.DescribeAlarms(nil) + if err != nil { + fmt.Println("Got error getting alarm descriptions:") + fmt.Println(err.Error()) + os.Exit(1) + } + + for _, alarm := range resp.MetricAlarms { + fmt.Println(*alarm.AlarmName) + } } diff --git a/go/example_code/cloudwatch/describe_alarms_for_metric.go b/go/example_code/cloudwatch/describe_alarms_for_metric.go index f2a2a1e50ec..3044dc2e693 100644 --- a/go/example_code/cloudwatch/describe_alarms_for_metric.go +++ b/go/example_code/cloudwatch/describe_alarms_for_metric.go @@ -1,70 +1,48 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Gets the CloudWatch alarms for a specific metric.] -// snippet-keyword:[Amazon CloudWatch] -// snippet-keyword:[DescribeAlarmsForMetric function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[cloudwatch] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatch" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatch" - "fmt" + "fmt" ) func main() { - sess, err := session.NewSession() - if err != nil { - fmt.Println("failed to create session,", err) - return - } - - svc := cloudwatch.New(sess) - - params := &cloudwatch.DescribeAlarmsForMetricInput{ - MetricName: aws.String("MetricName"), // Required - Namespace: aws.String("Namespace"), // Required - Dimensions: []*cloudwatch.Dimension{ - { // Required - Name: aws.String("DimensionName"), // Required - Value: aws.String("DimensionValue"), // Required - }, - // More values... - }, - ExtendedStatistic: aws.String("ExtendedStatistic"), - Period: aws.Int64(1), - Statistic: aws.String("Statistic"), - Unit: aws.String("StandardUnit"), - } - - resp, err := svc.DescribeAlarmsForMetric(params) - if err != nil { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - return - } - - // Pretty-print the response data. - fmt.Println(resp) + sess, err := session.NewSession() + if err != nil { + fmt.Println("failed to create session,", err) + return + } + + svc := cloudwatch.New(sess) + + params := &cloudwatch.DescribeAlarmsForMetricInput{ + MetricName: aws.String("MetricName"), // Required + Namespace: aws.String("Namespace"), // Required + Dimensions: []*cloudwatch.Dimension{ + { // Required + Name: aws.String("DimensionName"), // Required + Value: aws.String("DimensionValue"), // Required + }, + // More values... + }, + ExtendedStatistic: aws.String("ExtendedStatistic"), + Period: aws.Int64(1), + Statistic: aws.String("Statistic"), + Unit: aws.String("StandardUnit"), + } + + resp, err := svc.DescribeAlarmsForMetric(params) + if err != nil { + // Print the error, cast err to awserr.Error to get the Code and + // Message from an error. + fmt.Println(err.Error()) + return + } + + // Pretty-print the response data. + fmt.Println(resp) } diff --git a/go/example_code/cloudwatch/disable_alarm.go b/go/example_code/cloudwatch/disable_alarm.go index 1b9bebb8acf..2cbd2b2012a 100644 --- a/go/example_code/cloudwatch/disable_alarm.go +++ b/go/example_code/cloudwatch/disable_alarm.go @@ -1,67 +1,45 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Disables the actions on an alarm.] -// snippet-keyword:[AWS CloudWatch] -// snippet-keyword:[DisableAlarmActions function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[cloudwatch] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatch" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatch" - "fmt" - "os" + "fmt" + "os" ) func main() { - if len(os.Args) != 2 { - fmt.Println("You must supply an alarm name") - os.Exit(1) - } - - name := os.Args[1] - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create new CloudWatch client. - svc := cloudwatch.New(sess) - - // Disable the alarm. - _, err := svc.DisableAlarmActions(&cloudwatch.DisableAlarmActionsInput{ - AlarmNames: []*string{ - aws.String(name), - }, - }) - if err != nil { - fmt.Println("Error", err) - return - } - - fmt.Println("Success") + if len(os.Args) != 2 { + fmt.Println("You must supply an alarm name") + os.Exit(1) + } + + name := os.Args[1] + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create new CloudWatch client. + svc := cloudwatch.New(sess) + + // Disable the alarm. + _, err := svc.DisableAlarmActions(&cloudwatch.DisableAlarmActionsInput{ + AlarmNames: []*string{ + aws.String(name), + }, + }) + if err != nil { + fmt.Println("Error", err) + return + } + + fmt.Println("Success") } diff --git a/go/example_code/cloudwatch/events_put_events.go b/go/example_code/cloudwatch/events_put_events.go index 23455c7d584..3bf8f381243 100644 --- a/go/example_code/cloudwatch/events_put_events.go +++ b/go/example_code/cloudwatch/events_put_events.go @@ -1,65 +1,43 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Sends an event that is matched to targets for handling.] -// snippet-keyword:[AWS CloudWatch] -// snippet-keyword:[PutEvents function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[cloudwatch] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatchevents" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatchevents" - "fmt" + "fmt" ) func main() { - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create the cloudwatch events client - svc := cloudwatchevents.New(sess) - - result, err := svc.PutEvents(&cloudwatchevents.PutEventsInput{ - Entries: []*cloudwatchevents.PutEventsRequestEntry{ - &cloudwatchevents.PutEventsRequestEntry{ - Detail: aws.String("{ \"key1\": \"value1\", \"key2\": \"value2\" }"), - DetailType: aws.String("appRequestSubmitted"), - Resources: []*string{ - aws.String("RESOURCE_ARN"), - }, - Source: aws.String("com.company.myapp"), - }, - }, - }) - if err != nil { - fmt.Println("Error", err) - return - } - - fmt.Println("Ingested events:", result.Entries) + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create the cloudwatch events client + svc := cloudwatchevents.New(sess) + + result, err := svc.PutEvents(&cloudwatchevents.PutEventsInput{ + Entries: []*cloudwatchevents.PutEventsRequestEntry{ + &cloudwatchevents.PutEventsRequestEntry{ + Detail: aws.String("{ \"key1\": \"value1\", \"key2\": \"value2\" }"), + DetailType: aws.String("appRequestSubmitted"), + Resources: []*string{ + aws.String("RESOURCE_ARN"), + }, + Source: aws.String("com.company.myapp"), + }, + }, + }) + if err != nil { + fmt.Println("Error", err) + return + } + + fmt.Println("Ingested events:", result.Entries) } diff --git a/go/example_code/cloudwatch/events_put_targets.go b/go/example_code/cloudwatch/events_put_targets.go index 020601dbced..3172f0e9d6a 100644 --- a/go/example_code/cloudwatch/events_put_targets.go +++ b/go/example_code/cloudwatch/events_put_targets.go @@ -1,62 +1,40 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Defines a target to respond to an event.] -// snippet-keyword:[AWS CloudWatch] -// snippet-keyword:[PutTargets function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[cloudwatch] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatchevents" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatchevents" - "fmt" + "fmt" ) func main() { - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create the cloudwatch events client - svc := cloudwatchevents.New(sess) - - result, err := svc.PutTargets(&cloudwatchevents.PutTargetsInput{ - Rule: aws.String("DEMO_EVENT"), - Targets: []*cloudwatchevents.Target{ - &cloudwatchevents.Target{ - Arn: aws.String("LAMBDA_FUNCTION_ARN"), - Id: aws.String("myCloudWatchEventsTarget"), - }, - }, - }) - if err != nil { - fmt.Println("Error", err) - return - } - - fmt.Println("Success", result) + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create the cloudwatch events client + svc := cloudwatchevents.New(sess) + + result, err := svc.PutTargets(&cloudwatchevents.PutTargetsInput{ + Rule: aws.String("DEMO_EVENT"), + Targets: []*cloudwatchevents.Target{ + &cloudwatchevents.Target{ + Arn: aws.String("LAMBDA_FUNCTION_ARN"), + Id: aws.String("myCloudWatchEventsTarget"), + }, + }, + }) + if err != nil { + fmt.Println("Error", err) + return + } + + fmt.Println("Success", result) } diff --git a/go/example_code/cloudwatch/events_schedule_rule.go b/go/example_code/cloudwatch/events_schedule_rule.go index a8124cd2cc2..d4712db94f9 100644 --- a/go/example_code/cloudwatch/events_schedule_rule.go +++ b/go/example_code/cloudwatch/events_schedule_rule.go @@ -1,58 +1,36 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Creates a rule used to trigger an event.] -// snippet-keyword:[AWS CloudWatch] -// snippet-keyword:[PutRule function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[cloudwatch] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatchevents" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatchevents" - "fmt" + "fmt" ) func main() { - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create the cloudwatch events client - svc := cloudwatchevents.New(sess) - - result, err := svc.PutRule(&cloudwatchevents.PutRuleInput{ - Name: aws.String("DEMO_EVENT"), - RoleArn: aws.String("IAM_ROLE_ARN"), - ScheduleExpression: aws.String("rate(5 minutes)"), - }) - if err != nil { - fmt.Println("Error", err) - return - } - - fmt.Println("Rule ARN:", result.RuleArn) + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create the cloudwatch events client + svc := cloudwatchevents.New(sess) + + result, err := svc.PutRule(&cloudwatchevents.PutRuleInput{ + Name: aws.String("DEMO_EVENT"), + RoleArn: aws.String("IAM_ROLE_ARN"), + ScheduleExpression: aws.String("rate(5 minutes)"), + }) + if err != nil { + fmt.Println("Error", err) + return + } + + fmt.Println("Rule ARN:", result.RuleArn) } diff --git a/go/example_code/cloudwatch/listing_metrics.go b/go/example_code/cloudwatch/listing_metrics.go index 6ec9a7b65f5..7f99fc43787 100644 --- a/go/example_code/cloudwatch/listing_metrics.go +++ b/go/example_code/cloudwatch/listing_metrics.go @@ -1,73 +1,51 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Retrieves a list of published AWS CloudWatch metrics.] -// snippet-keyword:[AWS CloudWatch] -// snippet-keyword:[ListMetrics function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[cloudwatch] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cloudwatch" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cloudwatch" - "fmt" - "os" + "fmt" + "os" ) func main() { - if len(os.Args) != 4 { - fmt.Println("You must supply a metric name, namespace, and dimension name") - os.Exit(1) - } - - metric := os.Args[1] - namespace := os.Args[2] - dimension := os.Args[3] - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create CloudWatch client - svc := cloudwatch.New(sess) - - // Get the list of metrics matching your criteria - result, err := svc.ListMetrics(&cloudwatch.ListMetricsInput{ - MetricName: aws.String(metric), - Namespace: aws.String(namespace), - Dimensions: []*cloudwatch.DimensionFilter{ - &cloudwatch.DimensionFilter{ - Name: aws.String(dimension), - }, - }, - }) - if err != nil { - fmt.Println("Error", err) - return - } - - fmt.Println("Metrics", result.Metrics) + if len(os.Args) != 4 { + fmt.Println("You must supply a metric name, namespace, and dimension name") + os.Exit(1) + } + + metric := os.Args[1] + namespace := os.Args[2] + dimension := os.Args[3] + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create CloudWatch client + svc := cloudwatch.New(sess) + + // Get the list of metrics matching your criteria + result, err := svc.ListMetrics(&cloudwatch.ListMetricsInput{ + MetricName: aws.String(metric), + Namespace: aws.String(namespace), + Dimensions: []*cloudwatch.DimensionFilter{ + &cloudwatch.DimensionFilter{ + Name: aws.String(dimension), + }, + }, + }) + if err != nil { + fmt.Println("Error", err) + return + } + + fmt.Println("Metrics", result.Metrics) } diff --git a/go/example_code/codebuild/cb_build_project.go b/go/example_code/codebuild/cb_build_project.go index 172484980f4..ea6f0d7c12f 100644 --- a/go/example_code/codebuild/cb_build_project.go +++ b/go/example_code/codebuild/cb_build_project.go @@ -1,64 +1,42 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Builds the AWS CodeBuild project specified on the command line.] -// snippet-keyword:[AWS CodeBuild] -// snippet-keyword:[StartBuild function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[codebuild] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/codebuild" - "fmt" - "os" + "fmt" + "os" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/codebuild" ) // Builds a CodeBuild project in the region configured in the shared config func main() { - // Requires one argument, the name of the project. - if len(os.Args) != 2 { - fmt.Println("Project name required!") - os.Exit(1) - } - - project := os.Args[1] - - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create CodeBuild service client - svc := codebuild.New(sess) - - // Build the project - _, err = svc.StartBuild(&codebuild.StartBuildInput{ProjectName: aws.String(project)}) - if err != nil { - fmt.Println("Got error building project: ", err) - os.Exit(1) - } - - fmt.Printf("Started build for project %q\n", project) + // Requires one argument, the name of the project. + if len(os.Args) != 2 { + fmt.Println("Project name required!") + os.Exit(1) + } + + project := os.Args[1] + + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create CodeBuild service client + svc := codebuild.New(sess) + + // Build the project + _, err = svc.StartBuild(&codebuild.StartBuildInput{ProjectName: aws.String(project)}) + if err != nil { + fmt.Println("Got error building project: ", err) + os.Exit(1) + } + + fmt.Printf("Started build for project %q\n", project) } - diff --git a/go/example_code/codebuild/cb_list_builds.go b/go/example_code/codebuild/cb_list_builds.go index 2ce9346a718..9639ca68336 100644 --- a/go/example_code/codebuild/cb_list_builds.go +++ b/go/example_code/codebuild/cb_list_builds.go @@ -1,69 +1,48 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Displays information about your AWS CodeBuild project builds.] -// snippet-keyword:[AWS CodeBuild] -// snippet-keyword:[ListBuilds function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[codebuild] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/codebuild" - "fmt" - "os" + "fmt" + "os" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/codebuild" ) // Lists the CodeBuild builds for all projects in the region configured in the shared config func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create CodeBuild service client - svc := codebuild.New(sess) - - // Get the list of builds - names, err := svc.ListBuilds(&codebuild.ListBuildsInput{SortOrder: aws.String("ASCENDING")}) - - if err != nil { - fmt.Println("Got error listing builds: ", err) - os.Exit(1) - } - - // Get information about each build - builds, err := svc.BatchGetBuilds(&codebuild.BatchGetBuildsInput{Ids: names.Ids}) - - if err != nil { - fmt.Println("Got error getting builds: ", err) - os.Exit(1) - } - - for _, build := range builds.Builds { - fmt.Printf("Project: %s\n", aws.StringValue(build.ProjectName)) - fmt.Printf("Phase: %s\n", aws.StringValue(build.CurrentPhase)) - fmt.Printf("Status: %s\n", aws.StringValue(build.BuildStatus)) - fmt.Println("") - } + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create CodeBuild service client + svc := codebuild.New(sess) + + // Get the list of builds + names, err := svc.ListBuilds(&codebuild.ListBuildsInput{SortOrder: aws.String("ASCENDING")}) + + if err != nil { + fmt.Println("Got error listing builds: ", err) + os.Exit(1) + } + + // Get information about each build + builds, err := svc.BatchGetBuilds(&codebuild.BatchGetBuildsInput{Ids: names.Ids}) + + if err != nil { + fmt.Println("Got error getting builds: ", err) + os.Exit(1) + } + + for _, build := range builds.Builds { + fmt.Printf("Project: %s\n", aws.StringValue(build.ProjectName)) + fmt.Printf("Phase: %s\n", aws.StringValue(build.CurrentPhase)) + fmt.Printf("Status: %s\n", aws.StringValue(build.BuildStatus)) + fmt.Println("") + } } diff --git a/go/example_code/codebuild/cb_list_projects.go b/go/example_code/codebuild/cb_list_projects.go index 6d262c4ec97..747bf640ba3 100644 --- a/go/example_code/codebuild/cb_list_projects.go +++ b/go/example_code/codebuild/cb_list_projects.go @@ -1,61 +1,40 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Lists the names of up to 100 of your AWS CodeBuild projects.] -// snippet-keyword:[AWS CodeBuild] -// snippet-keyword:[ListProjects function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[codebuild] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/codebuild" - "fmt" - "os" + "fmt" + "os" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/codebuild" ) // Lists a CodeBuild projects in the region configured in the shared config func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create CodeBuild service client - svc := codebuild.New(sess) - - // Get the list of projects - result, err := svc.ListProjects( - &codebuild.ListProjectsInput{ - SortBy: aws.String("NAME"), - SortOrder: aws.String("ASCENDING", )}) - - if err != nil { - fmt.Println("Got error listing projects: ", err) - os.Exit(1) - } - - for _, p := range result.Projects { - fmt.Println(*p) - } + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create CodeBuild service client + svc := codebuild.New(sess) + + // Get the list of projects + result, err := svc.ListProjects( + &codebuild.ListProjectsInput{ + SortBy: aws.String("NAME"), + SortOrder: aws.String("ASCENDING")}) + + if err != nil { + fmt.Println("Got error listing projects: ", err) + os.Exit(1) + } + + for _, p := range result.Projects { + fmt.Println(*p) + } } diff --git a/go/example_code/cognito/CognitoCreateUser.go b/go/example_code/cognito/CognitoCreateUser.go index b440f281ab2..7a79210c9f3 100644 --- a/go/example_code/cognito/CognitoCreateUser.go +++ b/go/example_code/cognito/CognitoCreateUser.go @@ -1,87 +1,67 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[CognitoCreateUser.go creates a user in a Amazon Cognito user pool.] -// snippet-keyword:[Amazon Cognito] -// snippet-keyword:[AdminCreateUser function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[cognito] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-1-6] -/* - Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cognito.go.create_user.complete] package main // snippet-start:[cognito.go.create_user.imports] import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" - "flag" - "fmt" - "os" + "flag" + "fmt" + "os" ) + // snippet-end:[cognito.go.create_user.imports] func main() { - // snippet-start:[cognito.go.create_user.vars] - emailIDPtr := flag.String("e", "", "The email address of the user") - userPoolIDPtr := flag.String("p", "", "The ID of the user pool") - userNamePtr := flag.String("n", "", "The name of the user") + // snippet-start:[cognito.go.create_user.vars] + emailIDPtr := flag.String("e", "", "The email address of the user") + userPoolIDPtr := flag.String("p", "", "The ID of the user pool") + userNamePtr := flag.String("n", "", "The name of the user") - flag.Parse() + flag.Parse() - if *emailIDPtr == "" || *userPoolIDPtr == "" || *userNamePtr == "" { - fmt.Println("You must supply an email address, user pool ID, and user name") - fmt.Println("Usage: go run CreateUser.go -e EMAIL-ADDRESS -p USER-POOL-ID -n USER-NAME") - os.Exit(1) - } - // snippet-end:[cognito.go.create_user.vars] + if *emailIDPtr == "" || *userPoolIDPtr == "" || *userNamePtr == "" { + fmt.Println("You must supply an email address, user pool ID, and user name") + fmt.Println("Usage: go run CreateUser.go -e EMAIL-ADDRESS -p USER-POOL-ID -n USER-NAME") + os.Exit(1) + } + // snippet-end:[cognito.go.create_user.vars] - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - // snippet-start:[cognito.go.create_user.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[cognito.go.create_user.session] + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + // snippet-start:[cognito.go.create_user.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[cognito.go.create_user.session] - // snippet-start:[cognito.go.create_user.create] - cognitoClient := cognitoidentityprovider.New(sess) + // snippet-start:[cognito.go.create_user.create] + cognitoClient := cognitoidentityprovider.New(sess) - newUserData := &cognitoidentityprovider.AdminCreateUserInput{ - DesiredDeliveryMediums: []*string{ - aws.String("EMAIL"), - }, - UserAttributes: []*cognitoidentityprovider.AttributeType{ - { - Name: aws.String("email"), - Value: aws.String(*emailIDPtr), - }, - }, - } + newUserData := &cognitoidentityprovider.AdminCreateUserInput{ + DesiredDeliveryMediums: []*string{ + aws.String("EMAIL"), + }, + UserAttributes: []*cognitoidentityprovider.AttributeType{ + { + Name: aws.String("email"), + Value: aws.String(*emailIDPtr), + }, + }, + } - newUserData.SetUserPoolId(*userPoolIDPtr) - newUserData.SetUsername(*userNamePtr) + newUserData.SetUserPoolId(*userPoolIDPtr) + newUserData.SetUsername(*userNamePtr) - _, err := cognitoClient.AdminCreateUser(newUserData) - if err != nil { - fmt.Println("Got error creating user:", err) - } - // snippet-end:[cognito.go.create_user.create] + _, err := cognitoClient.AdminCreateUser(newUserData) + if err != nil { + fmt.Println("Got error creating user:", err) + } + // snippet-end:[cognito.go.create_user.create] } + // snippet-end:[cognito.go.create_user.complete] diff --git a/go/example_code/cognito/CognitoCreateUserPool.go b/go/example_code/cognito/CognitoCreateUserPool.go index 9a169931ef4..06b11cf4651 100644 --- a/go/example_code/cognito/CognitoCreateUserPool.go +++ b/go/example_code/cognito/CognitoCreateUserPool.go @@ -1,159 +1,139 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[CognitoCreateUserPool creates an Amazon Cognito user pool.] -// snippet-keyword:[Amazon Cognito] -// snippet-keyword:[CreateUserPool function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[cognito] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-02-12] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cognito.go.create_user_pool] package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" - "github.com/aws/aws-sdk-go/service/iam" - - "fmt" - "os" - "strings" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" + "github.com/aws/aws-sdk-go/service/iam" + + "fmt" + "os" + "strings" ) func getRoleName(poolName string) string { - name := strings.Replace(poolName, "-", "", -1) - return name + "-SMS-Role" + name := strings.Replace(poolName, "-", "", -1) + return name + "-SMS-Role" } // Creates Cognito user pool POOL_NAME // // Usage: -// go run CognitoCreateUserPool.go POOL_NAME +// +// go run CognitoCreateUserPool.go POOL_NAME func main() { - if len(os.Args) < 2 { - fmt.Println("Pool name is required") - fmt.Println("Usage: go run", os.Args[0], "POOL_NAME") - } - - poolName := os.Args[2] - - emailMsg := "{username} {####}" // Must match regex: [\p{L}\p{M}\p{S}\p{N}\p{P}\s*]*\{####\}[\p{L}\p{M}\p{S}\p{N}\p{P}\s*]* - emailSubject := "AWS TW Chat" - smsMsg := "{username} {####}" // Must match regex: .*\{####\}.* - - waitDays := int64(1) - - emailVerifyMsg := "{####}" // Must match regex: [\p{L}\p{M}\p{S}\p{N}\p{P}\s*]*\{####\}[\p{L}\p{M}\p{S}\p{N}\p{P}\s*]* - emailVerifySub := "AWS TW Chat" - smsAuthMsg := "{####}" // Must match regex: .*\{####\}.* - smsVerifyMsg := "{####}" // Must match regex: .*\{####\}.* - - // Initialize a session that the SDK will use to load configuration, - // credentials, and region from the shared config file. (~/.aws/config). - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // // Create SMS role so pool can msg new users on your behalf - iamSvc := iam.New(sess) - - doc := "{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Sid\": \"\", \"Effect\": \"Allow\", \"Principal\": { \"Service\": \"cognito-idp.amazonaws.com\" }, \"Action\": \"sts:AssumeRole\" } ] }" - - // Create SMS role with pool name, less any hyphens - roleName := getRoleName(poolName) // Required - - path := "/service-role/" - - iamResp, iamErr := iamSvc.CreateRole( - &iam.CreateRoleInput{ - AssumeRolePolicyDocument: &doc, - RoleName: &roleName, - Path: &path}) - - if iamErr != nil { - fmt.Println("Could not create role") - os.Exit(1) - } - - roleArn := iamResp.Role.Arn - roleID := iamResp.Role.RoleId - - // Create Cognito client - cgSvc := cognitoidentityprovider.New(sess) - - params := &cognitoidentityprovider.CreateUserPoolInput{ - PoolName: &poolName, // Required - AdminCreateUserConfig: &cognitoidentityprovider.AdminCreateUserConfigType{ - AllowAdminCreateUserOnly: aws.Bool(false), // false == users can sign themselves up - InviteMessageTemplate: &cognitoidentityprovider.MessageTemplateType{ - EmailMessage: &emailMsg, // Welcome message to new users - EmailSubject: &emailSubject, // Welcome subject to new users - SMSMessage: &smsMsg, - }, - UnusedAccountValidityDays: &waitDays, // How many days to wait before rescinding offer - }, - AutoVerifiedAttributes: []*string{ // Auto-verified means the user confirmed the SNS message - aws.String("email"), // Required; either email or phone_number - aws.String("phone_number"), - }, - EmailVerificationMessage: &emailVerifyMsg, - EmailVerificationSubject: &emailVerifySub, - Policies: &cognitoidentityprovider.UserPoolPolicyType{ - PasswordPolicy: &cognitoidentityprovider.PasswordPolicyType{ - MinimumLength: aws.Int64(6), // Require a password of at least 6 chars - RequireLowercase: aws.Bool(false), - RequireNumbers: aws.Bool(false), - RequireSymbols: aws.Bool(false), - RequireUppercase: aws.Bool(false), - }, - }, - Schema: []*cognitoidentityprovider.SchemaAttributeType{ - { // Required - AttributeDataType: aws.String("String"), - DeveloperOnlyAttribute: aws.Bool(false), - Mutable: aws.Bool(false), - Name: aws.String("user_name"), - Required: aws.Bool(false), - StringAttributeConstraints: &cognitoidentityprovider.StringAttributeConstraintsType{ - MaxLength: aws.String("64"), // user name can be up to 64 chars - MinLength: aws.String("3"), // or as few as 3 chars - }, - }, - }, - SmsAuthenticationMessage: &smsAuthMsg, - SmsConfiguration: &cognitoidentityprovider.SmsConfigurationType{ - SnsCallerArn: roleArn, // Required - ExternalId: roleID, - }, - SmsVerificationMessage: &smsVerifyMsg, - } - - fmt.Println("") - - cgResp, cgErr := cgSvc.CreateUserPool(params) - - if cgErr != nil { - fmt.Println("Could not create user pool") - os.Exit(1) - } - - fmt.Println("") - fmt.Println(cgResp) + if len(os.Args) < 2 { + fmt.Println("Pool name is required") + fmt.Println("Usage: go run", os.Args[0], "POOL_NAME") + } + + poolName := os.Args[2] + + emailMsg := "{username} {####}" // Must match regex: [\p{L}\p{M}\p{S}\p{N}\p{P}\s*]*\{####\}[\p{L}\p{M}\p{S}\p{N}\p{P}\s*]* + emailSubject := "AWS TW Chat" + smsMsg := "{username} {####}" // Must match regex: .*\{####\}.* + + waitDays := int64(1) + + emailVerifyMsg := "{####}" // Must match regex: [\p{L}\p{M}\p{S}\p{N}\p{P}\s*]*\{####\}[\p{L}\p{M}\p{S}\p{N}\p{P}\s*]* + emailVerifySub := "AWS TW Chat" + smsAuthMsg := "{####}" // Must match regex: .*\{####\}.* + smsVerifyMsg := "{####}" // Must match regex: .*\{####\}.* + + // Initialize a session that the SDK will use to load configuration, + // credentials, and region from the shared config file. (~/.aws/config). + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // // Create SMS role so pool can msg new users on your behalf + iamSvc := iam.New(sess) + + doc := "{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Sid\": \"\", \"Effect\": \"Allow\", \"Principal\": { \"Service\": \"cognito-idp.amazonaws.com\" }, \"Action\": \"sts:AssumeRole\" } ] }" + + // Create SMS role with pool name, less any hyphens + roleName := getRoleName(poolName) // Required + + path := "/service-role/" + + iamResp, iamErr := iamSvc.CreateRole( + &iam.CreateRoleInput{ + AssumeRolePolicyDocument: &doc, + RoleName: &roleName, + Path: &path}) + + if iamErr != nil { + fmt.Println("Could not create role") + os.Exit(1) + } + + roleArn := iamResp.Role.Arn + roleID := iamResp.Role.RoleId + + // Create Cognito client + cgSvc := cognitoidentityprovider.New(sess) + + params := &cognitoidentityprovider.CreateUserPoolInput{ + PoolName: &poolName, // Required + AdminCreateUserConfig: &cognitoidentityprovider.AdminCreateUserConfigType{ + AllowAdminCreateUserOnly: aws.Bool(false), // false == users can sign themselves up + InviteMessageTemplate: &cognitoidentityprovider.MessageTemplateType{ + EmailMessage: &emailMsg, // Welcome message to new users + EmailSubject: &emailSubject, // Welcome subject to new users + SMSMessage: &smsMsg, + }, + UnusedAccountValidityDays: &waitDays, // How many days to wait before rescinding offer + }, + AutoVerifiedAttributes: []*string{ // Auto-verified means the user confirmed the SNS message + aws.String("email"), // Required; either email or phone_number + aws.String("phone_number"), + }, + EmailVerificationMessage: &emailVerifyMsg, + EmailVerificationSubject: &emailVerifySub, + Policies: &cognitoidentityprovider.UserPoolPolicyType{ + PasswordPolicy: &cognitoidentityprovider.PasswordPolicyType{ + MinimumLength: aws.Int64(6), // Require a password of at least 6 chars + RequireLowercase: aws.Bool(false), + RequireNumbers: aws.Bool(false), + RequireSymbols: aws.Bool(false), + RequireUppercase: aws.Bool(false), + }, + }, + Schema: []*cognitoidentityprovider.SchemaAttributeType{ + { // Required + AttributeDataType: aws.String("String"), + DeveloperOnlyAttribute: aws.Bool(false), + Mutable: aws.Bool(false), + Name: aws.String("user_name"), + Required: aws.Bool(false), + StringAttributeConstraints: &cognitoidentityprovider.StringAttributeConstraintsType{ + MaxLength: aws.String("64"), // user name can be up to 64 chars + MinLength: aws.String("3"), // or as few as 3 chars + }, + }, + }, + SmsAuthenticationMessage: &smsAuthMsg, + SmsConfiguration: &cognitoidentityprovider.SmsConfigurationType{ + SnsCallerArn: roleArn, // Required + ExternalId: roleID, + }, + SmsVerificationMessage: &smsVerifyMsg, + } + + fmt.Println("") + + cgResp, cgErr := cgSvc.CreateUserPool(params) + + if cgErr != nil { + fmt.Println("Could not create user pool") + os.Exit(1) + } + + fmt.Println("") + fmt.Println(cgResp) } + // snippet-end:[cognito.go.create_user_pool] diff --git a/go/example_code/cognito/CognitoListUserPools.go b/go/example_code/cognito/CognitoListUserPools.go index a9875340de9..1c8d7891b81 100644 --- a/go/example_code/cognito/CognitoListUserPools.go +++ b/go/example_code/cognito/CognitoListUserPools.go @@ -1,68 +1,47 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[CognitoListUserPools lists your Amazon Cognito user pools.] -// snippet-keyword:[Amazon Cognito] -// snippet-keyword:[ListUserPools function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[cognito] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-02-12] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cognito.go.list_user_pools] package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" - "fmt" - "os" + "fmt" + "os" ) func main() { - // Initialize a session that the SDK will use to load configuration, - // credentials, and region from the shared config file. (~/.aws/config). - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create Cognito client - svc := cognitoidentityprovider.New(sess) - - max := int64(10) - - result, err := svc.ListUserPools( - &cognitoidentityprovider.ListUserPoolsInput{ - MaxResults: &max, - }) // .ListBuckets(nil) - if err != nil { - fmt.Println("Could not list user pools") - os.Exit(1) - } - - fmt.Println("User pools:") - fmt.Println("") - - for _, pool := range result.UserPools { - fmt.Println("Name: " + aws.StringValue(pool.Name)) - fmt.Println("ID: " + aws.StringValue(pool.Id)) - fmt.Println("Created: " + aws.TimeValue(pool.CreationDate).String()) - fmt.Println("") - } + // Initialize a session that the SDK will use to load configuration, + // credentials, and region from the shared config file. (~/.aws/config). + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create Cognito client + svc := cognitoidentityprovider.New(sess) + + max := int64(10) + + result, err := svc.ListUserPools( + &cognitoidentityprovider.ListUserPoolsInput{ + MaxResults: &max, + }) // .ListBuckets(nil) + if err != nil { + fmt.Println("Could not list user pools") + os.Exit(1) + } + + fmt.Println("User pools:") + fmt.Println("") + + for _, pool := range result.UserPools { + fmt.Println("Name: " + aws.StringValue(pool.Name)) + fmt.Println("ID: " + aws.StringValue(pool.Id)) + fmt.Println("Created: " + aws.TimeValue(pool.CreationDate).String()) + fmt.Println("") + } } + // snippet-end:[cognito.go.list_user_pools] diff --git a/go/example_code/cognito/CognitoListUsers.go b/go/example_code/cognito/CognitoListUsers.go index e2b0d6fc772..a8b39ab8c1c 100644 --- a/go/example_code/cognito/CognitoListUsers.go +++ b/go/example_code/cognito/CognitoListUsers.go @@ -1,87 +1,67 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[CognitoListUsers lists the users in a Amazon Cognito user pool.] -// snippet-keyword:[Amazon Cognito] -// snippet-keyword:[ListUsers function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[cognito] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-1-6] -/* - Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cognito.go.list_users.complete] package main // snippet-start:[cognito.go.list_users.imports] import ( - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" - "flag" - "fmt" - "os" + "flag" + "fmt" + "os" ) + // snippet-end:[cognito.go.list_users.imports] func main() { - // snippet-start:[cognito.go.list_users.vars] - userPoolIDPtr := flag.String("p", "", "The ID of the user pool") + // snippet-start:[cognito.go.list_users.vars] + userPoolIDPtr := flag.String("p", "", "The ID of the user pool") - flag.Parse() + flag.Parse() - if *userPoolIDPtr == "" { - fmt.Println("You must supply a user pool ID") - fmt.Println("Usage: go run CreateUser.go -p USER-POOL-ID") - os.Exit(1) - } - // snippet-end:[cognito.go.list_users.vars] + if *userPoolIDPtr == "" { + fmt.Println("You must supply a user pool ID") + fmt.Println("Usage: go run CreateUser.go -p USER-POOL-ID") + os.Exit(1) + } + // snippet-end:[cognito.go.list_users.vars] - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - // snippet-start:[cognito.go.list_users.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[cognito.go.list_users.session] + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + // snippet-start:[cognito.go.list_users.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[cognito.go.list_users.session] - // snippet-start:[cognito.go.list_users.list] - cognitoClient := cognitoidentityprovider.New(sess) + // snippet-start:[cognito.go.list_users.list] + cognitoClient := cognitoidentityprovider.New(sess) - results, err := cognitoClient.ListUsers( - &cognitoidentityprovider.ListUsersInput{ - UserPoolId: userPoolIDPtr}) - if err != nil { - fmt.Println("Got error listing users") - os.Exit(1) - } + results, err := cognitoClient.ListUsers( + &cognitoidentityprovider.ListUsersInput{ + UserPoolId: userPoolIDPtr}) + if err != nil { + fmt.Println("Got error listing users") + os.Exit(1) + } - // Show their names an email addresses - for _, user := range results.Users { - attributes := user.Attributes + // Show their names an email addresses + for _, user := range results.Users { + attributes := user.Attributes - for _, a := range attributes { - if *a.Name == "name" { - fmt.Println("Name: " + *a.Value) - } else if *a.Name == "email" { - fmt.Println("Email: " + *a.Value) - } - } + for _, a := range attributes { + if *a.Name == "name" { + fmt.Println("Name: " + *a.Value) + } else if *a.Name == "email" { + fmt.Println("Email: " + *a.Value) + } + } - fmt.Println("") - } - // snippet-end:[cognito.go.list_users.list] + fmt.Println("") + } + // snippet-end:[cognito.go.list_users.list] } + // snippet-end:[cognito.go.list_users.complete] diff --git a/go/example_code/costexplorer/get_cost_and_usage.go b/go/example_code/costexplorer/get_cost_and_usage.go index 30db28e355f..85d3446a801 100644 --- a/go/example_code/costexplorer/get_cost_and_usage.go +++ b/go/example_code/costexplorer/get_cost_and_usage.go @@ -1,27 +1,5 @@ -// snippet-sourceauthor:[tokiwong] -// snippet-sourcedescription:[Retrieves cost and usage metrics for your account] -// snippet-keyword:[Amazon Cost Explorer] -// snippet-keyword:[Amazon CE] -// snippet-keyword:[GetCostAndUsage function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ce] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-07-09] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main diff --git a/go/example_code/dynamodb/DynamoDBCreateItem.go b/go/example_code/dynamodb/DynamoDBCreateItem.go index 2f6b8304d64..dd7b6839f89 100644 --- a/go/example_code/dynamodb/DynamoDBCreateItem.go +++ b/go/example_code/dynamodb/DynamoDBCreateItem.go @@ -1,97 +1,78 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[DynamoDBCreateItem.go creates an item in an Amazon DynamoDB table.] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[PutItem function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[dynamodb] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-03-19] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[dynamodb.go.create_item] package main // snippet-start:[dynamodb.go.create_item.imports] import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" - "fmt" - "log" - "strconv" + "fmt" + "log" + "strconv" ) + // snippet-end:[dynamodb.go.create_item.imports] // snippet-start:[dynamodb.go.create_item.struct] // Create struct to hold info about new item type Item struct { - Year int - Title string - Plot string - Rating float64 + Year int + Title string + Plot string + Rating float64 } + // snippet-end:[dynamodb.go.create_item.struct] func main() { - // snippet-start:[dynamodb.go.create_item.session] - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials - // and region from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + // snippet-start:[dynamodb.go.create_item.session] + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials + // and region from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - // Create DynamoDB client - svc := dynamodb.New(sess) - // snippet-end:[dynamodb.go.create_item.session] + // Create DynamoDB client + svc := dynamodb.New(sess) + // snippet-end:[dynamodb.go.create_item.session] - // snippet-start:[dynamodb.go.create_item.assign_struct] - item := Item{ - Year: 2015, - Title: "The Big New Movie", - Plot: "Nothing happens at all.", - Rating: 0.0, - } + // snippet-start:[dynamodb.go.create_item.assign_struct] + item := Item{ + Year: 2015, + Title: "The Big New Movie", + Plot: "Nothing happens at all.", + Rating: 0.0, + } - av, err := dynamodbattribute.MarshalMap(item) - if err != nil { - log.Fatalf("Got error marshalling new movie item: %s", err) - } - // snippet-end:[dynamodb.go.create_item.assign_struct] + av, err := dynamodbattribute.MarshalMap(item) + if err != nil { + log.Fatalf("Got error marshalling new movie item: %s", err) + } + // snippet-end:[dynamodb.go.create_item.assign_struct] - // snippet-start:[dynamodb.go.create_item.call] - // Create item in table Movies - tableName := "Movies" + // snippet-start:[dynamodb.go.create_item.call] + // Create item in table Movies + tableName := "Movies" - input := &dynamodb.PutItemInput{ - Item: av, - TableName: aws.String(tableName), - } + input := &dynamodb.PutItemInput{ + Item: av, + TableName: aws.String(tableName), + } - _, err = svc.PutItem(input) - if err != nil { - log.Fatalf("Got error calling PutItem: %s", err) - } + _, err = svc.PutItem(input) + if err != nil { + log.Fatalf("Got error calling PutItem: %s", err) + } - year := strconv.Itoa(item.Year) + year := strconv.Itoa(item.Year) - fmt.Println("Successfully added '" + item.Title + "' (" + year + ") to table " + tableName) - // snippet-end:[dynamodb.go.create_item.call] + fmt.Println("Successfully added '" + item.Title + "' (" + year + ") to table " + tableName) + // snippet-end:[dynamodb.go.create_item.call] } + // snippet-end:[dynamodb.go.create_item] diff --git a/go/example_code/dynamodb/DynamoDBCreateTable.go b/go/example_code/dynamodb/DynamoDBCreateTable.go index 59e96201b7c..041726c7d7f 100644 --- a/go/example_code/dynamodb/DynamoDBCreateTable.go +++ b/go/example_code/dynamodb/DynamoDBCreateTable.go @@ -1,92 +1,72 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[DynamoDBCreateTable.go create an Amazon DynamoDB table.] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[CreateTable function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[dynamodb] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-03-18] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[dynamodb.go.create_table] package main // snippet-start:[dynamodb.go.create_table.imports] import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" - "fmt" - "log" + "fmt" + "log" ) + // snippet-end:[dynamodb.go.create_table.imports] func main() { - // snippet-start:[dynamodb.go.create_table.session] - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials - // and region from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + // snippet-start:[dynamodb.go.create_table.session] + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials + // and region from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - // Create DynamoDB client - svc := dynamodb.New(sess) - // snippet-end:[dynamodb.go.create_table.session] + // Create DynamoDB client + svc := dynamodb.New(sess) + // snippet-end:[dynamodb.go.create_table.session] - // snippet-start:[dynamodb.go.create_table.call] - // Create table Movies - tableName := "Movies" + // snippet-start:[dynamodb.go.create_table.call] + // Create table Movies + tableName := "Movies" - input := &dynamodb.CreateTableInput{ - AttributeDefinitions: []*dynamodb.AttributeDefinition{ - { - AttributeName: aws.String("Year"), - AttributeType: aws.String("N"), - }, - { - AttributeName: aws.String("Title"), - AttributeType: aws.String("S"), - }, - }, - KeySchema: []*dynamodb.KeySchemaElement{ - { - AttributeName: aws.String("Year"), - KeyType: aws.String("HASH"), - }, - { - AttributeName: aws.String("Title"), - KeyType: aws.String("RANGE"), - }, - }, - ProvisionedThroughput: &dynamodb.ProvisionedThroughput{ - ReadCapacityUnits: aws.Int64(10), - WriteCapacityUnits: aws.Int64(10), - }, - TableName: aws.String(tableName), - } + input := &dynamodb.CreateTableInput{ + AttributeDefinitions: []*dynamodb.AttributeDefinition{ + { + AttributeName: aws.String("Year"), + AttributeType: aws.String("N"), + }, + { + AttributeName: aws.String("Title"), + AttributeType: aws.String("S"), + }, + }, + KeySchema: []*dynamodb.KeySchemaElement{ + { + AttributeName: aws.String("Year"), + KeyType: aws.String("HASH"), + }, + { + AttributeName: aws.String("Title"), + KeyType: aws.String("RANGE"), + }, + }, + ProvisionedThroughput: &dynamodb.ProvisionedThroughput{ + ReadCapacityUnits: aws.Int64(10), + WriteCapacityUnits: aws.Int64(10), + }, + TableName: aws.String(tableName), + } - _, err := svc.CreateTable(input) - if err != nil { - log.Fatalf("Got error calling CreateTable: %s", err) - } + _, err := svc.CreateTable(input) + if err != nil { + log.Fatalf("Got error calling CreateTable: %s", err) + } - fmt.Println("Created the table", tableName) - // snippet-end:[dynamodb.go.create_table.call] + fmt.Println("Created the table", tableName) + // snippet-end:[dynamodb.go.create_table.call] } + // snippet-end:[dynamodb.go.create_table] diff --git a/go/example_code/dynamodb/DynamoDBDeleteItem.go b/go/example_code/dynamodb/DynamoDBDeleteItem.go index 0115600efa8..3eb8ee43fbd 100644 --- a/go/example_code/dynamodb/DynamoDBDeleteItem.go +++ b/go/example_code/dynamodb/DynamoDBDeleteItem.go @@ -1,77 +1,57 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[DynamoDBDeleteItem.go deletes an item from an Amazon DynamoDB table.] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[DeleteItem function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[dynamodb] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-03-19] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[dynamodb.go.delete_item] package main // snippet-start:[dynamodb.go.delete_item.imports] import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" - "fmt" - "log" + "fmt" + "log" ) + // snippet-end:[dynamodb.go.delete_item.imports] func main() { - // snippet-start:[dynamodb.go.delete_item.session] - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials - // and region from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create DynamoDB client - svc := dynamodb.New(sess) - // snippet-end:[dynamodb.go.delete_item.session] - - // snippet-start:[dynamodb.go.delete_item.call] - tableName := "Movies" - movieName := "The Big New Movie" - movieYear := "2015" - - input := &dynamodb.DeleteItemInput{ - Key: map[string]*dynamodb.AttributeValue{ - "Year": { - N: aws.String(movieYear), - }, - "Title": { - S: aws.String(movieName), - }, - }, - TableName: aws.String(tableName), - } - - _, err := svc.DeleteItem(input) - if err != nil { - log.Fatalf("Got error calling DeleteItem: %s", err) - } - - fmt.Println("Deleted '" + movieName + "' (" + movieYear + ") from table " + tableName) - // snippet-end:[dynamodb.go.delete_item.call] + // snippet-start:[dynamodb.go.delete_item.session] + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials + // and region from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create DynamoDB client + svc := dynamodb.New(sess) + // snippet-end:[dynamodb.go.delete_item.session] + + // snippet-start:[dynamodb.go.delete_item.call] + tableName := "Movies" + movieName := "The Big New Movie" + movieYear := "2015" + + input := &dynamodb.DeleteItemInput{ + Key: map[string]*dynamodb.AttributeValue{ + "Year": { + N: aws.String(movieYear), + }, + "Title": { + S: aws.String(movieName), + }, + }, + TableName: aws.String(tableName), + } + + _, err := svc.DeleteItem(input) + if err != nil { + log.Fatalf("Got error calling DeleteItem: %s", err) + } + + fmt.Println("Deleted '" + movieName + "' (" + movieYear + ") from table " + tableName) + // snippet-end:[dynamodb.go.delete_item.call] } + // snippet-end:[dynamodb.go.delete_item] diff --git a/go/example_code/dynamodb/DynamoDBListTables.go b/go/example_code/dynamodb/DynamoDBListTables.go index a99bbaf0338..f17b68fffa9 100644 --- a/go/example_code/dynamodb/DynamoDBListTables.go +++ b/go/example_code/dynamodb/DynamoDBListTables.go @@ -1,93 +1,71 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[DynamoDBListTables.go lists your Amazon DynamoDB tables.] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[ListTables function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[dynamodb] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-05-3] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[dynamodb.go.list_tables] package main // snippet-start:[dynamodb.go.list_tables.imports] import ( - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" - "fmt" + "fmt" ) // snippet-end:[dynamodb.go.list_tables.imports] func main() { - // snippet-start:[dynamodb.go.list_tables.session] - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials - // and region from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + // snippet-start:[dynamodb.go.list_tables.session] + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials + // and region from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - // Create DynamoDB client - svc := dynamodb.New(sess) - // snippet-end:[dynamodb.go.list_tables.session] + // Create DynamoDB client + svc := dynamodb.New(sess) + // snippet-end:[dynamodb.go.list_tables.session] - // snippet-start:[dynamodb.go.list_tables.call] - // create the input configuration instance - input := &dynamodb.ListTablesInput{} + // snippet-start:[dynamodb.go.list_tables.call] + // create the input configuration instance + input := &dynamodb.ListTablesInput{} - fmt.Printf("Tables:\n") + fmt.Printf("Tables:\n") - for { - // Get the list of tables - result, err := svc.ListTables(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case dynamodb.ErrCodeInternalServerError: - fmt.Println(dynamodb.ErrCodeInternalServerError, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } + for { + // Get the list of tables + result, err := svc.ListTables(input) + if err != nil { + if aerr, ok := err.(awserr.Error); ok { + switch aerr.Code() { + case dynamodb.ErrCodeInternalServerError: + fmt.Println(dynamodb.ErrCodeInternalServerError, aerr.Error()) + default: + fmt.Println(aerr.Error()) + } + } else { + // Print the error, cast err to awserr.Error to get the Code and + // Message from an error. + fmt.Println(err.Error()) + } + return + } - for _, n := range result.TableNames { - fmt.Println(*n) - } + for _, n := range result.TableNames { + fmt.Println(*n) + } - // assign the last read tablename as the start for our next call to the ListTables function - // the maximum number of table names returned in a call is 100 (default), which requires us to make - // multiple calls to the ListTables function to retrieve all table names - input.ExclusiveStartTableName = result.LastEvaluatedTableName + // assign the last read tablename as the start for our next call to the ListTables function + // the maximum number of table names returned in a call is 100 (default), which requires us to make + // multiple calls to the ListTables function to retrieve all table names + input.ExclusiveStartTableName = result.LastEvaluatedTableName - if result.LastEvaluatedTableName == nil { - break - } - } - // snippet-end:[dynamodb.go.list_tables.call] + if result.LastEvaluatedTableName == nil { + break + } + } + // snippet-end:[dynamodb.go.list_tables.call] } // snippet-end:[dynamodb.go.list_tables] diff --git a/go/example_code/dynamodb/DynamoDBLoadItems.go b/go/example_code/dynamodb/DynamoDBLoadItems.go index 88f4085b566..aebda27fd4e 100644 --- a/go/example_code/dynamodb/DynamoDBLoadItems.go +++ b/go/example_code/dynamodb/DynamoDBLoadItems.go @@ -1,110 +1,92 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[DynamoDBLoadItems.go adds items from a JSON file to an Amazon DynamoDB table.] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[PutItem function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[dynamodb] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-03-19] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[dynamodb.go.load_items] package main // snippet-start:[dynamodb.go.load_items.imports] import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" - - "encoding/json" - "fmt" - "log" - "io/ioutil" - "strconv" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" + + "encoding/json" + "fmt" + "io/ioutil" + "log" + "strconv" ) + // snippet-end:[dynamodb.go.load_items.imports] // snippet-start:[dynamodb.go.load_items.struct] // Create struct to hold info about new item type Item struct { - Year int - Title string - Plot string - Rating float64 + Year int + Title string + Plot string + Rating float64 } + // snippet-end:[dynamodb.go.load_items.struct] // snippet-start:[dynamodb.go.load_items.func] // Get table items from JSON file func getItems() []Item { - raw, err := ioutil.ReadFile("./.movie_data.json") - if err != nil { - log.Fatalf("Got error reading file: %s", err) - } - - var items []Item - json.Unmarshal(raw, &items) - return items + raw, err := ioutil.ReadFile("./.movie_data.json") + if err != nil { + log.Fatalf("Got error reading file: %s", err) + } + + var items []Item + json.Unmarshal(raw, &items) + return items } + // snippet-end:[dynamodb.go.load_items.func] func main() { - // snippet-start:[dynamodb.go.load_items.session] - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials - // and region from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create DynamoDB client - svc := dynamodb.New(sess) - // snippet-end:[dynamodb.go.load_items.session] - - // snippet-start:[dynamodb.go.load_items.call] - // Get table items from .movie_data.json - items := getItems() - - // Add each item to Movies table: - tableName := "Movies" - - for _, item := range items { - av, err := dynamodbattribute.MarshalMap(item) - if err != nil { - log.Fatalf("Got error marshalling map: %s", err) - } - - // Create item in table Movies - input := &dynamodb.PutItemInput{ - Item: av, - TableName: aws.String(tableName), - } - - _, err = svc.PutItem(input) - if err != nil { - log.Fatalf("Got error calling PutItem: %s", err) - } - - year := strconv.Itoa(item.Year) - - fmt.Println("Successfully added '" + item.Title + "' (" + year + ") to table " + tableName) - // snippet-end:[dynamodb.go.load_items.call] - } + // snippet-start:[dynamodb.go.load_items.session] + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials + // and region from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create DynamoDB client + svc := dynamodb.New(sess) + // snippet-end:[dynamodb.go.load_items.session] + + // snippet-start:[dynamodb.go.load_items.call] + // Get table items from .movie_data.json + items := getItems() + + // Add each item to Movies table: + tableName := "Movies" + + for _, item := range items { + av, err := dynamodbattribute.MarshalMap(item) + if err != nil { + log.Fatalf("Got error marshalling map: %s", err) + } + + // Create item in table Movies + input := &dynamodb.PutItemInput{ + Item: av, + TableName: aws.String(tableName), + } + + _, err = svc.PutItem(input) + if err != nil { + log.Fatalf("Got error calling PutItem: %s", err) + } + + year := strconv.Itoa(item.Year) + + fmt.Println("Successfully added '" + item.Title + "' (" + year + ") to table " + tableName) + // snippet-end:[dynamodb.go.load_items.call] + } } + // snippet-end:[dynamodb.go.load_items] diff --git a/go/example_code/dynamodb/DynamoDBReadItem.go b/go/example_code/dynamodb/DynamoDBReadItem.go index f7d039b6d71..48375219a69 100644 --- a/go/example_code/dynamodb/DynamoDBReadItem.go +++ b/go/example_code/dynamodb/DynamoDBReadItem.go @@ -1,104 +1,87 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[DynamoDBReadItem.go gets an item from an Amazon DynamoDB table.] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[GetItem function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[dynamodb] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-03-19] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[dynamodb.go.read_item] package main // snippet-start:[dynamodb.go.read_item.imports] import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" + "errors" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" - "fmt" - "log" + "fmt" + "log" ) + // snippet-end:[dynamodb.go.read_item.imports] // snippet-start:[dynamodb.go.read_item.struct] // Create struct to hold info about new item type Item struct { - Year int - Title string - Plot string - Rating float64 + Year int + Title string + Plot string + Rating float64 } + // snippet-end:[dynamodb.go.read_item.struct] func main() { - // snippet-start:[dynamodb.go.read_item.session] - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials - // and region from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + // snippet-start:[dynamodb.go.read_item.session] + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials + // and region from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - // Create DynamoDB client - svc := dynamodb.New(sess) - // snippet-end:[dynamodb.go.read_item.session] + // Create DynamoDB client + svc := dynamodb.New(sess) + // snippet-end:[dynamodb.go.read_item.session] - // snippet-start:[dynamodb.go.read_item.call] - tableName := "Movies" - movieName := "The Big New Movie" - movieYear := "2015" + // snippet-start:[dynamodb.go.read_item.call] + tableName := "Movies" + movieName := "The Big New Movie" + movieYear := "2015" - result, err := svc.GetItem(&dynamodb.GetItemInput{ - TableName: aws.String(tableName), - Key: map[string]*dynamodb.AttributeValue{ - "Year": { - N: aws.String(movieYear), - }, - "Title": { - S: aws.String(movieName), - }, - }, - }) - if err != nil { - log.Fatalf("Got error calling GetItem: %s", err) - } - // snippet-end:[dynamodb.go.read_item.call] + result, err := svc.GetItem(&dynamodb.GetItemInput{ + TableName: aws.String(tableName), + Key: map[string]*dynamodb.AttributeValue{ + "Year": { + N: aws.String(movieYear), + }, + "Title": { + S: aws.String(movieName), + }, + }, + }) + if err != nil { + log.Fatalf("Got error calling GetItem: %s", err) + } + // snippet-end:[dynamodb.go.read_item.call] - // snippet-start:[dynamodb.go.read_item.unmarshall] - if result.Item == nil { - msg := "Could not find '" + *title + "'" - return nil, errors.New(msg) - } - - item := Item{} + // snippet-start:[dynamodb.go.read_item.unmarshall] + if result.Item == nil { + msg := "Could not find '" + *title + "'" + return nil, errors.New(msg) + } - err = dynamodbattribute.UnmarshalMap(result.Item, &item) - if err != nil { - panic(fmt.Sprintf("Failed to unmarshal Record, %v", err)) - } + item := Item{} - fmt.Println("Found item:") - fmt.Println("Year: ", item.Year) - fmt.Println("Title: ", item.Title) - fmt.Println("Plot: ", item.Plot) - fmt.Println("Rating:", item.Rating) - // snippet-end:[dynamodb.go.read_item.unmarshall] + err = dynamodbattribute.UnmarshalMap(result.Item, &item) + if err != nil { + panic(fmt.Sprintf("Failed to unmarshal Record, %v", err)) + } + + fmt.Println("Found item:") + fmt.Println("Year: ", item.Year) + fmt.Println("Title: ", item.Title) + fmt.Println("Plot: ", item.Plot) + fmt.Println("Rating:", item.Rating) + // snippet-end:[dynamodb.go.read_item.unmarshall] } + // snippet-end:[dynamodb.go.read_item] diff --git a/go/example_code/dynamodb/DynamoDBScanItems.go b/go/example_code/dynamodb/DynamoDBScanItems.go index 3d3b81f6d1b..0971845a400 100644 --- a/go/example_code/dynamodb/DynamoDBScanItems.go +++ b/go/example_code/dynamodb/DynamoDBScanItems.go @@ -1,133 +1,113 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[DynamoDBScanItems.go gets items from and Amazon DymanoDB table using the Expression Builder package.] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Scan function] -// snippet-keyword:[Expression Builder] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[dynamodb] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-03-19] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[dynamodb.go.scan_items] package main // snippet-start:[dynamodb.go.scan_items.imports] import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" - "github.com/aws/aws-sdk-go/service/dynamodb/expression" - - "fmt" - "log" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" + "github.com/aws/aws-sdk-go/service/dynamodb/expression" + + "fmt" + "log" ) + // snippet-end:[dynamodb.go.scan_items.imports] // snippet-start:[dynamodb.go.scan_items.struct] // Create struct to hold info about new item type Item struct { - Year int - Title string - Plot string - Rating float64 + Year int + Title string + Plot string + Rating float64 } + // snippet-end:[dynamodb.go.scan_items.struct] // Get the movies with a minimum rating of 4.0 in 2013 func main() { - // snippet-start:[dynamodb.go.scan_items.session] - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials - // and region from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create DynamoDB client - svc := dynamodb.New(sess) - // snippet-end:[dynamodb.go.scan_items.session] - - // snippet-start:[dynamodb.go.scan_items.vars] - tableName := "Movies" - minRating := 4.0 - year := 2013 - // snippet-end:[dynamodb.go.scan_items.vars] - - // snippet-start:[dynamodb.go.scan_items.expr] - // Create the Expression to fill the input struct with. - // Get all movies in that year; we'll pull out those with a higher rating later - filt := expression.Name("Year").Equal(expression.Value(year)) - - // Or we could get by ratings and pull out those with the right year later - // filt := expression.Name("info.rating").GreaterThan(expression.Value(min_rating)) - - // Get back the title, year, and rating - proj := expression.NamesList(expression.Name("Title"), expression.Name("Year"), expression.Name("Rating")) - - expr, err := expression.NewBuilder().WithFilter(filt).WithProjection(proj).Build() - if err != nil { - log.Fatalf("Got error building expression: %s", err) - } - // snippet-end:[dynamodb.go.scan_items.expr] - - // snippet-start:[dynamodb.go.scan_items.call] - // Build the query input parameters - params := &dynamodb.ScanInput{ - ExpressionAttributeNames: expr.Names(), - ExpressionAttributeValues: expr.Values(), - FilterExpression: expr.Filter(), - ProjectionExpression: expr.Projection(), - TableName: aws.String(tableName), - } - - // Make the DynamoDB Query API call - result, err := svc.Scan(params) - if err != nil { - log.Fatalf("Query API call failed: %s", err) - } - // snippet-end:[dynamodb.go.scan_items.call] - - // snippet-start:[dynamodb.go.scan_items.process] - numItems := 0 - - for _, i := range result.Items { - item := Item{} - - err = dynamodbattribute.UnmarshalMap(i, &item) - - if err != nil { - log.Fatalf("Got error unmarshalling: %s", err) - } - - // Which ones had a higher rating than minimum? - if item.Rating > minRating { - // Or it we had filtered by rating previously: - // if item.Year == year { - numItems++ - - fmt.Println("Title: ", item.Title) - fmt.Println("Rating:", item.Rating) - fmt.Println() - } - } - - fmt.Println("Found", numItems, "movie(s) with a rating above", minRating, "in", year) - // snippet-end:[dynamodb.go.scan_items.process] + // snippet-start:[dynamodb.go.scan_items.session] + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials + // and region from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create DynamoDB client + svc := dynamodb.New(sess) + // snippet-end:[dynamodb.go.scan_items.session] + + // snippet-start:[dynamodb.go.scan_items.vars] + tableName := "Movies" + minRating := 4.0 + year := 2013 + // snippet-end:[dynamodb.go.scan_items.vars] + + // snippet-start:[dynamodb.go.scan_items.expr] + // Create the Expression to fill the input struct with. + // Get all movies in that year; we'll pull out those with a higher rating later + filt := expression.Name("Year").Equal(expression.Value(year)) + + // Or we could get by ratings and pull out those with the right year later + // filt := expression.Name("info.rating").GreaterThan(expression.Value(min_rating)) + + // Get back the title, year, and rating + proj := expression.NamesList(expression.Name("Title"), expression.Name("Year"), expression.Name("Rating")) + + expr, err := expression.NewBuilder().WithFilter(filt).WithProjection(proj).Build() + if err != nil { + log.Fatalf("Got error building expression: %s", err) + } + // snippet-end:[dynamodb.go.scan_items.expr] + + // snippet-start:[dynamodb.go.scan_items.call] + // Build the query input parameters + params := &dynamodb.ScanInput{ + ExpressionAttributeNames: expr.Names(), + ExpressionAttributeValues: expr.Values(), + FilterExpression: expr.Filter(), + ProjectionExpression: expr.Projection(), + TableName: aws.String(tableName), + } + + // Make the DynamoDB Query API call + result, err := svc.Scan(params) + if err != nil { + log.Fatalf("Query API call failed: %s", err) + } + // snippet-end:[dynamodb.go.scan_items.call] + + // snippet-start:[dynamodb.go.scan_items.process] + numItems := 0 + + for _, i := range result.Items { + item := Item{} + + err = dynamodbattribute.UnmarshalMap(i, &item) + + if err != nil { + log.Fatalf("Got error unmarshalling: %s", err) + } + + // Which ones had a higher rating than minimum? + if item.Rating > minRating { + // Or it we had filtered by rating previously: + // if item.Year == year { + numItems++ + + fmt.Println("Title: ", item.Title) + fmt.Println("Rating:", item.Rating) + fmt.Println() + } + } + + fmt.Println("Found", numItems, "movie(s) with a rating above", minRating, "in", year) + // snippet-end:[dynamodb.go.scan_items.process] } + // snippet-end:[dynamodb.go.scan_items] diff --git a/go/example_code/dynamodb/DynamoDBUpdateItem.go b/go/example_code/dynamodb/DynamoDBUpdateItem.go index b59abd36415..8ea49d09917 100644 --- a/go/example_code/dynamodb/DynamoDBUpdateItem.go +++ b/go/example_code/dynamodb/DynamoDBUpdateItem.go @@ -1,86 +1,66 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[DynamoDBUpdateItem.go updates an item in an Amazon DynamoDB table.] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[UpdateItem function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[dynamodb] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-03-19] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[dynamodb.go.update_item] package main // snippet-start:[dynamodb.go.update_item.imports] import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" - "fmt" - "log" + "fmt" + "log" ) + // snippet-end:[dynamodb.go.update_item.imports] func main() { - // snippet-start:[dynamodb.go.update_item.session] - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials - // and region from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + // snippet-start:[dynamodb.go.update_item.session] + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials + // and region from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - // Create DynamoDB client - svc := dynamodb.New(sess) - // snippet-end:[dynamodb.go.update_item.session] + // Create DynamoDB client + svc := dynamodb.New(sess) + // snippet-end:[dynamodb.go.update_item.session] - // snippet-start:[dynamodb.go.update_item.call] - // Update item in table Movies - tableName := "Movies" - movieName := "The Big New Movie" - movieYear := "2015" - movieRating := "0.5" + // snippet-start:[dynamodb.go.update_item.call] + // Update item in table Movies + tableName := "Movies" + movieName := "The Big New Movie" + movieYear := "2015" + movieRating := "0.5" - input := &dynamodb.UpdateItemInput{ - ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{ - ":r": { - N: aws.String(movieRating), - }, - }, - TableName: aws.String(tableName), - Key: map[string]*dynamodb.AttributeValue{ - "Year": { - N: aws.String(movieYear), - }, - "Title": { - S: aws.String(movieName), - }, - }, - ReturnValues: aws.String("UPDATED_NEW"), - UpdateExpression: aws.String("set Rating = :r"), - } + input := &dynamodb.UpdateItemInput{ + ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{ + ":r": { + N: aws.String(movieRating), + }, + }, + TableName: aws.String(tableName), + Key: map[string]*dynamodb.AttributeValue{ + "Year": { + N: aws.String(movieYear), + }, + "Title": { + S: aws.String(movieName), + }, + }, + ReturnValues: aws.String("UPDATED_NEW"), + UpdateExpression: aws.String("set Rating = :r"), + } - _, err := svc.UpdateItem(input) - if err != nil { - log.Fatalf("Got error calling UpdateItem: %s", err) - } + _, err := svc.UpdateItem(input) + if err != nil { + log.Fatalf("Got error calling UpdateItem: %s", err) + } - fmt.Println("Successfully updated '" + movieName + "' (" + movieYear + ") rating to " + movieRating) - // snippet-end:[dynamodb.go.update_item.call] + fmt.Println("Successfully updated '" + movieName + "' (" + movieYear + ") rating to " + movieRating) + // snippet-end:[dynamodb.go.update_item.call] } + // snippet-end:[dynamodb.go.update_item] diff --git a/go/example_code/dynamodb/create_item.go b/go/example_code/dynamodb/create_item.go index c6bf587c372..0fcfef5f9d7 100644 --- a/go/example_code/dynamodb/create_item.go +++ b/go/example_code/dynamodb/create_item.go @@ -1,94 +1,72 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Creates an item in an Amazon DynamoDB table.] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[PutItem function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[dynamodb] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" - "fmt" - "os" + "fmt" + "os" ) // Create structs to hold info about new item type ItemInfo struct { - Plot string`json:"plot"` - Rating float64`json:"rating"` + Plot string `json:"plot"` + Rating float64 `json:"rating"` } type Item struct { - Year int`json:"year"` - Title string`json:"title"` - Info ItemInfo`json:"info"` + Year int `json:"year"` + Title string `json:"title"` + Info ItemInfo `json:"info"` } func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create DynamoDB client - svc := dynamodb.New(sess) - - info := ItemInfo{ - Plot: "Nothing happens at all.", - Rating: 0.0, - } - - item := Item{ - Year: 2015, - Title: "The Big New Movie", - Info: info, - } - - av, err := dynamodbattribute.MarshalMap(item) - - if err != nil { - fmt.Println("Got error marshalling map:") - fmt.Println(err.Error()) - os.Exit(1) - } - - // Create item in table Movies - input := &dynamodb.PutItemInput{ - Item: av, - TableName: aws.String("Movies"), - } - - _, err = svc.PutItem(input) - - if err != nil { - fmt.Println("Got error calling PutItem:") - fmt.Println(err.Error()) - os.Exit(1) - } - - fmt.Println("Successfully added 'The Big New Movie' (2015) to Movies table") + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create DynamoDB client + svc := dynamodb.New(sess) + + info := ItemInfo{ + Plot: "Nothing happens at all.", + Rating: 0.0, + } + + item := Item{ + Year: 2015, + Title: "The Big New Movie", + Info: info, + } + + av, err := dynamodbattribute.MarshalMap(item) + + if err != nil { + fmt.Println("Got error marshalling map:") + fmt.Println(err.Error()) + os.Exit(1) + } + + // Create item in table Movies + input := &dynamodb.PutItemInput{ + Item: av, + TableName: aws.String("Movies"), + } + + _, err = svc.PutItem(input) + + if err != nil { + fmt.Println("Got error calling PutItem:") + fmt.Println(err.Error()) + os.Exit(1) + } + + fmt.Println("Successfully added 'The Big New Movie' (2015) to Movies table") } diff --git a/go/example_code/dynamodb/create_table.go b/go/example_code/dynamodb/create_table.go index fb3d424d8c9..36325b635d8 100644 --- a/go/example_code/dynamodb/create_table.go +++ b/go/example_code/dynamodb/create_table.go @@ -1,85 +1,63 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Creates an Amazon DynamoDB table.] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[CreateTable function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[dynamodb] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" ) func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create DynamoDB client - svc := dynamodb.New(sess) - - // Create table Movies - input := &dynamodb.CreateTableInput{ - AttributeDefinitions: []*dynamodb.AttributeDefinition{ - { - AttributeName: aws.String("year"), - AttributeType: aws.String("N"), - }, - { - AttributeName: aws.String("title"), - AttributeType: aws.String("S"), - }, - }, - KeySchema: []*dynamodb.KeySchemaElement{ - { - AttributeName: aws.String("year"), - KeyType: aws.String("HASH"), - }, - { - AttributeName: aws.String("title"), - KeyType: aws.String("RANGE"), - }, - }, - ProvisionedThroughput: &dynamodb.ProvisionedThroughput{ - ReadCapacityUnits: aws.Int64(10), - WriteCapacityUnits: aws.Int64(10), - }, - TableName: aws.String("Movies"), - } - - _, err = svc.CreateTable(input) - - if err != nil { - fmt.Println("Got error calling CreateTable:") - fmt.Println(err.Error()) - os.Exit(1) - } - - fmt.Println("Created the table Movies in us-west-2") + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create DynamoDB client + svc := dynamodb.New(sess) + + // Create table Movies + input := &dynamodb.CreateTableInput{ + AttributeDefinitions: []*dynamodb.AttributeDefinition{ + { + AttributeName: aws.String("year"), + AttributeType: aws.String("N"), + }, + { + AttributeName: aws.String("title"), + AttributeType: aws.String("S"), + }, + }, + KeySchema: []*dynamodb.KeySchemaElement{ + { + AttributeName: aws.String("year"), + KeyType: aws.String("HASH"), + }, + { + AttributeName: aws.String("title"), + KeyType: aws.String("RANGE"), + }, + }, + ProvisionedThroughput: &dynamodb.ProvisionedThroughput{ + ReadCapacityUnits: aws.Int64(10), + WriteCapacityUnits: aws.Int64(10), + }, + TableName: aws.String("Movies"), + } + + _, err = svc.CreateTable(input) + + if err != nil { + fmt.Println("Got error calling CreateTable:") + fmt.Println(err.Error()) + os.Exit(1) + } + + fmt.Println("Created the table Movies in us-west-2") } diff --git a/go/example_code/dynamodb/delete_item.go b/go/example_code/dynamodb/delete_item.go index caa73424622..9450c17ed2b 100644 --- a/go/example_code/dynamodb/delete_item.go +++ b/go/example_code/dynamodb/delete_item.go @@ -1,80 +1,59 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Deletes an item from an Amazon DynamoDB table.] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[DeleteItem function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[dynamodb] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-03-12] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[dynamodb.go.deleteitem] package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" - - "fmt" - "os" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" + + "fmt" + "os" ) // Item has the values for a movie type Item struct { - Year int `json:"year"` - Title string `json:"title"` + Year int `json:"year"` + Title string `json:"title"` } func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create DynamoDB client - svc := dynamodb.New(sess) - - item := Item{ - Year: 2015, - Title: "The Big New Movie", - } - - av, err := dynamodbattribute.MarshalMap(item) - if err != nil { - fmt.Println("Got error marshalling map:") - fmt.Println(err.Error()) - os.Exit(1) - } - - input := &dynamodb.DeleteItemInput{ - Key: av, - TableName: aws.String("Movies"), - } - - _, err = svc.DeleteItem(input) - if err != nil { - fmt.Println("Got error calling DeleteItem") - fmt.Println(err.Error()) - return - } - - fmt.Println("Deleted 'The Big New Movie' (2015)") + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create DynamoDB client + svc := dynamodb.New(sess) + + item := Item{ + Year: 2015, + Title: "The Big New Movie", + } + + av, err := dynamodbattribute.MarshalMap(item) + if err != nil { + fmt.Println("Got error marshalling map:") + fmt.Println(err.Error()) + os.Exit(1) + } + + input := &dynamodb.DeleteItemInput{ + Key: av, + TableName: aws.String("Movies"), + } + + _, err = svc.DeleteItem(input) + if err != nil { + fmt.Println("Got error calling DeleteItem") + fmt.Println(err.Error()) + return + } + + fmt.Println("Deleted 'The Big New Movie' (2015)") } -// snippet-end:[dynamodb.go.deleteitem] \ No newline at end of file + +// snippet-end:[dynamodb.go.deleteitem] diff --git a/go/example_code/dynamodb/list_tables.go b/go/example_code/dynamodb/list_tables.go index a300a8b19cb..295a41a805a 100644 --- a/go/example_code/dynamodb/list_tables.go +++ b/go/example_code/dynamodb/list_tables.go @@ -1,84 +1,62 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Lists your Amazon DynamoDB tables.] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[ListTables function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[dynamodb] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-04-24] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" ) func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, _ := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create DynamoDB client - svc := dynamodb.New(sess) - - // create the input configuration instance - input := &dynamodb.ListTablesInput{} - - fmt.Printf("Tables:\n") - - for { - // Get the list of tables - result, err := svc.ListTables(input) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case dynamodb.ErrCodeInternalServerError: - fmt.Println(dynamodb.ErrCodeInternalServerError, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - return - } - - for _, n := range result.TableNames { - fmt.Println(*n) - } - - // assign the last read tablename as the start for our next call to the ListTables function - // the maximum number of table names returned in a call is 100 (default), which requires us to make - // multiple calls to the ListTables function to retrieve all table names - input.ExclusiveStartTableName = result.LastEvaluatedTableName - - if result.LastEvaluatedTableName == nil { - break - } - } + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, _ := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create DynamoDB client + svc := dynamodb.New(sess) + + // create the input configuration instance + input := &dynamodb.ListTablesInput{} + + fmt.Printf("Tables:\n") + + for { + // Get the list of tables + result, err := svc.ListTables(input) + if err != nil { + if aerr, ok := err.(awserr.Error); ok { + switch aerr.Code() { + case dynamodb.ErrCodeInternalServerError: + fmt.Println(dynamodb.ErrCodeInternalServerError, aerr.Error()) + default: + fmt.Println(aerr.Error()) + } + } else { + // Print the error, cast err to awserr.Error to get the Code and + // Message from an error. + fmt.Println(err.Error()) + } + return + } + + for _, n := range result.TableNames { + fmt.Println(*n) + } + + // assign the last read tablename as the start for our next call to the ListTables function + // the maximum number of table names returned in a call is 100 (default), which requires us to make + // multiple calls to the ListTables function to retrieve all table names + input.ExclusiveStartTableName = result.LastEvaluatedTableName + + if result.LastEvaluatedTableName == nil { + break + } + } } diff --git a/go/example_code/dynamodb/load_items.go b/go/example_code/dynamodb/load_items.go index fce8f7b5dfb..2212ef9d9e6 100644 --- a/go/example_code/dynamodb/load_items.go +++ b/go/example_code/dynamodb/load_items.go @@ -1,27 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Adds items from a JSON file to an Amazon DynamoDB table.] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[PutItem function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[dynamodb] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main @@ -30,6 +8,7 @@ import ( "fmt" "io/ioutil" "log" + "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" diff --git a/go/example_code/dynamodb/read_item.go b/go/example_code/dynamodb/read_item.go index ceaa2901a4a..1c2f3b71087 100644 --- a/go/example_code/dynamodb/read_item.go +++ b/go/example_code/dynamodb/read_item.go @@ -1,94 +1,72 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Gets an item from an Amazon DynamoDB table.] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[GetItem function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[dynamodb] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "log" + "fmt" + "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" ) // Create structs to hold info about new item type ItemInfo struct { - Plot string`json:"plot"` - Rating float64`json:"rating"` + Plot string `json:"plot"` + Rating float64 `json:"rating"` } type Item struct { - Year int`json:"year"` - Title string`json:"title"` - Info ItemInfo`json:"info"` + Year int `json:"year"` + Title string `json:"title"` + Info ItemInfo `json:"info"` } func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create DynamoDB client - svc := dynamodb.New(sess) - - result, err := svc.GetItem(&dynamodb.GetItemInput{ - TableName: aws.String("Movies"), - Key: map[string]*dynamodb.AttributeValue{ - "year": { - N: aws.String("2015"), - }, - "title": { - S: aws.String("The Big New Movie"), - }, - }, - }) - - if err != nil { - log.Fatalf("Got error calling GetItem: %s", err) - } - - item := Item{} - - err = dynamodbattribute.UnmarshalMap(result.Item, &item) - - if err != nil { - panic(fmt.Sprintf("Failed to unmarshal Record, %v", err)) - } - - if item.Title == "" { - fmt.Println("Could not find 'The Big New Movie' (2015)") - return - } - - fmt.Println("Found item:") - fmt.Println("Year: ", item.Year) - fmt.Println("Title: ", item.Title) - fmt.Println("Plot: ", item.Info.Plot) - fmt.Println("Rating:", item.Info.Rating) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create DynamoDB client + svc := dynamodb.New(sess) + + result, err := svc.GetItem(&dynamodb.GetItemInput{ + TableName: aws.String("Movies"), + Key: map[string]*dynamodb.AttributeValue{ + "year": { + N: aws.String("2015"), + }, + "title": { + S: aws.String("The Big New Movie"), + }, + }, + }) + + if err != nil { + log.Fatalf("Got error calling GetItem: %s", err) + } + + item := Item{} + + err = dynamodbattribute.UnmarshalMap(result.Item, &item) + + if err != nil { + panic(fmt.Sprintf("Failed to unmarshal Record, %v", err)) + } + + if item.Title == "" { + fmt.Println("Could not find 'The Big New Movie' (2015)") + return + } + + fmt.Println("Found item:") + fmt.Println("Year: ", item.Year) + fmt.Println("Title: ", item.Title) + fmt.Println("Plot: ", item.Info.Plot) + fmt.Println("Rating:", item.Info.Rating) } diff --git a/go/example_code/dynamodb/scan_items.go b/go/example_code/dynamodb/scan_items.go index c2fa54dc7f7..195cad22b02 100644 --- a/go/example_code/dynamodb/scan_items.go +++ b/go/example_code/dynamodb/scan_items.go @@ -1,126 +1,103 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Gets items from and Amazon DymanoDB table using the Expression Builder package.] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Scan function] -// snippet-keyword:[Expression Builder] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[dynamodb] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "log" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" - "github.com/aws/aws-sdk-go/service/dynamodb/expression" + "fmt" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" + "github.com/aws/aws-sdk-go/service/dynamodb/expression" ) // Create structs to hold info about new item type ItemInfo struct { - Plot string`json:"plot"` - Rating float64`json:"rating"` + Plot string `json:"plot"` + Rating float64 `json:"rating"` } type Item struct { - Year int`json:"year"` - Title string`json:"title"` - Info ItemInfo`json:"info"` + Year int `json:"year"` + Title string `json:"title"` + Info ItemInfo `json:"info"` } // Get the movies with a minimum rating of 8.0 in 2011 func main() { - min_rating := 8.0 - year := 2011 + min_rating := 8.0 + year := 2011 - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) - if err != nil { - log.Fatalf("Got error creating session: %s", err) - } + if err != nil { + log.Fatalf("Got error creating session: %s", err) + } - // Create DynamoDB client - svc := dynamodb.New(sess) + // Create DynamoDB client + svc := dynamodb.New(sess) - // Create the Expression to fill the input struct with. - // Get all movies in that year; we'll pull out those with a higher rating later - filt := expression.Name("year").Equal(expression.Value(year)) + // Create the Expression to fill the input struct with. + // Get all movies in that year; we'll pull out those with a higher rating later + filt := expression.Name("year").Equal(expression.Value(year)) - // Or we could get by ratings and pull out those with the right year later - // filt := expression.Name("info.rating").GreaterThan(expression.Value(min_rating)) + // Or we could get by ratings and pull out those with the right year later + // filt := expression.Name("info.rating").GreaterThan(expression.Value(min_rating)) - // Get back the title, year, and rating - proj := expression.NamesList(expression.Name("title"), expression.Name("year"), expression.Name("info.rating")) + // Get back the title, year, and rating + proj := expression.NamesList(expression.Name("title"), expression.Name("year"), expression.Name("info.rating")) - expr, err := expression.NewBuilder().WithFilter(filt).WithProjection(proj).Build() + expr, err := expression.NewBuilder().WithFilter(filt).WithProjection(proj).Build() - if err != nil { - log.Fatalf("Got error building expression: %s", err) - } + if err != nil { + log.Fatalf("Got error building expression: %s", err) + } - // Build the query input parameters - params := &dynamodb.ScanInput{ - ExpressionAttributeNames: expr.Names(), - ExpressionAttributeValues: expr.Values(), - FilterExpression: expr.Filter(), - ProjectionExpression: expr.Projection(), - TableName: aws.String("Movies"), - } + // Build the query input parameters + params := &dynamodb.ScanInput{ + ExpressionAttributeNames: expr.Names(), + ExpressionAttributeValues: expr.Values(), + FilterExpression: expr.Filter(), + ProjectionExpression: expr.Projection(), + TableName: aws.String("Movies"), + } - // Make the DynamoDB Query API call - result, err := svc.Scan(params) + // Make the DynamoDB Query API call + result, err := svc.Scan(params) - if err != nil { - log.Fatalf("Query API call failed: %s", err) - } + if err != nil { + log.Fatalf("Query API call failed: %s", err) + } - num_items := 0 + num_items := 0 - for _, i := range result.Items { - item := Item{} + for _, i := range result.Items { + item := Item{} - err = dynamodbattribute.UnmarshalMap(i, &item) + err = dynamodbattribute.UnmarshalMap(i, &item) - if err != nil { - log.Fatalf("Got error unmarshalling: %s", err) - } + if err != nil { + log.Fatalf("Got error unmarshalling: %s", err) + } - // Which ones had a higher rating? - if item.Info.Rating > min_rating { - // Or it we had filtered by rating previously: - // if item.Year == year { - num_items += 1 + // Which ones had a higher rating? + if item.Info.Rating > min_rating { + // Or it we had filtered by rating previously: + // if item.Year == year { + num_items += 1 - fmt.Println("Title: ", item.Title) - fmt.Println("Rating:", item.Info.Rating) - fmt.Println() - } - } + fmt.Println("Title: ", item.Title) + fmt.Println("Rating:", item.Info.Rating) + fmt.Println() + } + } - fmt.Println("Found", num_items, "movie(s) with a rating above", min_rating, "in", year) + fmt.Println("Found", num_items, "movie(s) with a rating above", min_rating, "in", year) } diff --git a/go/example_code/dynamodb/update_item.go b/go/example_code/dynamodb/update_item.go index 8523fcdefcc..501ae392899 100644 --- a/go/example_code/dynamodb/update_item.go +++ b/go/example_code/dynamodb/update_item.go @@ -1,93 +1,71 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Updates an item in an Amazon DynamoDB table.] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[UpdateItem function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[dynamodb] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-03-12] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" - "fmt" - "log" + "fmt" + "log" ) // ItemInfo holds info to update type ItemInfo struct { - Rating float64 `json:"rating"` + Rating float64 `json:"rating"` } // Item identifies the item in the table type Item struct { - Year int `json:"year"` - Title string `json:"title"` + Year int `json:"year"` + Title string `json:"title"` } func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create DynamoDB client - svc := dynamodb.New(sess) - - info := ItemInfo{ - Rating: 0.5, - } - - item := Item{ - Year: 2015, - Title: "The Big New Movie", - } - - expr, err := dynamodbattribute.MarshalMap(info) - if err != nil { - log.Fatalf("Got error marshalling info: %s", err) - } - - key, err := dynamodbattribute.MarshalMap(item) - if err != nil { - log.Fatalf("Got error marshalling item: %s", err) - } - - // Update item in table Movies - input := &dynamodb.UpdateItemInput{ - ExpressionAttributeValues: expr, - TableName: aws.String("Movies"), - Key: key, - ReturnValues: aws.String("UPDATED_NEW"), - UpdateExpression: aws.String("set info.rating = :r"), - } - - _, err = svc.UpdateItem(input) - if err != nil { - log.Fatalf("Got error calling UpdateItem: %s", err) - } - - fmt.Println("Successfully updated 'The Big New Movie' (2015) rating to 0.5") + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create DynamoDB client + svc := dynamodb.New(sess) + + info := ItemInfo{ + Rating: 0.5, + } + + item := Item{ + Year: 2015, + Title: "The Big New Movie", + } + + expr, err := dynamodbattribute.MarshalMap(info) + if err != nil { + log.Fatalf("Got error marshalling info: %s", err) + } + + key, err := dynamodbattribute.MarshalMap(item) + if err != nil { + log.Fatalf("Got error marshalling item: %s", err) + } + + // Update item in table Movies + input := &dynamodb.UpdateItemInput{ + ExpressionAttributeValues: expr, + TableName: aws.String("Movies"), + Key: key, + ReturnValues: aws.String("UPDATED_NEW"), + UpdateExpression: aws.String("set info.rating = :r"), + } + + _, err = svc.UpdateItem(input) + if err != nil { + log.Fatalf("Got error calling UpdateItem: %s", err) + } + + fmt.Println("Successfully updated 'The Big New Movie' (2015) rating to 0.5") } diff --git a/go/example_code/ec2/create_image_no_block_device.go b/go/example_code/ec2/create_image_no_block_device.go index 6333431be46..5c5b2c098f5 100644 --- a/go/example_code/ec2/create_image_no_block_device.go +++ b/go/example_code/ec2/create_image_no_block_device.go @@ -1,71 +1,49 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Creates an Amazon EC2 instance without a block device.] -// snippet-keyword:[Amazon Elastic Compute Cloud] -// snippet-keyword:[CreateImage function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ec2] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-11-08] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ec2" - "fmt" + "fmt" ) func main() { - // Load session from shared config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create EC2 service client - svc := ec2.New(sess) - - opts := &ec2.CreateImageInput{ - Description: aws.String("image description"), - InstanceId: aws.String("i-abcdef12"), - Name: aws.String("image name"), - BlockDeviceMappings: []*ec2.BlockDeviceMapping{ - { - DeviceName: aws.String("/dev/sda1"), - NoDevice: aws.String(""), - }, - { - DeviceName: aws.String("/dev/sdb"), - NoDevice: aws.String(""), - }, - { - DeviceName: aws.String("/dev/sdc"), - NoDevice: aws.String(""), - }, - }, - } - resp, err := svc.CreateImage(opts) - if err != nil { - fmt.Println(err) - return - } - - fmt.Println("ID: ", resp.ImageId) + // Load session from shared config + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create EC2 service client + svc := ec2.New(sess) + + opts := &ec2.CreateImageInput{ + Description: aws.String("image description"), + InstanceId: aws.String("i-abcdef12"), + Name: aws.String("image name"), + BlockDeviceMappings: []*ec2.BlockDeviceMapping{ + { + DeviceName: aws.String("/dev/sda1"), + NoDevice: aws.String(""), + }, + { + DeviceName: aws.String("/dev/sdb"), + NoDevice: aws.String(""), + }, + { + DeviceName: aws.String("/dev/sdc"), + NoDevice: aws.String(""), + }, + }, + } + resp, err := svc.CreateImage(opts) + if err != nil { + fmt.Println(err) + return + } + + fmt.Println("ID: ", resp.ImageId) } diff --git a/go/example_code/ec2/create_instance.go b/go/example_code/ec2/create_instance.go index a6ad9e248e2..9532f1c08a1 100644 --- a/go/example_code/ec2/create_instance.go +++ b/go/example_code/ec2/create_instance.go @@ -1,78 +1,55 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Creates an Amazon EC2 instance with tags.] -// snippet-keyword:[Amazon Elastic Compute Cloud] -// snippet-keyword:[CreateTags function] -// snippet-keyword:[RunInstances function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ec2] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-11-08] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ec2" - "fmt" - "log" + "fmt" + "log" ) func main() { - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create EC2 service client - svc := ec2.New(sess) - - // Specify the details of the instance that you want to create. - runResult, err := svc.RunInstances(&ec2.RunInstancesInput{ - // An Amazon Linux AMI ID for t2.micro instances in the us-west-2 region - ImageId: aws.String("ami-e7527ed7"), - InstanceType: aws.String("t2.micro"), - MinCount: aws.Int64(1), - MaxCount: aws.Int64(1), - }) - - if err != nil { - fmt.Println("Could not create instance", err) - return - } - - fmt.Println("Created instance", *runResult.Instances[0].InstanceId) - - // Add tags to the created instance - _, errtag := svc.CreateTags(&ec2.CreateTagsInput{ - Resources: []*string{runResult.Instances[0].InstanceId}, - Tags: []*ec2.Tag{ - { - Key: aws.String("Name"), - Value: aws.String("MyFirstInstance"), - }, - }, - }) - if errtag != nil { - log.Println("Could not create tags for instance", runResult.Instances[0].InstanceId, errtag) - return - } - - fmt.Println("Successfully tagged instance") -} \ No newline at end of file + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create EC2 service client + svc := ec2.New(sess) + + // Specify the details of the instance that you want to create. + runResult, err := svc.RunInstances(&ec2.RunInstancesInput{ + // An Amazon Linux AMI ID for t2.micro instances in the us-west-2 region + ImageId: aws.String("ami-e7527ed7"), + InstanceType: aws.String("t2.micro"), + MinCount: aws.Int64(1), + MaxCount: aws.Int64(1), + }) + + if err != nil { + fmt.Println("Could not create instance", err) + return + } + + fmt.Println("Created instance", *runResult.Instances[0].InstanceId) + + // Add tags to the created instance + _, errtag := svc.CreateTags(&ec2.CreateTagsInput{ + Resources: []*string{runResult.Instances[0].InstanceId}, + Tags: []*ec2.Tag{ + { + Key: aws.String("Name"), + Value: aws.String("MyFirstInstance"), + }, + }, + }) + if errtag != nil { + log.Println("Could not create tags for instance", runResult.Instances[0].InstanceId, errtag) + return + } + + fmt.Println("Successfully tagged instance") +} diff --git a/go/example_code/ec2/describing_instances.go b/go/example_code/ec2/describing_instances.go index 6fe5738e633..5ea72cb98c4 100644 --- a/go/example_code/ec2/describing_instances.go +++ b/go/example_code/ec2/describing_instances.go @@ -1,51 +1,29 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Describes your Amazon EC2 instances.] -// snippet-keyword:[Amazon Elastic Compute Cloud] -// snippet-keyword:[DescribeInstances function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ec2] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ec2" - "fmt" + "fmt" ) func main() { - // Load session from shared config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create new EC2 client - ec2Svc := ec2.New(sess) - - // Call to get detailed information on each instance - result, err := ec2Svc.DescribeInstances(nil) - if err != nil { - fmt.Println("Error", err) - } else { - fmt.Println("Success", result) - } + // Load session from shared config + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create new EC2 client + ec2Svc := ec2.New(sess) + + // Call to get detailed information on each instance + result, err := ec2Svc.DescribeInstances(nil) + if err != nil { + fmt.Println("Error", err) + } else { + fmt.Println("Success", result) + } } diff --git a/go/example_code/ec2/ec2_allocate_address.go b/go/example_code/ec2/ec2_allocate_address.go index 360ee7c7aae..89c36d22fb3 100644 --- a/go/example_code/ec2/ec2_allocate_address.go +++ b/go/example_code/ec2/ec2_allocate_address.go @@ -1,85 +1,63 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Allocates a static IP address and associates it with an Amazon EC2 instance.] -// snippet-keyword:[Amazon Elastic Compute Cloud] -// snippet-keyword:[AllocateAddress function] -// snippet-keyword:[AssociateAddress function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ec2] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" - "path/filepath" + "fmt" + "os" + "path/filepath" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ec2" ) // Attempts to allocate an VPC Elastic IP Address for region. The IP // address will be associated with the instance ID passed in. // // Usage: -// go run ec2_allocate_address.go INSTANCE_ID +// +// go run ec2_allocate_address.go INSTANCE_ID func main() { - if len(os.Args) != 2 { - exitErrorf("instance ID required\nUsage: %s instance_id", - filepath.Base(os.Args[0])) - } - instanceID := os.Args[1] - - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create an EC2 service client. - svc := ec2.New(sess) - - // Attempt to allocate the Elastic IP address. - allocRes, err := svc.AllocateAddress(&ec2.AllocateAddressInput{ - Domain: aws.String("vpc"), - }) - if err != nil { - exitErrorf("Unable to allocate IP address, %v", err) - } - - // Associate the new Elastic IP address with an existing EC2 instance. - assocRes, err := svc.AssociateAddress(&ec2.AssociateAddressInput{ - AllocationId: allocRes.AllocationId, - InstanceId: aws.String(instanceID), - }) - if err != nil { - exitErrorf("Unable to associate IP address with %s, %v", - instanceID, err) - } - - fmt.Printf("Successfully allocated %s with instance %s.\n\tallocation id: %s, association id: %s\n", - *allocRes.PublicIp, instanceID, *allocRes.AllocationId, *assocRes.AssociationId) + if len(os.Args) != 2 { + exitErrorf("instance ID required\nUsage: %s instance_id", + filepath.Base(os.Args[0])) + } + instanceID := os.Args[1] + + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create an EC2 service client. + svc := ec2.New(sess) + + // Attempt to allocate the Elastic IP address. + allocRes, err := svc.AllocateAddress(&ec2.AllocateAddressInput{ + Domain: aws.String("vpc"), + }) + if err != nil { + exitErrorf("Unable to allocate IP address, %v", err) + } + + // Associate the new Elastic IP address with an existing EC2 instance. + assocRes, err := svc.AssociateAddress(&ec2.AssociateAddressInput{ + AllocationId: allocRes.AllocationId, + InstanceId: aws.String(instanceID), + }) + if err != nil { + exitErrorf("Unable to associate IP address with %s, %v", + instanceID, err) + } + + fmt.Printf("Successfully allocated %s with instance %s.\n\tallocation id: %s, association id: %s\n", + *allocRes.PublicIp, instanceID, *allocRes.AllocationId, *assocRes.AssociationId) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/ec2/ec2_create_keypair.go b/go/example_code/ec2/ec2_create_keypair.go index b795ef14553..0c03d36dc71 100644 --- a/go/example_code/ec2/ec2_create_keypair.go +++ b/go/example_code/ec2/ec2_create_keypair.go @@ -1,78 +1,57 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Creates an Amazon EC2 key pair.] -// snippet-keyword:[Amazon Elastic Compute Cloud] -// snippet-keyword:[CreateKeyPair function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ec2] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" - "path/filepath" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" + "fmt" + "os" + "path/filepath" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ec2" ) // Creates a new EC2 key pair for the name provided. // // Usage: -// go run ec2_create_keypair.go KEY_PAIR_NAME +// +// go run ec2_create_keypair.go KEY_PAIR_NAME func main() { - if len(os.Args) != 2 { - exitErrorf("pair name required\nUsage: %s key_pair_name", - filepath.Base(os.Args[0])) - } - pairName := os.Args[1] - - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create an EC2 service client. - svc := ec2.New(sess) - - // Creates a new key pair with the given name - result, err := svc.CreateKeyPair(&ec2.CreateKeyPairInput{ - KeyName: aws.String(pairName), - }) - if err != nil { - if aerr, ok := err.(awserr.Error); ok && aerr.Code() == "InvalidKeyPair.Duplicate" { - exitErrorf("Keypair %q already exists.", pairName) - } - exitErrorf("Unable to create key pair: %s, %v.", pairName, err) - } - - fmt.Printf("Created key pair %q %s\n%s\n", - *result.KeyName, *result.KeyFingerprint, - *result.KeyMaterial) + if len(os.Args) != 2 { + exitErrorf("pair name required\nUsage: %s key_pair_name", + filepath.Base(os.Args[0])) + } + pairName := os.Args[1] + + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create an EC2 service client. + svc := ec2.New(sess) + + // Creates a new key pair with the given name + result, err := svc.CreateKeyPair(&ec2.CreateKeyPairInput{ + KeyName: aws.String(pairName), + }) + if err != nil { + if aerr, ok := err.(awserr.Error); ok && aerr.Code() == "InvalidKeyPair.Duplicate" { + exitErrorf("Keypair %q already exists.", pairName) + } + exitErrorf("Unable to create key pair: %s, %v.", pairName, err) + } + + fmt.Printf("Created key pair %q %s\n%s\n", + *result.KeyName, *result.KeyFingerprint, + *result.KeyMaterial) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/ec2/ec2_create_security_group.go b/go/example_code/ec2/ec2_create_security_group.go index 7b4e935f9f2..f67765cb09b 100644 --- a/go/example_code/ec2/ec2_create_security_group.go +++ b/go/example_code/ec2/ec2_create_security_group.go @@ -1,43 +1,20 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Creates an EC2 security group.] -// snippet-keyword:[Amazon Elastic Compute Cloud] -// snippet-keyword:[AuthorizeSecurityGroupIngress function] -// snippet-keyword:[CreateSecurityGroup function] -// snippet-keyword:[DescribeVpcs function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ec2] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-1-6] -/* - Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[ec2.go.create_security_group.complete] package main // snippet-start:[ec2.go.create_security_group.imports] import ( - "flag" - "fmt" - "os" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" + "flag" + "fmt" + "os" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ec2" ) + // snippet-end:[ec2.go.create_security_group.imports] // Creates a new security group with the given name and description for @@ -45,106 +22,108 @@ import ( // first VPC in the account if a VPC ID is not provided. // // Usage: -// go run ec2_describe_security_groups.go -n name -d description -vpc vpcID +// +// go run ec2_describe_security_groups.go -n name -d description -vpc vpcID func main() { - // snippet-start:[ec2.go.create_security_group.vars] - namePtr := flag.String("n", "", "Group Name") - descPtr := flag.String("d", "", "Group Description") - vpcIDPtr := flag.String("vpc", "", "(Optional) VPC ID to associate security group with") - - flag.Parse() - - if *namePtr == "" || *descPtr == "" { - flag.PrintDefaults() - exitErrorf("Group name and description require") - } - // snippet-end:[ec2.go.create_security_group.vars] - - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - // snippet-start:[ec2.go.create_security_group.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := ec2.New(sess) - // snippet-end:[ec2.go.create_security_group.session] - - // If the VPC ID wasn't provided in the CLI retrieve the first in the account. - // snippet-start:[ec2.go.create_security_group.vpcid] - if *vpcIDPtr == "" { - // Get a list of VPCs so we can associate the group with the first VPC. - result, err := svc.DescribeVpcs(nil) - if err != nil { - exitErrorf("Unable to describe VPCs, %v", err) - } - if len(result.Vpcs) == 0 { - exitErrorf("No VPCs found to associate security group with.") - } - - *vpcIDPtr = aws.StringValue(result.Vpcs[0].VpcId) - } - // snippet-end:[ec2.go.create_security_group.vpcid] - - // Create the security group with the VPC, name and description. - // snippet-start:[ec2.go.create_security_group.create] - createRes, err := svc.CreateSecurityGroup(&ec2.CreateSecurityGroupInput{ - GroupName: aws.String(*namePtr), - Description: aws.String(*descPtr), - VpcId: aws.String(*vpcIDPtr), - }) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case "InvalidVpcID.NotFound": - exitErrorf("Unable to find VPC with ID %q.", *vpcIDPtr) - case "InvalidGroup.Duplicate": - exitErrorf("Security group %q already exists.", *namePtr) - } - } - exitErrorf("Unable to create security group %q, %v", *namePtr, err) - } - - fmt.Printf("Created security group %s with VPC %s.\n", - aws.StringValue(createRes.GroupId), *vpcIDPtr) - // snippet-end:[ec2.go.create_security_group.create] - - // Add permissions to the security group - // snippet-start:[ec2.go.create_security_group.permissions] - _, err = svc.AuthorizeSecurityGroupIngress(&ec2.AuthorizeSecurityGroupIngressInput{ - GroupName: aws.String(*namePtr), - IpPermissions: []*ec2.IpPermission{ - // Can use setters to simplify seting multiple values without the - // needing to use aws.String or associated helper utilities. - (&ec2.IpPermission{}). - SetIpProtocol("tcp"). - SetFromPort(80). - SetToPort(80). - SetIpRanges([]*ec2.IpRange{ - {CidrIp: aws.String("0.0.0.0/0")}, - }), - (&ec2.IpPermission{}). - SetIpProtocol("tcp"). - SetFromPort(22). - SetToPort(22). - SetIpRanges([]*ec2.IpRange{ - (&ec2.IpRange{}). - SetCidrIp("0.0.0.0/0"), - }), - }, - }) - if err != nil { - exitErrorf("Unable to set security group %q ingress, %v", *namePtr, err) - } - - fmt.Println("Successfully set security group ingress") - // snippet-end:[ec2.go.create_security_group.permissions] + // snippet-start:[ec2.go.create_security_group.vars] + namePtr := flag.String("n", "", "Group Name") + descPtr := flag.String("d", "", "Group Description") + vpcIDPtr := flag.String("vpc", "", "(Optional) VPC ID to associate security group with") + + flag.Parse() + + if *namePtr == "" || *descPtr == "" { + flag.PrintDefaults() + exitErrorf("Group name and description require") + } + // snippet-end:[ec2.go.create_security_group.vars] + + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + // snippet-start:[ec2.go.create_security_group.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := ec2.New(sess) + // snippet-end:[ec2.go.create_security_group.session] + + // If the VPC ID wasn't provided in the CLI retrieve the first in the account. + // snippet-start:[ec2.go.create_security_group.vpcid] + if *vpcIDPtr == "" { + // Get a list of VPCs so we can associate the group with the first VPC. + result, err := svc.DescribeVpcs(nil) + if err != nil { + exitErrorf("Unable to describe VPCs, %v", err) + } + if len(result.Vpcs) == 0 { + exitErrorf("No VPCs found to associate security group with.") + } + + *vpcIDPtr = aws.StringValue(result.Vpcs[0].VpcId) + } + // snippet-end:[ec2.go.create_security_group.vpcid] + + // Create the security group with the VPC, name and description. + // snippet-start:[ec2.go.create_security_group.create] + createRes, err := svc.CreateSecurityGroup(&ec2.CreateSecurityGroupInput{ + GroupName: aws.String(*namePtr), + Description: aws.String(*descPtr), + VpcId: aws.String(*vpcIDPtr), + }) + if err != nil { + if aerr, ok := err.(awserr.Error); ok { + switch aerr.Code() { + case "InvalidVpcID.NotFound": + exitErrorf("Unable to find VPC with ID %q.", *vpcIDPtr) + case "InvalidGroup.Duplicate": + exitErrorf("Security group %q already exists.", *namePtr) + } + } + exitErrorf("Unable to create security group %q, %v", *namePtr, err) + } + + fmt.Printf("Created security group %s with VPC %s.\n", + aws.StringValue(createRes.GroupId), *vpcIDPtr) + // snippet-end:[ec2.go.create_security_group.create] + + // Add permissions to the security group + // snippet-start:[ec2.go.create_security_group.permissions] + _, err = svc.AuthorizeSecurityGroupIngress(&ec2.AuthorizeSecurityGroupIngressInput{ + GroupName: aws.String(*namePtr), + IpPermissions: []*ec2.IpPermission{ + // Can use setters to simplify seting multiple values without the + // needing to use aws.String or associated helper utilities. + (&ec2.IpPermission{}). + SetIpProtocol("tcp"). + SetFromPort(80). + SetToPort(80). + SetIpRanges([]*ec2.IpRange{ + {CidrIp: aws.String("0.0.0.0/0")}, + }), + (&ec2.IpPermission{}). + SetIpProtocol("tcp"). + SetFromPort(22). + SetToPort(22). + SetIpRanges([]*ec2.IpRange{ + (&ec2.IpRange{}). + SetCidrIp("0.0.0.0/0"), + }), + }, + }) + if err != nil { + exitErrorf("Unable to set security group %q ingress, %v", *namePtr, err) + } + + fmt.Println("Successfully set security group ingress") + // snippet-end:[ec2.go.create_security_group.permissions] } // snippet-start:[ec2.go.create_security_group.exit] func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } + // snippet-end:[ec2.go.create_security_group.exit] // snippet-end:[ec2.go.create_security_group.complete] diff --git a/go/example_code/ec2/ec2_delete_keypair.go b/go/example_code/ec2/ec2_delete_keypair.go index 163ea6580fe..5030b29fc5b 100644 --- a/go/example_code/ec2/ec2_delete_keypair.go +++ b/go/example_code/ec2/ec2_delete_keypair.go @@ -1,77 +1,56 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Deletes an Amazon EC2 key pair.] -// snippet-keyword:[Amazon Elastic Compute Cloud] -// snippet-keyword:[DeleteKeyPair function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ec2] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" - "path/filepath" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" + "fmt" + "os" + "path/filepath" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ec2" ) // Deletes a EC2 key pair for the name provided. No error will be returned // if the key pair does not exist. // // Usage: -// go run ec2_delete_keypair.go KEY_PAIR_NAME +// +// go run ec2_delete_keypair.go KEY_PAIR_NAME func main() { - if len(os.Args) != 2 { - exitErrorf("pair name required\nUsage: %s key_pair_name", - filepath.Base(os.Args[0])) - } - pairName := os.Args[1] - - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create an EC2 service client. - svc := ec2.New(sess) - - // Delete the key pair by name - _, err = svc.DeleteKeyPair(&ec2.DeleteKeyPairInput{ - KeyName: aws.String(pairName), - }) - if err != nil { - if aerr, ok := err.(awserr.Error); ok && aerr.Code() == "InvalidKeyPair.Duplicate" { - exitErrorf("Key pair %q does not exist.", pairName) - } - exitErrorf("Unable to delete key pair: %s, %v.", pairName, err) - } - - fmt.Printf("Successfully deleted %q key pair\n", pairName) + if len(os.Args) != 2 { + exitErrorf("pair name required\nUsage: %s key_pair_name", + filepath.Base(os.Args[0])) + } + pairName := os.Args[1] + + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create an EC2 service client. + svc := ec2.New(sess) + + // Delete the key pair by name + _, err = svc.DeleteKeyPair(&ec2.DeleteKeyPairInput{ + KeyName: aws.String(pairName), + }) + if err != nil { + if aerr, ok := err.(awserr.Error); ok && aerr.Code() == "InvalidKeyPair.Duplicate" { + exitErrorf("Key pair %q does not exist.", pairName) + } + exitErrorf("Unable to delete key pair: %s, %v.", pairName, err) + } + + fmt.Printf("Successfully deleted %q key pair\n", pairName) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/ec2/ec2_delete_security_group.go b/go/example_code/ec2/ec2_delete_security_group.go index 4fbab148fe7..98b7f556505 100644 --- a/go/example_code/ec2/ec2_delete_security_group.go +++ b/go/example_code/ec2/ec2_delete_security_group.go @@ -1,81 +1,60 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Deletes an EC2 security group.] -// snippet-keyword:[Amazon Elastic Compute Cloud] -// snippet-keyword:[DeleteSecurityGroup function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ec2] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" - "path/filepath" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" + "fmt" + "os" + "path/filepath" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ec2" ) // Deletes a security group by the ID passed in. // // Usage: -// go run ec2_delete_security_group.go group_id +// +// go run ec2_delete_security_group.go group_id func main() { - if len(os.Args) != 2 { - exitErrorf("Security Group ID required\nUsage: %s group_id", - filepath.Base(os.Args[0])) - } - groupID := os.Args[1] - - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create an EC2 service client. - svc := ec2.New(sess) - - // Delete the security group. - _, err = svc.DeleteSecurityGroup(&ec2.DeleteSecurityGroupInput{ - GroupId: aws.String(groupID), - }) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case "InvalidGroupId.Malformed": - fallthrough - case "InvalidGroup.NotFound": - exitErrorf("%s.", aerr.Message()) - } - } - exitErrorf("Unable to get descriptions for security groups, %v.", err) - } - - fmt.Printf("Successfully delete security group %q.\n", groupID) + if len(os.Args) != 2 { + exitErrorf("Security Group ID required\nUsage: %s group_id", + filepath.Base(os.Args[0])) + } + groupID := os.Args[1] + + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create an EC2 service client. + svc := ec2.New(sess) + + // Delete the security group. + _, err = svc.DeleteSecurityGroup(&ec2.DeleteSecurityGroupInput{ + GroupId: aws.String(groupID), + }) + if err != nil { + if aerr, ok := err.(awserr.Error); ok { + switch aerr.Code() { + case "InvalidGroupId.Malformed": + fallthrough + case "InvalidGroup.NotFound": + exitErrorf("%s.", aerr.Message()) + } + } + exitErrorf("Unable to get descriptions for security groups, %v.", err) + } + + fmt.Printf("Successfully delete security group %q.\n", groupID) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/ec2/ec2_describe_addresses.go b/go/example_code/ec2/ec2_describe_addresses.go index 09f546892bc..cb877f9dbe7 100644 --- a/go/example_code/ec2/ec2_describe_addresses.go +++ b/go/example_code/ec2/ec2_describe_addresses.go @@ -1,88 +1,67 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Describe your Amazon EC2 instance IP addresses.] -// snippet-keyword:[Amazon Elastic Compute Cloud] -// snippet-keyword:[DescribeAddresses function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ec2] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ec2" ) // Prints out the Elastic IP Addresses for the account's VPC. // // Usage: -// go run ec2_describe_addresses.go +// +// go run ec2_describe_addresses.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) - // Create an EC2 service client. - svc := ec2.New(sess) + // Create an EC2 service client. + svc := ec2.New(sess) - // Make the API request to EC2 filtering for the addresses in the - // account's VPC. - result, err := svc.DescribeAddresses(&ec2.DescribeAddressesInput{ - Filters: []*ec2.Filter{ - { - Name: aws.String("domain"), - Values: aws.StringSlice([]string{"vpc"}), - }, - }, - }) - if err != nil { - exitErrorf("Unable to elastic IP address, %v", err) - } + // Make the API request to EC2 filtering for the addresses in the + // account's VPC. + result, err := svc.DescribeAddresses(&ec2.DescribeAddressesInput{ + Filters: []*ec2.Filter{ + { + Name: aws.String("domain"), + Values: aws.StringSlice([]string{"vpc"}), + }, + }, + }) + if err != nil { + exitErrorf("Unable to elastic IP address, %v", err) + } - // Printout the IP addresses if there are any. - if len(result.Addresses) == 0 { - fmt.Printf("No elastic IPs for %s region\n", *svc.Config.Region) - } else { - fmt.Println("Elastic IPs") - for _, addr := range result.Addresses { - fmt.Println("*", fmtAddress(addr)) - } - } + // Printout the IP addresses if there are any. + if len(result.Addresses) == 0 { + fmt.Printf("No elastic IPs for %s region\n", *svc.Config.Region) + } else { + fmt.Println("Elastic IPs") + for _, addr := range result.Addresses { + fmt.Println("*", fmtAddress(addr)) + } + } } func fmtAddress(addr *ec2.Address) string { - out := fmt.Sprintf("IP: %s, allocation id: %s", - aws.StringValue(addr.PublicIp), aws.StringValue(addr.AllocationId)) - if addr.InstanceId != nil { - out += fmt.Sprintf(", instance-id: %s", *addr.InstanceId) - } - return out + out := fmt.Sprintf("IP: %s, allocation id: %s", + aws.StringValue(addr.PublicIp), aws.StringValue(addr.AllocationId)) + if addr.InstanceId != nil { + out += fmt.Sprintf(", instance-id: %s", *addr.InstanceId) + } + return out } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/ec2/ec2_describe_keypairs.go b/go/example_code/ec2/ec2_describe_keypairs.go index b83838e4d97..e14eb9278b6 100644 --- a/go/example_code/ec2/ec2_describe_keypairs.go +++ b/go/example_code/ec2/ec2_describe_keypairs.go @@ -1,66 +1,45 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Describes your Amazon EC2 key pairs.] -// snippet-keyword:[Amazon Elastic Compute Cloud] -// snippet-keyword:[DescribeKeyPairs function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ec2] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ec2" - "fmt" - "os" + "fmt" + "os" ) // Returns a list of Key Pairs stored in EC2.. // // Usage: -// go run ec2_describe_keypairs.go +// +// go run ec2_describe_keypairs.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create an EC2 service client. - svc := ec2.New(sess) - - // Returns a list of key pairs - result, err := svc.DescribeKeyPairs(nil) - if err != nil { - exitErrorf("Unable to get key pairs, %v", err) - } - - fmt.Println("Key Pairs:") - for _, pair := range result.KeyPairs { - fmt.Printf("%s: %s\n", *pair.KeyName, *pair.KeyFingerprint) - } + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create an EC2 service client. + svc := ec2.New(sess) + + // Returns a list of key pairs + result, err := svc.DescribeKeyPairs(nil) + if err != nil { + exitErrorf("Unable to get key pairs, %v", err) + } + + fmt.Println("Key Pairs:") + for _, pair := range result.KeyPairs { + fmt.Printf("%s: %s\n", *pair.KeyName, *pair.KeyFingerprint) + } } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/ec2/ec2_describe_security_groups.go b/go/example_code/ec2/ec2_describe_security_groups.go index 2a85c3df6d9..23c35271ba1 100644 --- a/go/example_code/ec2/ec2_describe_security_groups.go +++ b/go/example_code/ec2/ec2_describe_security_groups.go @@ -1,85 +1,64 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Describes your EC2 security groups.] -// snippet-keyword:[Amazon Elastic Compute Cloud] -// snippet-keyword:[DescribeSecurityGroups function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ec2] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" - "path/filepath" + "fmt" + "os" + "path/filepath" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ec2" ) // Describes the security groups by IDs that are passed into the CLI. Takes // a space separated list of group IDs as input. // // Usage: -// go run ec2_describe_security_groups.go groupId1 groupId2 ... +// +// go run ec2_describe_security_groups.go groupId1 groupId2 ... func main() { - if len(os.Args) < 2 { - exitErrorf("Security Group ID required\nUsage: %s group_id ...", - filepath.Base(os.Args[0])) - } - groupIds := os.Args[1:] + if len(os.Args) < 2 { + exitErrorf("Security Group ID required\nUsage: %s group_id ...", + filepath.Base(os.Args[0])) + } + groupIds := os.Args[1:] - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) - // Create an EC2 service client. - svc := ec2.New(sess) + // Create an EC2 service client. + svc := ec2.New(sess) - // Retrieve the security group descriptions - result, err := svc.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{ - GroupIds: aws.StringSlice(groupIds), - }) - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case "InvalidGroupId.Malformed": - fallthrough - case "InvalidGroup.NotFound": - exitErrorf("%s.", aerr.Message()) - } - } - exitErrorf("Unable to get descriptions for security groups, %v", err) - } + // Retrieve the security group descriptions + result, err := svc.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{ + GroupIds: aws.StringSlice(groupIds), + }) + if err != nil { + if aerr, ok := err.(awserr.Error); ok { + switch aerr.Code() { + case "InvalidGroupId.Malformed": + fallthrough + case "InvalidGroup.NotFound": + exitErrorf("%s.", aerr.Message()) + } + } + exitErrorf("Unable to get descriptions for security groups, %v", err) + } - fmt.Println("Security Group:") - for _, group := range result.SecurityGroups { - fmt.Println(group) - } + fmt.Println("Security Group:") + for _, group := range result.SecurityGroups { + fmt.Println(group) + } } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/ec2/ec2_release_address.go b/go/example_code/ec2/ec2_release_address.go index b33f9ab8fb2..ea1a1a8ae7f 100644 --- a/go/example_code/ec2/ec2_release_address.go +++ b/go/example_code/ec2/ec2_release_address.go @@ -1,78 +1,57 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Releases an Amazon EC2 instance IP address.] -// snippet-keyword:[Amazon Elastic Compute Cloud] -// snippet-keyword:[ReleaseAddress function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ec2] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" - "path/filepath" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" + "fmt" + "os" + "path/filepath" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ec2" ) // Releases an Elastic IP address allocation ID. If the address is associated // with a EC2 instance the association will be removed. // // Usage: -// go run ec2_release_address.go ALLOCATION_ID +// +// go run ec2_release_address.go ALLOCATION_ID func main() { - if len(os.Args) != 2 { - exitErrorf("allocation ID required\nUsage: %s allocation_id", - filepath.Base(os.Args[0])) - } - allocationID := os.Args[1] - - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create an EC2 service client. - svc := ec2.New(sess) - - // Attempt to release the Elastic IP address. - _, err = svc.ReleaseAddress(&ec2.ReleaseAddressInput{ - AllocationId: aws.String(allocationID), - }) - if err != nil { - if aerr, ok := err.(awserr.Error); ok && aerr.Code() == "InvalidAllocationID.NotFound" { - exitErrorf("Allocation ID %s does not exist", allocationID) - } - exitErrorf("Unable to release IP address for allocation %s, %v", - allocationID, err) - } - - fmt.Printf("Successfully released allocation ID %s\n", allocationID) + if len(os.Args) != 2 { + exitErrorf("allocation ID required\nUsage: %s allocation_id", + filepath.Base(os.Args[0])) + } + allocationID := os.Args[1] + + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create an EC2 service client. + svc := ec2.New(sess) + + // Attempt to release the Elastic IP address. + _, err = svc.ReleaseAddress(&ec2.ReleaseAddressInput{ + AllocationId: aws.String(allocationID), + }) + if err != nil { + if aerr, ok := err.(awserr.Error); ok && aerr.Code() == "InvalidAllocationID.NotFound" { + exitErrorf("Allocation ID %s does not exist", allocationID) + } + exitErrorf("Unable to release IP address for allocation %s, %v", + allocationID, err) + } + + fmt.Printf("Successfully released allocation ID %s\n", allocationID) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/ec2/get_console_output.go b/go/example_code/ec2/get_console_output.go index 305160c7ef3..db6caf8e273 100644 --- a/go/example_code/ec2/get_console_output.go +++ b/go/example_code/ec2/get_console_output.go @@ -1,62 +1,50 @@ -// snippet-sourcetype:[full-example] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/base64" - "fmt" - "os" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" + "encoding/base64" + "fmt" + "os" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/endpoints" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ec2" ) func decodeOutputb64(encoded string) string { - decoded, err := base64.StdEncoding.DecodeString(encoded) - if err != nil { - fmt.Println("Error", err) - return "" - } + decoded, err := base64.StdEncoding.DecodeString(encoded) + if err != nil { + fmt.Println("Error", err) + return "" + } - return string(decoded) + return string(decoded) } func main() { - // Create new EC2 service - ec2Svc := ec2.New(session.Must(session.NewSession(&aws.Config{ - Region: aws.String(endpoints.UsWest2RegionID), - }))) - - if len(os.Args) == 1 { - fmt.Printf("Usage %s \n", os.Args[0]) - os.Exit(1) - } - - instanceId := os.Args[1] - - // Call EC2 GetConsoleOutput API on the given instance according - // https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.GetConsoleOutput - - input := ec2.GetConsoleOutputInput{InstanceId: aws.String(instanceId)} - json, err := ec2Svc.GetConsoleOutput(&input) - if err != nil { - fmt.Println("Error", err) - } else { - fmt.Println(decodeOutputb64(*json.Output)) - } + // Create new EC2 service + ec2Svc := ec2.New(session.Must(session.NewSession(&aws.Config{ + Region: aws.String(endpoints.UsWest2RegionID), + }))) + + if len(os.Args) == 1 { + fmt.Printf("Usage %s \n", os.Args[0]) + os.Exit(1) + } + + instanceId := os.Args[1] + + // Call EC2 GetConsoleOutput API on the given instance according + // https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#EC2.GetConsoleOutput + + input := ec2.GetConsoleOutputInput{InstanceId: aws.String(instanceId)} + json, err := ec2Svc.GetConsoleOutput(&input) + if err != nil { + fmt.Println("Error", err) + } else { + fmt.Println(decodeOutputb64(*json.Output)) + } } diff --git a/go/example_code/ec2/monitoring_instances.go b/go/example_code/ec2/monitoring_instances.go index 1b6aac6975e..c9a7241d123 100644 --- a/go/example_code/ec2/monitoring_instances.go +++ b/go/example_code/ec2/monitoring_instances.go @@ -1,101 +1,78 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Manages Amazon EC2 instance monitoring.] -// snippet-keyword:[Amazon Elastic Compute Cloud] -// snippet-keyword:[MonitorInstances function] -// snippet-keyword:[UnmonitorInstances function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ec2] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ec2" ) // Usage: // go run main.go -// * state can either be ON or OFF +// - state can either be ON or OFF func main() { - // Load session from shared config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + // Load session from shared config + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - // Create new EC2 client - svc := ec2.New(sess) + // Create new EC2 client + svc := ec2.New(sess) - // Turn monitoring on - if os.Args[1] == "ON" { - // We set DryRun to true to check to see if the instance exists and we have the - // necessary permissions to monitor the instance. - input := &ec2.MonitorInstancesInput{ - InstanceIds: []*string{ - aws.String(os.Args[2]), - }, - DryRun: aws.Bool(true), - } - result, err := svc.MonitorInstances(input) - awsErr, ok := err.(awserr.Error) + // Turn monitoring on + if os.Args[1] == "ON" { + // We set DryRun to true to check to see if the instance exists and we have the + // necessary permissions to monitor the instance. + input := &ec2.MonitorInstancesInput{ + InstanceIds: []*string{ + aws.String(os.Args[2]), + }, + DryRun: aws.Bool(true), + } + result, err := svc.MonitorInstances(input) + awsErr, ok := err.(awserr.Error) - // If the error code is `DryRunOperation` it means we have the necessary - // permissions to monitor this instance - if ok && awsErr.Code() == "DryRunOperation" { - // Let's now set dry run to be false. This will allow us to turn monitoring on - input.DryRun = aws.Bool(false) - result, err = svc.MonitorInstances(input) - if err != nil { - fmt.Println("Error", err) - } else { - fmt.Println("Success", result.InstanceMonitorings) - } - } else { - // This could be due to a lack of permissions - fmt.Println("Error", err) - } - } else if os.Args[1] == "OFF" { // Turn monitoring off - input := &ec2.UnmonitorInstancesInput{ - InstanceIds: []*string{ - aws.String(os.Args[2]), - }, - DryRun: aws.Bool(true), - } - result, err := svc.UnmonitorInstances(input) - awsErr, ok := err.(awserr.Error) - if ok && awsErr.Code() == "DryRunOperation" { - input.DryRun = aws.Bool(false) - result, err = svc.UnmonitorInstances(input) - if err != nil { - fmt.Println("Error", err) - } else { - fmt.Println("Success", result.InstanceMonitorings) - } - } else { - fmt.Println("Error", err) - } - } + // If the error code is `DryRunOperation` it means we have the necessary + // permissions to monitor this instance + if ok && awsErr.Code() == "DryRunOperation" { + // Let's now set dry run to be false. This will allow us to turn monitoring on + input.DryRun = aws.Bool(false) + result, err = svc.MonitorInstances(input) + if err != nil { + fmt.Println("Error", err) + } else { + fmt.Println("Success", result.InstanceMonitorings) + } + } else { + // This could be due to a lack of permissions + fmt.Println("Error", err) + } + } else if os.Args[1] == "OFF" { // Turn monitoring off + input := &ec2.UnmonitorInstancesInput{ + InstanceIds: []*string{ + aws.String(os.Args[2]), + }, + DryRun: aws.Bool(true), + } + result, err := svc.UnmonitorInstances(input) + awsErr, ok := err.(awserr.Error) + if ok && awsErr.Code() == "DryRunOperation" { + input.DryRun = aws.Bool(false) + result, err = svc.UnmonitorInstances(input) + if err != nil { + fmt.Println("Error", err) + } else { + fmt.Println("Success", result.InstanceMonitorings) + } + } else { + fmt.Println("Error", err) + } + } } diff --git a/go/example_code/ec2/reboot_instances.go b/go/example_code/ec2/reboot_instances.go index 9abdaf4b4de..09a1cc81c04 100644 --- a/go/example_code/ec2/reboot_instances.go +++ b/go/example_code/ec2/reboot_instances.go @@ -1,74 +1,52 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Reboots an Amazon EC2 instance.] -// snippet-keyword:[Amazon Elastic Compute Cloud] -// snippet-keyword:[RebootInstances function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ec2] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ec2" ) // Usage: // go run main.go func main() { - // Load session from shared config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create new EC2 client - svc := ec2.New(sess) - - // We set DryRun to true to check to see if the instance exists and we have the - // necessary permissions to monitor the instance. - input := &ec2.RebootInstancesInput{ - InstanceIds: []*string{ - aws.String(os.Args[1]), - }, - DryRun: aws.Bool(true), - } - result, err := svc.RebootInstances(input) - awsErr, ok := err.(awserr.Error) - - // If the error code is `DryRunOperation` it means we have the necessary - // permissions to Start this instance - if ok && awsErr.Code() == "DryRunOperation" { - // Let's now set dry run to be false. This will allow us to reboot the instances - input.DryRun = aws.Bool(false) - result, err = svc.RebootInstances(input) - if err != nil { - fmt.Println("Error", err) - } else { - fmt.Println("Success", result) - } - } else { // This could be due to a lack of permissions - fmt.Println("Error", err) - } + // Load session from shared config + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create new EC2 client + svc := ec2.New(sess) + + // We set DryRun to true to check to see if the instance exists and we have the + // necessary permissions to monitor the instance. + input := &ec2.RebootInstancesInput{ + InstanceIds: []*string{ + aws.String(os.Args[1]), + }, + DryRun: aws.Bool(true), + } + result, err := svc.RebootInstances(input) + awsErr, ok := err.(awserr.Error) + + // If the error code is `DryRunOperation` it means we have the necessary + // permissions to Start this instance + if ok && awsErr.Code() == "DryRunOperation" { + // Let's now set dry run to be false. This will allow us to reboot the instances + input.DryRun = aws.Bool(false) + result, err = svc.RebootInstances(input) + if err != nil { + fmt.Println("Error", err) + } else { + fmt.Println("Success", result) + } + } else { // This could be due to a lack of permissions + fmt.Println("Error", err) + } } diff --git a/go/example_code/ec2/regions_and_availability.go b/go/example_code/ec2/regions_and_availability.go index a73d6d1ebe2..8e05c559501 100644 --- a/go/example_code/ec2/regions_and_availability.go +++ b/go/example_code/ec2/regions_and_availability.go @@ -1,64 +1,41 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Retrieves details about AWS Regions and Availability Zones.] -// snippet-keyword:[Amazon Elastic Compute Cloud] -// snippet-keyword:[DescribeAvailabilityZones function] -// snippet-keyword:[DescribeRegions function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ec2] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ec2" ) // Usage: // go run main.go func main() { - // Load session from shared config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create new EC2 client - svc := ec2.New(sess) - - // Retrieves all regions/endpoints that work with EC2 - resultRegions, err := svc.DescribeRegions(nil) - if err != nil { - fmt.Println("Error", err) - return - } - - fmt.Println("Success", resultRegions.Regions) - - // Retrieves availability zones only for region of the ec2 service object - resultAvalZones, err := svc.DescribeAvailabilityZones(nil) - if err != nil { - fmt.Println("Error", err) - return - } - - fmt.Println("Success", resultAvalZones.AvailabilityZones) + // Load session from shared config + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create new EC2 client + svc := ec2.New(sess) + + // Retrieves all regions/endpoints that work with EC2 + resultRegions, err := svc.DescribeRegions(nil) + if err != nil { + fmt.Println("Error", err) + return + } + + fmt.Println("Success", resultRegions.Regions) + + // Retrieves availability zones only for region of the ec2 service object + resultAvalZones, err := svc.DescribeAvailabilityZones(nil) + if err != nil { + fmt.Println("Error", err) + return + } + + fmt.Println("Success", resultAvalZones.AvailabilityZones) } diff --git a/go/example_code/ec2/start_stop_instances.go b/go/example_code/ec2/start_stop_instances.go index 5982fd980ac..362f6af1b54 100644 --- a/go/example_code/ec2/start_stop_instances.go +++ b/go/example_code/ec2/start_stop_instances.go @@ -1,99 +1,76 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Starts and stops an Amazon EC2 instance.] -// snippet-keyword:[Amazon Elastic Compute Cloud] -// snippet-keyword:[StartInstances function] -// snippet-keyword:[StopInstances function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ec2] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ec2" ) // Usage: // go run main.go -// * state can either be START or STOP +// - state can either be START or STOP func main() { - // Load session from shared config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + // Load session from shared config + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - // Create new EC2 client - svc := ec2.New(sess) + // Create new EC2 client + svc := ec2.New(sess) - // Turn monitoring on - if os.Args[1] == "START" { - // We set DryRun to true to check to see if the instance exists and we have the - // necessary permissions to monitor the instance. - input := &ec2.StartInstancesInput{ - InstanceIds: []*string{ - aws.String(os.Args[2]), - }, - DryRun: aws.Bool(true), - } - result, err := svc.StartInstances(input) - awsErr, ok := err.(awserr.Error) + // Turn monitoring on + if os.Args[1] == "START" { + // We set DryRun to true to check to see if the instance exists and we have the + // necessary permissions to monitor the instance. + input := &ec2.StartInstancesInput{ + InstanceIds: []*string{ + aws.String(os.Args[2]), + }, + DryRun: aws.Bool(true), + } + result, err := svc.StartInstances(input) + awsErr, ok := err.(awserr.Error) - // If the error code is `DryRunOperation` it means we have the necessary - // permissions to Start this instance - if ok && awsErr.Code() == "DryRunOperation" { - // Let's now set dry run to be false. This will allow us to start the instances - input.DryRun = aws.Bool(false) - result, err = svc.StartInstances(input) - if err != nil { - fmt.Println("Error", err) - } else { - fmt.Println("Success", result.StartingInstances) - } - } else { // This could be due to a lack of permissions - fmt.Println("Error", err) - } - } else if os.Args[1] == "STOP" { // Turn instances off - input := &ec2.StopInstancesInput{ - InstanceIds: []*string{ - aws.String(os.Args[2]), - }, - DryRun: aws.Bool(true), - } - result, err := svc.StopInstances(input) - awsErr, ok := err.(awserr.Error) - if ok && awsErr.Code() == "DryRunOperation" { - input.DryRun = aws.Bool(false) - result, err = svc.StopInstances(input) - if err != nil { - fmt.Println("Error", err) - } else { - fmt.Println("Success", result.StoppingInstances) - } - } else { - fmt.Println("Error", err) - } - } + // If the error code is `DryRunOperation` it means we have the necessary + // permissions to Start this instance + if ok && awsErr.Code() == "DryRunOperation" { + // Let's now set dry run to be false. This will allow us to start the instances + input.DryRun = aws.Bool(false) + result, err = svc.StartInstances(input) + if err != nil { + fmt.Println("Error", err) + } else { + fmt.Println("Success", result.StartingInstances) + } + } else { // This could be due to a lack of permissions + fmt.Println("Error", err) + } + } else if os.Args[1] == "STOP" { // Turn instances off + input := &ec2.StopInstancesInput{ + InstanceIds: []*string{ + aws.String(os.Args[2]), + }, + DryRun: aws.Bool(true), + } + result, err := svc.StopInstances(input) + awsErr, ok := err.(awserr.Error) + if ok && awsErr.Code() == "DryRunOperation" { + input.DryRun = aws.Bool(false) + result, err = svc.StopInstances(input) + if err != nil { + fmt.Println("Error", err) + } else { + fmt.Println("Success", result.StoppingInstances) + } + } else { + fmt.Println("Error", err) + } + } } diff --git a/go/example_code/extending_sdk/addHeader.go b/go/example_code/extending_sdk/addHeader.go index 081f6bf5bdc..acdf0139a4c 100644 --- a/go/example_code/extending_sdk/addHeader.go +++ b/go/example_code/extending_sdk/addHeader.go @@ -1,63 +1,40 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Adds a custom header to a DynamoDB table.] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Handlers.Send.PushFront function] -// snippet-keyword:[ListTables function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[dynamodb] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/dynamodb" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/dynamodb" - "fmt" - "os" + "fmt" + "os" ) func main() { - // Initialize a session in us-west-2 that the SDK will use to load credentials - // from the shared config file. (~/.aws/credentials). - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - if err != nil { - fmt.Println("Error getting session:") - fmt.Println(err) - os.Exit(1) - } - - // Create DynamoDB client - // and expose HTTP requests/responses - svc := dynamodb.New(sess, aws.NewConfig().WithLogLevel(aws.LogDebugWithHTTPBody)) - - // Add "CustomHeader" header with value of 10 - svc.Handlers.Send.PushFront(func(r *request.Request) { - r.HTTPRequest.Header.Set("CustomHeader", fmt.Sprintf("%d", 10)) - }) - - // Call ListTables just to see HTTP request/response - // The request should have the CustomHeader set to 10 - _, _ = svc.ListTables(&dynamodb.ListTablesInput{}) + // Initialize a session in us-west-2 that the SDK will use to load credentials + // from the shared config file. (~/.aws/credentials). + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + if err != nil { + fmt.Println("Error getting session:") + fmt.Println(err) + os.Exit(1) + } + + // Create DynamoDB client + // and expose HTTP requests/responses + svc := dynamodb.New(sess, aws.NewConfig().WithLogLevel(aws.LogDebugWithHTTPBody)) + + // Add "CustomHeader" header with value of 10 + svc.Handlers.Send.PushFront(func(r *request.Request) { + r.HTTPRequest.Header.Set("CustomHeader", fmt.Sprintf("%d", 10)) + }) + + // Call ListTables just to see HTTP request/response + // The request should have the CustomHeader set to 10 + _, _ = svc.ListTables(&dynamodb.ListTablesInput{}) } diff --git a/go/example_code/extending_sdk/addTags.go b/go/example_code/extending_sdk/addTags.go index 7454216b8a6..4eaddc508af 100644 --- a/go/example_code/extending_sdk/addTags.go +++ b/go/example_code/extending_sdk/addTags.go @@ -1,112 +1,91 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[addTags.go adds tags to an S3 bucket and displays its tags.] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[GetBucketTagging function] -// snippet-keyword:[PutBucketTagging function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-03-22] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ -//snippet-start:[extending.go.add_tags] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[extending.go.add_tags] package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" - "fmt" + "fmt" ) // Tag S3 bucket MyBucket with cost center tag "123456" and stack tag "MyTestStack". // // See: -// http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html +// +// http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html func main() { - // Pre-defined values - bucket := "MyBucket" - tagName1 := "Cost Center" - tagValue1 := "123456" - tagName2 := "Stack" - tagValue2 := "MyTestStack" + // Pre-defined values + bucket := "MyBucket" + tagName1 := "Cost Center" + tagValue1 := "123456" + tagName2 := "Stack" + tagValue2 := "MyTestStack" - // Initialize a session in us-west-2 that the SDK will use to load credentials - // from the shared credentials file. (~/.aws/credentials). - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - if err != nil { - fmt.Println(err.Error()) - return - } + // Initialize a session in us-west-2 that the SDK will use to load credentials + // from the shared credentials file. (~/.aws/credentials). + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + if err != nil { + fmt.Println(err.Error()) + return + } - // Create S3 service client - svc := s3.New(sess) + // Create S3 service client + svc := s3.New(sess) - // Create input for PutBucket method - putInput := &s3.PutBucketTaggingInput{ - Bucket: aws.String(bucket), - Tagging: &s3.Tagging{ - TagSet: []*s3.Tag{ - { - Key: aws.String(tagName1), - Value: aws.String(tagValue1), - }, - { - Key: aws.String(tagName2), - Value: aws.String(tagValue2), - }, - }, - }, - } + // Create input for PutBucket method + putInput := &s3.PutBucketTaggingInput{ + Bucket: aws.String(bucket), + Tagging: &s3.Tagging{ + TagSet: []*s3.Tag{ + { + Key: aws.String(tagName1), + Value: aws.String(tagValue1), + }, + { + Key: aws.String(tagName2), + Value: aws.String(tagValue2), + }, + }, + }, + } - _, err = svc.PutBucketTagging(putInput) - if err != nil { - fmt.Println(err.Error()) - return - } + _, err = svc.PutBucketTagging(putInput) + if err != nil { + fmt.Println(err.Error()) + return + } - // Now show the tags - // Create input for GetBucket method - getInput := &s3.GetBucketTaggingInput{ - Bucket: aws.String(bucket), - } + // Now show the tags + // Create input for GetBucket method + getInput := &s3.GetBucketTaggingInput{ + Bucket: aws.String(bucket), + } - result, err := svc.GetBucketTagging(getInput) - if err != nil { - fmt.Println(err.Error()) - return - } + result, err := svc.GetBucketTagging(getInput) + if err != nil { + fmt.Println(err.Error()) + return + } - numTags := len(result.TagSet) + numTags := len(result.TagSet) - if numTags > 0 { - fmt.Println("Found", numTags, "Tag(s):") - fmt.Println("") + if numTags > 0 { + fmt.Println("Found", numTags, "Tag(s):") + fmt.Println("") - for _, t := range result.TagSet { - fmt.Println(" Key: ", *t.Key) - fmt.Println(" Value:", *t.Value) - fmt.Println("") - } - } else { - fmt.Println("Did not find any tags") - } + for _, t := range result.TagSet { + fmt.Println(" Key: ", *t.Key) + fmt.Println(" Value:", *t.Value) + fmt.Println("") + } + } else { + fmt.Println("Did not find any tags") + } } -//snippet-end:[extending.go.add_tags] \ No newline at end of file + +// snippet-end:[extending.go.add_tags] diff --git a/go/example_code/extending_sdk/ecs/update_deployment_with_setters.go b/go/example_code/extending_sdk/ecs/update_deployment_with_setters.go index d8f1f266797..b3feb1eea3d 100644 --- a/go/example_code/extending_sdk/ecs/update_deployment_with_setters.go +++ b/go/example_code/extending_sdk/ecs/update_deployment_with_setters.go @@ -1,56 +1,36 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[update_deployment_with_setters.go uses chainable setters on nested fields in an API operation request.] -// snippet-keyword:[Extending the SDK] -// snippet-keyword:[UpdateService function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[aws-go-sdk] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-03-22] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ -//snippet-start:[s3.go.update_deployment] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[s3.go.update_deployment] package main import ( - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ecs" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ecs" - "fmt" + "fmt" ) func main() { - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := ecs.New(sess) - - //snippet-start:[s3.go.update_deployment.call] - resp, err := svc.UpdateService((&ecs.UpdateServiceInput{}). - SetService("myService"). - SetDeploymentConfiguration((&ecs.DeploymentConfiguration{}). - SetMinimumHealthyPercent(80), - ), - ) - //snippet-end:[s3.go.update_deployment.call] - if err != nil { - fmt.Println("Error calling UpdateService:") - fmt.Println(err.Error()) - } else { - fmt.Println(resp) - } + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := ecs.New(sess) + + // snippet-start:[s3.go.update_deployment.call] + resp, err := svc.UpdateService((&ecs.UpdateServiceInput{}). + SetService("myService"). + SetDeploymentConfiguration((&ecs.DeploymentConfiguration{}). + SetMinimumHealthyPercent(80), + ), + ) + // snippet-end:[s3.go.update_deployment.call] + if err != nil { + fmt.Println("Error calling UpdateService:") + fmt.Println(err.Error()) + } else { + fmt.Println(resp) + } } -//snippet-end:[s3.go.update_deployment] + +// snippet-end:[s3.go.update_deployment] diff --git a/go/example_code/extending_sdk/handleServiceErrorCodes.go b/go/example_code/extending_sdk/handleServiceErrorCodes.go index a2df1316844..32ee3893109 100644 --- a/go/example_code/extending_sdk/handleServiceErrorCodes.go +++ b/go/example_code/extending_sdk/handleServiceErrorCodes.go @@ -1,43 +1,22 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Handling Errors in the AWS SDK for Go.] -// snippet-keyword:[Error handling] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[sdk-for-go] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" - "path/filepath" + "fmt" + "os" + "path/filepath" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } // Will make a request to S3 for the contents of an object. If the request @@ -51,38 +30,38 @@ func exitErrorf(msg string, args ...interface{}) { // // Usage: handleServiceErrorCodes func main() { - if len(os.Args) < 3 { - exitErrorf("Usage: %s ", filepath.Base(os.Args[0])) - } - sess := session.Must(session.NewSession()) + if len(os.Args) < 3 { + exitErrorf("Usage: %s ", filepath.Base(os.Args[0])) + } + sess := session.Must(session.NewSession()) - svc := s3.New(sess) - resp, err := svc.GetObject(&s3.GetObjectInput{ - Bucket: aws.String(os.Args[1]), - Key: aws.String(os.Args[2]), - }) + svc := s3.New(sess) + resp, err := svc.GetObject(&s3.GetObjectInput{ + Bucket: aws.String(os.Args[1]), + Key: aws.String(os.Args[2]), + }) - if err != nil { - // Casting to the awserr.Error type will allow you to inspect the error - // code returned by the service in code. The error code can be used - // to switch on context specific functionality. In this case a context - // specific error message is printed to the user based on the bucket - // and key existing. - // - // For information on other S3 API error codes see: - // http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case s3.ErrCodeNoSuchBucket: - exitErrorf("bucket %s does not exist", os.Args[1]) - case s3.ErrCodeNoSuchKey: - exitErrorf("object with key %s does not exist in bucket %s", os.Args[2], os.Args[1]) - } - } - exitErrorf("unknown error occurred, %v", err) - } - defer resp.Body.Close() + if err != nil { + // Casting to the awserr.Error type will allow you to inspect the error + // code returned by the service in code. The error code can be used + // to switch on context specific functionality. In this case a context + // specific error message is printed to the user based on the bucket + // and key existing. + // + // For information on other S3 API error codes see: + // http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html + if aerr, ok := err.(awserr.Error); ok { + switch aerr.Code() { + case s3.ErrCodeNoSuchBucket: + exitErrorf("bucket %s does not exist", os.Args[1]) + case s3.ErrCodeNoSuchKey: + exitErrorf("object with key %s does not exist in bucket %s", os.Args[2], os.Args[1]) + } + } + exitErrorf("unknown error occurred, %v", err) + } + defer resp.Body.Close() - fmt.Printf("s3://%s/%s exists. size: %d\n", os.Args[1], os.Args[2], - aws.Int64Value(resp.ContentLength)) + fmt.Printf("s3://%s/%s exists. size: %d\n", os.Args[1], os.Args[2], + aws.Int64Value(resp.ContentLength)) } diff --git a/go/example_code/extending_sdk/request_context.go b/go/example_code/extending_sdk/request_context.go index d1707eccc35..fc77e52f4e0 100644 --- a/go/example_code/extending_sdk/request_context.go +++ b/go/example_code/extending_sdk/request_context.go @@ -1,74 +1,54 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[request_context.go shows how to use context.Context with SDK requests.] -// snippet-keyword:[Extending the SDK] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[aws-go-sdk] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-03-14] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" - "context" - "fmt" - "time" + "context" + "fmt" + "time" ) func main() { - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := sqs.New(sess) - - // URL to our queue - qURL := "QueueURL" - - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - // SQS ReceiveMessage - params := &sqs.ReceiveMessageInput{ - AttributeNames: []*string{ - aws.String(sqs.MessageSystemAttributeNameSentTimestamp), - }, - MessageAttributeNames: []*string{ - aws.String(sqs.QueueAttributeNameAll), - }, - QueueUrl: &qURL, - MaxNumberOfMessages: aws.Int64(1), - VisibilityTimeout: aws.Int64(20), // 20 seconds - WaitTimeSeconds: aws.Int64(0), - } - - //snippet-start:[extending.go.receive_message_request] - req, resp := svc.ReceiveMessageRequest(params) - req.HTTPRequest = req.HTTPRequest.WithContext(ctx) - - err := req.Send() - if err != nil { - fmt.Println("Got error receiving message:") - fmt.Println(err.Error()) - } else { - fmt.Println(resp) - } - //snippet-end:[extending.go.receive_message_request] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := sqs.New(sess) + + // URL to our queue + qURL := "QueueURL" + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + // SQS ReceiveMessage + params := &sqs.ReceiveMessageInput{ + AttributeNames: []*string{ + aws.String(sqs.MessageSystemAttributeNameSentTimestamp), + }, + MessageAttributeNames: []*string{ + aws.String(sqs.QueueAttributeNameAll), + }, + QueueUrl: &qURL, + MaxNumberOfMessages: aws.Int64(1), + VisibilityTimeout: aws.Int64(20), // 20 seconds + WaitTimeSeconds: aws.Int64(0), + } + + // snippet-start:[extending.go.receive_message_request] + req, resp := svc.ReceiveMessageRequest(params) + req.HTTPRequest = req.HTTPRequest.WithContext(ctx) + + err := req.Send() + if err != nil { + fmt.Println("Got error receiving message:") + fmt.Println(err.Error()) + } else { + fmt.Println(resp) + } + // snippet-end:[extending.go.receive_message_request] } diff --git a/go/example_code/glacier/create_vault.go b/go/example_code/glacier/create_vault.go index 4384c35f66a..3fa3a1e2ad5 100644 --- a/go/example_code/glacier/create_vault.go +++ b/go/example_code/glacier/create_vault.go @@ -1,57 +1,35 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Creates a Glacier vault.] -// snippet-keyword:[Amazon Glacier] -// snippet-keyword:[CreateVault function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[glacier] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-03-14] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "log" + "log" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/glacier" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/glacier" ) func main() { - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create Glacier client in default region - svc := glacier.New(sess) - - // start snippet - _, err := svc.CreateVault(&glacier.CreateVaultInput{ - VaultName: aws.String("YOUR_VAULT_NAME"), - }) - if err != nil { - log.Println(err) - return - } - - log.Println("Created vault!") - // end snippet + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create Glacier client in default region + svc := glacier.New(sess) + + // start snippet + _, err := svc.CreateVault(&glacier.CreateVaultInput{ + VaultName: aws.String("YOUR_VAULT_NAME"), + }) + if err != nil { + log.Println(err) + return + } + + log.Println("Created vault!") + // end snippet } diff --git a/go/example_code/glacier/upload_archive.go b/go/example_code/glacier/upload_archive.go index 8737420c80b..af6f94b8219 100644 --- a/go/example_code/glacier/upload_archive.go +++ b/go/example_code/glacier/upload_archive.go @@ -1,60 +1,38 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Upload a single reader object as an entire archive.] -// snippet-keyword:[Amazon Glacier] -// snippet-keyword:[UploadArchive function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[glacier] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-03-14] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "bytes" - "log" + "bytes" + "log" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/glacier" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/glacier" ) func main() { - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create Glacier client in default region - svc := glacier.New(sess) - - // start snippet - vaultName := "YOUR_VAULT_NAME" - - result, err := svc.UploadArchive(&glacier.UploadArchiveInput{ - VaultName: &vaultName, - Body: bytes.NewReader(make([]byte, 2*1024*1024)), // 2 MB buffer - }) - if err != nil { - log.Println("Error uploading archive.", err) - return - } - - log.Println("Uploaded to archive", *result.ArchiveId) - // end snippet + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create Glacier client in default region + svc := glacier.New(sess) + + // start snippet + vaultName := "YOUR_VAULT_NAME" + + result, err := svc.UploadArchive(&glacier.UploadArchiveInput{ + VaultName: &vaultName, + Body: bytes.NewReader(make([]byte, 2*1024*1024)), // 2 MB buffer + }) + if err != nil { + log.Println("Error uploading archive.", err) + return + } + + log.Println("Uploaded to archive", *result.ArchiveId) + // end snippet } diff --git a/go/example_code/iam/IamListAdmins.go b/go/example_code/iam/IamListAdmins.go index c68c87e6238..2c220c61953 100644 --- a/go/example_code/iam/IamListAdmins.go +++ b/go/example_code/iam/IamListAdmins.go @@ -1,208 +1,182 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Lists the IAM users that have adminstrator privileges.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[ListGroupPolicies function] -// snippet-keyword:[ListAttachedGroupPolicies function] -// snippet-keyword:[ListGroupsForUser function] -// snippet-keyword:[GetAccountAuthorizationDetails function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" - "fmt" - "os" + "fmt" + "os" ) func UserPolicyHasAdmin(user *iam.UserDetail, admin string) bool { - for _, policy := range user.UserPolicyList { - if *policy.PolicyName == admin { - return true - } - } + for _, policy := range user.UserPolicyList { + if *policy.PolicyName == admin { + return true + } + } - return false + return false } func AttachedUserPolicyHasAdmin(user *iam.UserDetail, admin string) bool { - for _, policy := range user.AttachedManagedPolicies { - if *policy.PolicyName == admin { - return true - } - } + for _, policy := range user.AttachedManagedPolicies { + if *policy.PolicyName == admin { + return true + } + } - return false + return false } func GroupPolicyHasAdmin(svc *iam.IAM, group *iam.Group, admin string) bool { - input := &iam.ListGroupPoliciesInput{ - GroupName: group.GroupName, - } - - result, err := svc.ListGroupPolicies(input) - if err != nil { - fmt.Println("Got error calling ListGroupPolicies for group", group.GroupName) - } - - // Wade through policies - for _, policyName := range result.PolicyNames { - if - *policyName == admin { - return true - } - } - - return false + input := &iam.ListGroupPoliciesInput{ + GroupName: group.GroupName, + } + + result, err := svc.ListGroupPolicies(input) + if err != nil { + fmt.Println("Got error calling ListGroupPolicies for group", group.GroupName) + } + + // Wade through policies + for _, policyName := range result.PolicyNames { + if *policyName == admin { + return true + } + } + + return false } func AttachedGroupPolicyHasAdmin(svc *iam.IAM, group *iam.Group, admin string) bool { - input := &iam.ListAttachedGroupPoliciesInput{GroupName: group.GroupName} - result, err := svc.ListAttachedGroupPolicies(input) - if err != nil { - fmt.Println("Got error getting attached group policies:") - fmt.Println(err.Error()) - os.Exit(1) - } - - for _, policy := range result.AttachedPolicies { - if *policy.PolicyName == admin { - return true - } - } - - return false + input := &iam.ListAttachedGroupPoliciesInput{GroupName: group.GroupName} + result, err := svc.ListAttachedGroupPolicies(input) + if err != nil { + fmt.Println("Got error getting attached group policies:") + fmt.Println(err.Error()) + os.Exit(1) + } + + for _, policy := range result.AttachedPolicies { + if *policy.PolicyName == admin { + return true + } + } + + return false } func UsersGroupsHaveAdmin(svc *iam.IAM, user *iam.UserDetail, admin string) bool { - input := &iam.ListGroupsForUserInput{UserName: user.UserName} - result, err := svc.ListGroupsForUser(input) - if err != nil { - fmt.Println("Got error getting groups for user:") - fmt.Println(err.Error()) - os.Exit(1) - } + input := &iam.ListGroupsForUserInput{UserName: user.UserName} + result, err := svc.ListGroupsForUser(input) + if err != nil { + fmt.Println("Got error getting groups for user:") + fmt.Println(err.Error()) + os.Exit(1) + } - for _, group := range result.Groups { - groupPolicyHasAdmin := GroupPolicyHasAdmin(svc, group, admin) + for _, group := range result.Groups { + groupPolicyHasAdmin := GroupPolicyHasAdmin(svc, group, admin) - if groupPolicyHasAdmin { - return true - } + if groupPolicyHasAdmin { + return true + } - attachedGroupPolicyHasAdmin := AttachedGroupPolicyHasAdmin(svc, group, admin) + attachedGroupPolicyHasAdmin := AttachedGroupPolicyHasAdmin(svc, group, admin) - if attachedGroupPolicyHasAdmin { - return true - } - } + if attachedGroupPolicyHasAdmin { + return true + } + } - return false + return false } func IsUserAdmin(svc *iam.IAM, user *iam.UserDetail, admin string) bool { - // Check policy, attached policy, and groups (policy and attached policy) - policyHasAdmin := UserPolicyHasAdmin(user, admin) - if policyHasAdmin { - return true - } - - attachedPolicyHasAdmin := AttachedUserPolicyHasAdmin(user, admin) - if attachedPolicyHasAdmin { - return true - } - - userGroupsHaveAdmin := UsersGroupsHaveAdmin(svc, user, admin) - if userGroupsHaveAdmin { - return true - } - - return false + // Check policy, attached policy, and groups (policy and attached policy) + policyHasAdmin := UserPolicyHasAdmin(user, admin) + if policyHasAdmin { + return true + } + + attachedPolicyHasAdmin := AttachedUserPolicyHasAdmin(user, admin) + if attachedPolicyHasAdmin { + return true + } + + userGroupsHaveAdmin := UsersGroupsHaveAdmin(svc, user, admin) + if userGroupsHaveAdmin { + return true + } + + return false } func main() { - sess, err := session.NewSession() - if err != nil { - fmt.Println("Got error creating new session") - fmt.Println(err.Error()) - os.Exit(1) - } - - svc := iam.New(sess, &aws.Config{Region: aws.String("us-west-2")}) - - numUsers := 0 - numAdmins := 0 - - // Get list of users - user := "User" - input := &iam.GetAccountAuthorizationDetailsInput{Filter: []*string{&user}} - resp, err := svc.GetAccountAuthorizationDetails(input) - if err != nil { - fmt.Println("Got error getting account details") - fmt.Println(err.Error()) - os.Exit(1) - } - - // The policy name that indicates administrator access - adminName := "AdministratorAccess" - - // Wade through resulting users - for _, user := range resp.UserDetailList { - numUsers += 1 - - isAdmin := IsUserAdmin(svc, user, adminName) - - if isAdmin { - fmt.Println(*user.UserName) - numAdmins += 1 - } - } - - // Are there more? - for *resp.IsTruncated { - input := &iam.GetAccountAuthorizationDetailsInput{Filter: []*string{&user}, Marker: resp.Marker} - resp, err = svc.GetAccountAuthorizationDetails(input) - if err != nil { - fmt.Println("Got error getting account details") - fmt.Println(err.Error()) - os.Exit(1) - } - - // Wade through resulting users - for _, user := range resp.UserDetailList { - numUsers += 1 - - isAdmin := IsUserAdmin(svc, user, adminName) - - if isAdmin { - fmt.Println(*user.UserName) - numAdmins += 1 - } - } - } - - fmt.Println("") - fmt.Println("Found", numAdmins, "admin(s) out of", numUsers, "user(s).") + sess, err := session.NewSession() + if err != nil { + fmt.Println("Got error creating new session") + fmt.Println(err.Error()) + os.Exit(1) + } + + svc := iam.New(sess, &aws.Config{Region: aws.String("us-west-2")}) + + numUsers := 0 + numAdmins := 0 + + // Get list of users + user := "User" + input := &iam.GetAccountAuthorizationDetailsInput{Filter: []*string{&user}} + resp, err := svc.GetAccountAuthorizationDetails(input) + if err != nil { + fmt.Println("Got error getting account details") + fmt.Println(err.Error()) + os.Exit(1) + } + + // The policy name that indicates administrator access + adminName := "AdministratorAccess" + + // Wade through resulting users + for _, user := range resp.UserDetailList { + numUsers += 1 + + isAdmin := IsUserAdmin(svc, user, adminName) + + if isAdmin { + fmt.Println(*user.UserName) + numAdmins += 1 + } + } + + // Are there more? + for *resp.IsTruncated { + input := &iam.GetAccountAuthorizationDetailsInput{Filter: []*string{&user}, Marker: resp.Marker} + resp, err = svc.GetAccountAuthorizationDetails(input) + if err != nil { + fmt.Println("Got error getting account details") + fmt.Println(err.Error()) + os.Exit(1) + } + + // Wade through resulting users + for _, user := range resp.UserDetailList { + numUsers += 1 + + isAdmin := IsUserAdmin(svc, user, adminName) + + if isAdmin { + fmt.Println(*user.UserName) + numAdmins += 1 + } + } + } + + fmt.Println("") + fmt.Println("Found", numAdmins, "admin(s) out of", numUsers, "user(s).") } diff --git a/go/example_code/iam/iam_accesskeylastused.go b/go/example_code/iam/iam_accesskeylastused.go index 3b51dedcf99..98106cc6ec3 100644 --- a/go/example_code/iam/iam_accesskeylastused.go +++ b/go/example_code/iam/iam_accesskeylastused.go @@ -1,58 +1,36 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Determines when an IAM access key was last used.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[GetAccessKeyLastUsed function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // Usage: // go run iam_accesskeylastused.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) - // Create a IAM service client. - svc := iam.New(sess) + // Create a IAM service client. + svc := iam.New(sess) - result, err := svc.GetAccessKeyLastUsed(&iam.GetAccessKeyLastUsedInput{ - AccessKeyId: aws.String("ACCESS_KEY_ID"), - }) + result, err := svc.GetAccessKeyLastUsed(&iam.GetAccessKeyLastUsedInput{ + AccessKeyId: aws.String("ACCESS_KEY_ID"), + }) - if err != nil { - fmt.Println("Error", err) - return - } + if err != nil { + fmt.Println("Error", err) + return + } - fmt.Println("Success", *result.AccessKeyLastUsed) + fmt.Println("Success", *result.AccessKeyLastUsed) } diff --git a/go/example_code/iam/iam_attachuserpolicy.go b/go/example_code/iam/iam_attachuserpolicy.go index 640da25eedd..5b11aaa48d5 100644 --- a/go/example_code/iam/iam_attachuserpolicy.go +++ b/go/example_code/iam/iam_attachuserpolicy.go @@ -1,96 +1,73 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Attaches an IAM policy.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[AttachRolePolicy function] -// snippet-keyword:[ListAttachedRolePoliciesPages function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // Usage: // go run iam_attachuserpolicy.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) - // Create a IAM service client. - svc := iam.New(sess) + // Create a IAM service client. + svc := iam.New(sess) - var pageErr error - policyName := "AmazonDynamoDBFullAccess" - policyArn := "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess" + var pageErr error + policyName := "AmazonDynamoDBFullAccess" + policyArn := "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess" - // Paginate through all role policies. If our role exists on any role - // policy we will set the pageErr and return false. Stopping the - // pagination. - err = svc.ListAttachedRolePoliciesPages( - &iam.ListAttachedRolePoliciesInput{ - RoleName: &os.Args[1], - }, - func(page *iam.ListAttachedRolePoliciesOutput, lastPage bool) bool { - if page != nil && len(page.AttachedPolicies) > 0 { - for _, policy := range page.AttachedPolicies { - if *policy.PolicyName == policyName { - pageErr = fmt.Errorf("%s is already attached to this role", policyName) - return false - } - } - // We should keep paginating because we did not find our role - return true - } - return false - }, - ) + // Paginate through all role policies. If our role exists on any role + // policy we will set the pageErr and return false. Stopping the + // pagination. + err = svc.ListAttachedRolePoliciesPages( + &iam.ListAttachedRolePoliciesInput{ + RoleName: &os.Args[1], + }, + func(page *iam.ListAttachedRolePoliciesOutput, lastPage bool) bool { + if page != nil && len(page.AttachedPolicies) > 0 { + for _, policy := range page.AttachedPolicies { + if *policy.PolicyName == policyName { + pageErr = fmt.Errorf("%s is already attached to this role", policyName) + return false + } + } + // We should keep paginating because we did not find our role + return true + } + return false + }, + ) - if pageErr != nil { - fmt.Println("Error", pageErr) - return - } + if pageErr != nil { + fmt.Println("Error", pageErr) + return + } - if err != nil { - fmt.Println("Error", err) - return - } + if err != nil { + fmt.Println("Error", err) + return + } - _, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{ - PolicyArn: &policyArn, - RoleName: &os.Args[1], - }) + _, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{ + PolicyArn: &policyArn, + RoleName: &os.Args[1], + }) - if err != nil { - fmt.Println("Unable to attach role policy to role") - return - } - fmt.Println("Role attached successfully") + if err != nil { + fmt.Println("Unable to attach role policy to role") + return + } + fmt.Println("Role attached successfully") } diff --git a/go/example_code/iam/iam_createaccesskey.go b/go/example_code/iam/iam_createaccesskey.go index ef066e147ec..3125f159984 100644 --- a/go/example_code/iam/iam_createaccesskey.go +++ b/go/example_code/iam/iam_createaccesskey.go @@ -1,58 +1,36 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Creates an IAM access key.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[CreateAccessKey function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // Usage: // go run iam_createaccesskey.go > newuserkeys.txt func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) - // Create a IAM service client. - svc := iam.New(sess) + // Create a IAM service client. + svc := iam.New(sess) - result, err := svc.CreateAccessKey(&iam.CreateAccessKeyInput{ - UserName: aws.String("IAM_USER_NAME"), - }) + result, err := svc.CreateAccessKey(&iam.CreateAccessKeyInput{ + UserName: aws.String("IAM_USER_NAME"), + }) - if err != nil { - fmt.Println("Error", err) - return - } + if err != nil { + fmt.Println("Error", err) + return + } - fmt.Println("Success", *result.AccessKey) + fmt.Println("Success", *result.AccessKey) } diff --git a/go/example_code/iam/iam_createaccountalias.go b/go/example_code/iam/iam_createaccountalias.go index 6b3859b13c7..ecbf740e7b2 100644 --- a/go/example_code/iam/iam_createaccountalias.go +++ b/go/example_code/iam/iam_createaccountalias.go @@ -1,59 +1,37 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Creates an IAM account alias.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[CreateAccountAlias function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // Usage: // go run iam_createaccountalias.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) - // Create a IAM service client. - svc := iam.New(sess) + // Create a IAM service client. + svc := iam.New(sess) - _, err = svc.CreateAccountAlias(&iam.CreateAccountAliasInput{ - AccountAlias: &os.Args[1], - }) + _, err = svc.CreateAccountAlias(&iam.CreateAccountAliasInput{ + AccountAlias: &os.Args[1], + }) - if err != nil { - fmt.Println("Error", err) - return - } + if err != nil { + fmt.Println("Error", err) + return + } - fmt.Printf("Account alias %s has been created\n", os.Args[1]) + fmt.Printf("Account alias %s has been created\n", os.Args[1]) } diff --git a/go/example_code/iam/iam_createpolicy.go b/go/example_code/iam/iam_createpolicy.go index 8f24a1c4b86..8279b005c49 100644 --- a/go/example_code/iam/iam_createpolicy.go +++ b/go/example_code/iam/iam_createpolicy.go @@ -1,105 +1,83 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Creates an IAM policy.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[CreatePolicy function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "fmt" + "encoding/json" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // PolicyDocument is our definition of our policies to be uploaded to IAM. type PolicyDocument struct { - Version string - Statement []StatementEntry + Version string + Statement []StatementEntry } // StatementEntry will dictate what this policy will allow or not allow. type StatementEntry struct { - Effect string - Action []string - Resource string + Effect string + Action []string + Resource string } // Usage: // go run iam_createpolicy.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) - // Create a IAM service client. - svc := iam.New(sess) + // Create a IAM service client. + svc := iam.New(sess) - // Builds our policy document for IAM. - policy := PolicyDocument{ - Version: "2012-10-17", - Statement: []StatementEntry{ - StatementEntry{ - Effect: "Allow", - Action: []string{ - "logs:CreateLogGroup", // Allow for creating log groups - }, - Resource: "RESOURCE ARN FOR logs:*", - }, - StatementEntry{ - Effect: "Allow", - // Allows for DeleteItem, GetItem, PutItem, Scan, and UpdateItem - Action: []string{ - "dynamodb:DeleteItem", - "dynamodb:GetItem", - "dynamodb:PutItem", - "dynamodb:Scan", - "dynamodb:UpdateItem", - }, - Resource: "RESOURCE ARN FOR dynamodb:*", - }, - }, - } + // Builds our policy document for IAM. + policy := PolicyDocument{ + Version: "2012-10-17", + Statement: []StatementEntry{ + StatementEntry{ + Effect: "Allow", + Action: []string{ + "logs:CreateLogGroup", // Allow for creating log groups + }, + Resource: "RESOURCE ARN FOR logs:*", + }, + StatementEntry{ + Effect: "Allow", + // Allows for DeleteItem, GetItem, PutItem, Scan, and UpdateItem + Action: []string{ + "dynamodb:DeleteItem", + "dynamodb:GetItem", + "dynamodb:PutItem", + "dynamodb:Scan", + "dynamodb:UpdateItem", + }, + Resource: "RESOURCE ARN FOR dynamodb:*", + }, + }, + } - b, err := json.Marshal(&policy) - if err != nil { - fmt.Println("Error marshaling policy", err) - return - } + b, err := json.Marshal(&policy) + if err != nil { + fmt.Println("Error marshaling policy", err) + return + } - result, err := svc.CreatePolicy(&iam.CreatePolicyInput{ - PolicyDocument: aws.String(string(b)), - PolicyName: aws.String("myDynamodbPolicy"), - }) + result, err := svc.CreatePolicy(&iam.CreatePolicyInput{ + PolicyDocument: aws.String(string(b)), + PolicyName: aws.String("myDynamodbPolicy"), + }) - if err != nil { - fmt.Println("Error", err) - return - } + if err != nil { + fmt.Println("Error", err) + return + } - fmt.Println("New policy", result) + fmt.Println("New policy", result) } diff --git a/go/example_code/iam/iam_createuser.go b/go/example_code/iam/iam_createuser.go index e040e2dad10..798e7020f80 100644 --- a/go/example_code/iam/iam_createuser.go +++ b/go/example_code/iam/iam_createuser.go @@ -1,69 +1,46 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Creates an IAM user.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[CreateUser function] -// snippet-keyword:[GetUser function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // Usage: // go run iam_createuser.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create a IAM service client. - svc := iam.New(sess) - - _, err = svc.GetUser(&iam.GetUserInput{ - UserName: &os.Args[1], - }) - - if awserr, ok := err.(awserr.Error); ok && awserr.Code() == iam.ErrCodeNoSuchEntityException { - result, err := svc.CreateUser(&iam.CreateUserInput{ - UserName: &os.Args[1], - }) - - if err != nil { - fmt.Println("CreateUser Error", err) - return - } - - fmt.Println("Success", result) - } else { - fmt.Println("GetUser Error", err) - } + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create a IAM service client. + svc := iam.New(sess) + + _, err = svc.GetUser(&iam.GetUserInput{ + UserName: &os.Args[1], + }) + + if awserr, ok := err.(awserr.Error); ok && awserr.Code() == iam.ErrCodeNoSuchEntityException { + result, err := svc.CreateUser(&iam.CreateUserInput{ + UserName: &os.Args[1], + }) + + if err != nil { + fmt.Println("CreateUser Error", err) + return + } + + fmt.Println("Success", result) + } else { + fmt.Println("GetUser Error", err) + } } diff --git a/go/example_code/iam/iam_deleteaccesskey.go b/go/example_code/iam/iam_deleteaccesskey.go index 0ec2a18d922..3cbe071b4c9 100644 --- a/go/example_code/iam/iam_deleteaccesskey.go +++ b/go/example_code/iam/iam_deleteaccesskey.go @@ -1,59 +1,37 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Deletes an IAM access key.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[DeleteAccessKey function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // Usage: // go run iam_deleteaccesskey.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create a IAM service client. - svc := iam.New(sess) - - result, err := svc.DeleteAccessKey(&iam.DeleteAccessKeyInput{ - AccessKeyId: aws.String("ACCESS_KEY_ID"), - UserName: aws.String("USER_NAME"), - }) - - if err != nil { - fmt.Println("Error", err) - return - } - - fmt.Println("Success", result) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create a IAM service client. + svc := iam.New(sess) + + result, err := svc.DeleteAccessKey(&iam.DeleteAccessKeyInput{ + AccessKeyId: aws.String("ACCESS_KEY_ID"), + UserName: aws.String("USER_NAME"), + }) + + if err != nil { + fmt.Println("Error", err) + return + } + + fmt.Println("Success", result) } diff --git a/go/example_code/iam/iam_deleteaccountalias.go b/go/example_code/iam/iam_deleteaccountalias.go index e6172cf8611..c6ceedf02ee 100644 --- a/go/example_code/iam/iam_deleteaccountalias.go +++ b/go/example_code/iam/iam_deleteaccountalias.go @@ -1,59 +1,37 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Deletes an IAM account alias.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[DeleteAccountAlias function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // Usage: // go run iam_deleteaccountalias.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) - // Create a IAM service client. - svc := iam.New(sess) + // Create a IAM service client. + svc := iam.New(sess) - _, err = svc.DeleteAccountAlias(&iam.DeleteAccountAliasInput{ - AccountAlias: &os.Args[1], - }) + _, err = svc.DeleteAccountAlias(&iam.DeleteAccountAliasInput{ + AccountAlias: &os.Args[1], + }) - if err != nil { - fmt.Println("Error", err) - return - } + if err != nil { + fmt.Println("Error", err) + return + } - fmt.Printf("Alias %s has been deleted\n", os.Args[1]) + fmt.Printf("Alias %s has been deleted\n", os.Args[1]) } diff --git a/go/example_code/iam/iam_deleteservercert.go b/go/example_code/iam/iam_deleteservercert.go index 528b59ac5f5..e6ba3da6e15 100644 --- a/go/example_code/iam/iam_deleteservercert.go +++ b/go/example_code/iam/iam_deleteservercert.go @@ -1,57 +1,35 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Deletes a server certificate.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[DeleteServerCertificate function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // Usage: // go run iam_deleteservercert.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create a IAM service client. - svc := iam.New(sess) - - _, err = svc.DeleteServerCertificate(&iam.DeleteServerCertificateInput{ - ServerCertificateName: aws.String("CERTIFICATE_NAME"), - }) - if err != nil { - fmt.Println("Error", err) - return - } - - fmt.Println("Server certificate deleted") + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create a IAM service client. + svc := iam.New(sess) + + _, err = svc.DeleteServerCertificate(&iam.DeleteServerCertificateInput{ + ServerCertificateName: aws.String("CERTIFICATE_NAME"), + }) + if err != nil { + fmt.Println("Error", err) + return + } + + fmt.Println("Server certificate deleted") } diff --git a/go/example_code/iam/iam_deleteuser.go b/go/example_code/iam/iam_deleteuser.go index f354d0c0dca..1b31f4eca74 100644 --- a/go/example_code/iam/iam_deleteuser.go +++ b/go/example_code/iam/iam_deleteuser.go @@ -1,64 +1,42 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Deletes an IAM user.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[DeleteUser function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // Usage: // go run iam_deleteuser.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create a IAM service client. - svc := iam.New(sess) - - _, err = svc.DeleteUser(&iam.DeleteUserInput{ - UserName: &os.Args[1], - }) - - // If the user does not exist than we will log an error. - if awserr, ok := err.(awserr.Error); ok && awserr.Code() == iam.ErrCodeNoSuchEntityException { - fmt.Printf("User %s does not exist\n", os.Args[1]) - return - } else if err != nil { - fmt.Println("Error", err) - return - } - - fmt.Printf("User %s has been deleted\n", os.Args[1]) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create a IAM service client. + svc := iam.New(sess) + + _, err = svc.DeleteUser(&iam.DeleteUserInput{ + UserName: &os.Args[1], + }) + + // If the user does not exist than we will log an error. + if awserr, ok := err.(awserr.Error); ok && awserr.Code() == iam.ErrCodeNoSuchEntityException { + fmt.Printf("User %s does not exist\n", os.Args[1]) + return + } else if err != nil { + fmt.Println("Error", err) + return + } + + fmt.Printf("User %s has been deleted\n", os.Args[1]) } diff --git a/go/example_code/iam/iam_detachuserpolicy.go b/go/example_code/iam/iam_detachuserpolicy.go index 6280ef8ce97..79e035304a9 100644 --- a/go/example_code/iam/iam_detachuserpolicy.go +++ b/go/example_code/iam/iam_detachuserpolicy.go @@ -1,94 +1,71 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Detaches an IAM policy.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[DetachRolePolicy function] -// snippet-keyword:[ListAttachedRolePoliciesPages function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // Usage: // go run iam_detachuserpolicy.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) - // Create a IAM service client. - svc := iam.New(sess) + // Create a IAM service client. + svc := iam.New(sess) - foundPolicy := false - policyName := "AmazonDynamoDBFullAccess" - policyArn := "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess" + foundPolicy := false + policyName := "AmazonDynamoDBFullAccess" + policyArn := "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess" - // Paginate through all role policies. If our role exists on any role - // policy we will stop iterating to detach the role. - err = svc.ListAttachedRolePoliciesPages( - &iam.ListAttachedRolePoliciesInput{ - RoleName: &os.Args[1], - }, - func(page *iam.ListAttachedRolePoliciesOutput, lastPage bool) bool { - if page != nil && len(page.AttachedPolicies) > 0 { - for _, policy := range page.AttachedPolicies { - if *policy.PolicyName == policyName { - foundPolicy = true - return false - } - } - return true - } - return false - }, - ) + // Paginate through all role policies. If our role exists on any role + // policy we will stop iterating to detach the role. + err = svc.ListAttachedRolePoliciesPages( + &iam.ListAttachedRolePoliciesInput{ + RoleName: &os.Args[1], + }, + func(page *iam.ListAttachedRolePoliciesOutput, lastPage bool) bool { + if page != nil && len(page.AttachedPolicies) > 0 { + for _, policy := range page.AttachedPolicies { + if *policy.PolicyName == policyName { + foundPolicy = true + return false + } + } + return true + } + return false + }, + ) - if err != nil { - fmt.Println("Error", err) - return - } + if err != nil { + fmt.Println("Error", err) + return + } - if !foundPolicy { - fmt.Println("Policy was not attached to role") - return - } + if !foundPolicy { + fmt.Println("Policy was not attached to role") + return + } - _, err = svc.DetachRolePolicy(&iam.DetachRolePolicyInput{ - PolicyArn: &policyArn, - RoleName: &os.Args[1], - }) + _, err = svc.DetachRolePolicy(&iam.DetachRolePolicyInput{ + PolicyArn: &policyArn, + RoleName: &os.Args[1], + }) - if err != nil { - fmt.Println("Unable to detach role policy to role") - return - } - fmt.Println("Role detached successfully") + if err != nil { + fmt.Println("Unable to detach role policy to role") + return + } + fmt.Println("Role detached successfully") } diff --git a/go/example_code/iam/iam_getpolicy.go b/go/example_code/iam/iam_getpolicy.go index fc2105c670d..7b7385e5d9f 100644 --- a/go/example_code/iam/iam_getpolicy.go +++ b/go/example_code/iam/iam_getpolicy.go @@ -1,59 +1,37 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Gets an IAM policy.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[GetPolicy function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // Usage: // go run iam_getpolicy.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create a IAM service client. - svc := iam.New(sess) - - arn := "arn:aws:iam::aws:policy/AWSLambdaExecute" - result, err := svc.GetPolicy(&iam.GetPolicyInput{ - PolicyArn: &arn, - }) - - if err != nil { - fmt.Println("Error", err) - return - } - - fmt.Printf("%s - %s\n", arn, *result.Policy.Description) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create a IAM service client. + svc := iam.New(sess) + + arn := "arn:aws:iam::aws:policy/AWSLambdaExecute" + result, err := svc.GetPolicy(&iam.GetPolicyInput{ + PolicyArn: &arn, + }) + + if err != nil { + fmt.Println("Error", err) + return + } + + fmt.Printf("%s - %s\n", arn, *result.Policy.Description) } diff --git a/go/example_code/iam/iam_getpublickeys.go b/go/example_code/iam/iam_getpublickeys.go index 66a48c9411f..f4d5574b167 100644 --- a/go/example_code/iam/iam_getpublickeys.go +++ b/go/example_code/iam/iam_getpublickeys.go @@ -1,78 +1,55 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Gets an IAM public key.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[GetSSHPublicKey function] -// snippet-keyword:[ListSSHPublicKeys function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // Usage: // go run iam_getpublickeys.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create a IAM service client. - svc := iam.New(sess) - - // List SSH public keys. - keysResult, err := svc.ListSSHPublicKeys(&iam.ListSSHPublicKeysInput{ - UserName: &os.Args[1], - }) - - if err != nil { - fmt.Println("Error", err) - return - } - - for _, key := range keysResult.SSHPublicKeys { - if key == nil { - continue - } - - // Get a SSH public key. - keyResult, err := svc.GetSSHPublicKey(&iam.GetSSHPublicKeyInput{ - UserName: &os.Args[1], - SSHPublicKeyId: key.SSHPublicKeyId, - Encoding: aws.String("SSH"), - }) - - if err != nil { - continue - } - - fmt.Printf("%s\n", *keyResult.SSHPublicKey.SSHPublicKeyBody) - } + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create a IAM service client. + svc := iam.New(sess) + + // List SSH public keys. + keysResult, err := svc.ListSSHPublicKeys(&iam.ListSSHPublicKeysInput{ + UserName: &os.Args[1], + }) + + if err != nil { + fmt.Println("Error", err) + return + } + + for _, key := range keysResult.SSHPublicKeys { + if key == nil { + continue + } + + // Get a SSH public key. + keyResult, err := svc.GetSSHPublicKey(&iam.GetSSHPublicKeyInput{ + UserName: &os.Args[1], + SSHPublicKeyId: key.SSHPublicKeyId, + Encoding: aws.String("SSH"), + }) + + if err != nil { + continue + } + + fmt.Printf("%s\n", *keyResult.SSHPublicKey.SSHPublicKeyBody) + } } diff --git a/go/example_code/iam/iam_getservercert.go b/go/example_code/iam/iam_getservercert.go index 02a1b176234..11517484374 100644 --- a/go/example_code/iam/iam_getservercert.go +++ b/go/example_code/iam/iam_getservercert.go @@ -1,57 +1,35 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Retries an IAM server certificate.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[GetServerCertificate function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // Usage: // go run iam_getservercert.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create a IAM service client. - svc := iam.New(sess) - - result, err := svc.GetServerCertificate(&iam.GetServerCertificateInput{ - ServerCertificateName: aws.String("CERTIFICATE_NAME"), - }) - if err != nil { - fmt.Println("Error", err) - return - } - - fmt.Println("ServerCertificate:", result) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create a IAM service client. + svc := iam.New(sess) + + result, err := svc.GetServerCertificate(&iam.GetServerCertificateInput{ + ServerCertificateName: aws.String("CERTIFICATE_NAME"), + }) + if err != nil { + fmt.Println("Error", err) + return + } + + fmt.Println("ServerCertificate:", result) } diff --git a/go/example_code/iam/iam_listaccesskeys.go b/go/example_code/iam/iam_listaccesskeys.go index 5bd38adb533..25217a7fd34 100644 --- a/go/example_code/iam/iam_listaccesskeys.go +++ b/go/example_code/iam/iam_listaccesskeys.go @@ -1,59 +1,37 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Lists your IAM access keys.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[ListAccessKeys function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // Usage: // go run iam_listaccesskeys.go > newuserkeys.txt func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create a IAM service client. - svc := iam.New(sess) - - result, err := svc.ListAccessKeys(&iam.ListAccessKeysInput{ - MaxItems: aws.Int64(5), - UserName: aws.String("IAM_USER_NAME"), - }) - - if err != nil { - fmt.Println("Error", err) - return - } - - fmt.Println("Success", result) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create a IAM service client. + svc := iam.New(sess) + + result, err := svc.ListAccessKeys(&iam.ListAccessKeysInput{ + MaxItems: aws.Int64(5), + UserName: aws.String("IAM_USER_NAME"), + }) + + if err != nil { + fmt.Println("Error", err) + return + } + + fmt.Println("Success", result) } diff --git a/go/example_code/iam/iam_listaccountaliases.go b/go/example_code/iam/iam_listaccountaliases.go index 5b5ede6b260..6c60553df78 100644 --- a/go/example_code/iam/iam_listaccountaliases.go +++ b/go/example_code/iam/iam_listaccountaliases.go @@ -1,63 +1,41 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Lists your IAM account aliases.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[ListAccountAliases function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // Usage: // go run iam_listaccountaliases.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create a IAM service client. - svc := iam.New(sess) - - result, err := svc.ListAccountAliases(&iam.ListAccountAliasesInput{ - MaxItems: aws.Int64(10), - }) - - if err != nil { - fmt.Println("Error", err) - return - } - - for i, alias := range result.AccountAliases { - if alias == nil { - continue - } - fmt.Printf("Alias %d: %s\n", i, *alias) - } + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create a IAM service client. + svc := iam.New(sess) + + result, err := svc.ListAccountAliases(&iam.ListAccountAliasesInput{ + MaxItems: aws.Int64(10), + }) + + if err != nil { + fmt.Println("Error", err) + return + } + + for i, alias := range result.AccountAliases { + if alias == nil { + continue + } + fmt.Printf("Alias %d: %s\n", i, *alias) + } } diff --git a/go/example_code/iam/iam_listservercerts.go b/go/example_code/iam/iam_listservercerts.go index b2fa145c670..9f6345eb610 100644 --- a/go/example_code/iam/iam_listservercerts.go +++ b/go/example_code/iam/iam_listservercerts.go @@ -1,61 +1,39 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Lists your IAM server certificates.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[ListServerCertificates function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // Usage: // go run iam_listservercerts.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create a IAM service client. - svc := iam.New(sess) - - result, err := svc.ListServerCertificates(nil) - if err != nil { - fmt.Println("Error", err) - return - } - - for i, metadata := range result.ServerCertificateMetadataList { - if metadata == nil { - continue - } - - fmt.Printf("Metadata %d: %v\n", i, metadata) - } + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create a IAM service client. + svc := iam.New(sess) + + result, err := svc.ListServerCertificates(nil) + if err != nil { + fmt.Println("Error", err) + return + } + + for i, metadata := range result.ServerCertificateMetadataList { + if metadata == nil { + continue + } + + fmt.Printf("Metadata %d: %v\n", i, metadata) + } } diff --git a/go/example_code/iam/iam_listusers.go b/go/example_code/iam/iam_listusers.go index f448a30775d..dad113ed36d 100644 --- a/go/example_code/iam/iam_listusers.go +++ b/go/example_code/iam/iam_listusers.go @@ -1,63 +1,41 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Lists your IAM users.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[ListUsers function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // Usage: // go run iam_listusers.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create a IAM service client. - svc := iam.New(sess) - - result, err := svc.ListUsers(&iam.ListUsersInput{ - MaxItems: aws.Int64(10), - }) - - if err != nil { - fmt.Println("Error", err) - return - } - - for i, user := range result.Users { - if user == nil { - continue - } - fmt.Printf("%d user %s created %v\n", i, *user.UserName, user.CreateDate) - } + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create a IAM service client. + svc := iam.New(sess) + + result, err := svc.ListUsers(&iam.ListUsersInput{ + MaxItems: aws.Int64(10), + }) + + if err != nil { + fmt.Println("Error", err) + return + } + + for i, user := range result.Users { + if user == nil { + continue + } + fmt.Printf("%d user %s created %v\n", i, *user.UserName, user.CreateDate) + } } diff --git a/go/example_code/iam/iam_updateaccesskey.go b/go/example_code/iam/iam_updateaccesskey.go index 92ef9bd4418..bdb03256805 100644 --- a/go/example_code/iam/iam_updateaccesskey.go +++ b/go/example_code/iam/iam_updateaccesskey.go @@ -1,60 +1,38 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Updates an IAM access key.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[UpdateAccessKey function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // Usage: // go run iam_updateaccesskey.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create a IAM service client. - svc := iam.New(sess) - - _, err = svc.UpdateAccessKey(&iam.UpdateAccessKeyInput{ - AccessKeyId: aws.String("ACCESS_KEY_ID"), - Status: aws.String(iam.StatusTypeActive), - UserName: aws.String("USER_NAME"), - }) - - if err != nil { - fmt.Println("Error", err) - return - } - - fmt.Println("Access Key updated") + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create a IAM service client. + svc := iam.New(sess) + + _, err = svc.UpdateAccessKey(&iam.UpdateAccessKeyInput{ + AccessKeyId: aws.String("ACCESS_KEY_ID"), + Status: aws.String(iam.StatusTypeActive), + UserName: aws.String("USER_NAME"), + }) + + if err != nil { + fmt.Println("Error", err) + return + } + + fmt.Println("Access Key updated") } diff --git a/go/example_code/iam/iam_updateservercert.go b/go/example_code/iam/iam_updateservercert.go index 3992ddacb8b..33c09a13e54 100644 --- a/go/example_code/iam/iam_updateservercert.go +++ b/go/example_code/iam/iam_updateservercert.go @@ -1,58 +1,36 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Updates an IAM server certificate.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[UpdateServerCertificate function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // Usage: // go run iam_updateservercert.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create a IAM service client. - svc := iam.New(sess) - - _, err = svc.UpdateServerCertificate(&iam.UpdateServerCertificateInput{ - ServerCertificateName: aws.String("CERTIFICATE_NAME"), - NewServerCertificateName: aws.String("NEW_CERTIFICATE_NAME"), - }) - if err != nil { - fmt.Println("Error", err) - return - } - - fmt.Println("Server certificate updated") + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create a IAM service client. + svc := iam.New(sess) + + _, err = svc.UpdateServerCertificate(&iam.UpdateServerCertificateInput{ + ServerCertificateName: aws.String("CERTIFICATE_NAME"), + NewServerCertificateName: aws.String("NEW_CERTIFICATE_NAME"), + }) + if err != nil { + fmt.Println("Error", err) + return + } + + fmt.Println("Server certificate updated") } diff --git a/go/example_code/iam/iam_updateuser.go b/go/example_code/iam/iam_updateuser.go index 700a52d3cd2..4f387d811db 100644 --- a/go/example_code/iam/iam_updateuser.go +++ b/go/example_code/iam/iam_updateuser.go @@ -1,60 +1,38 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Updates an IAM user.] -// snippet-keyword:[AWS Identity and Access Management] -// snippet-keyword:[UpdateUser function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[iam] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" ) // Usage: // go run iam_updateuser.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create a IAM service client. - svc := iam.New(sess) - - result, err := svc.UpdateUser(&iam.UpdateUserInput{ - UserName: &os.Args[1], - NewUserName: &os.Args[2], - }) - - if err != nil { - fmt.Println("Error", err) - return - } - - fmt.Println("Success", result) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create a IAM service client. + svc := iam.New(sess) + + result, err := svc.UpdateUser(&iam.UpdateUserInput{ + UserName: &os.Args[1], + NewUserName: &os.Args[2], + }) + + if err != nil { + fmt.Println("Error", err) + return + } + + fmt.Println("Success", result) } diff --git a/go/example_code/kms/kms_create_key.go b/go/example_code/kms/kms_create_key.go index 18e9fb47921..5e03227b5f7 100644 --- a/go/example_code/kms/kms_create_key.go +++ b/go/example_code/kms/kms_create_key.go @@ -1,37 +1,15 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Creates a KMS key.] -// snippet-keyword:[AWS Key Management Service] -// snippet-keyword:[CreateKey function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[kms] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/kms" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/kms" - "fmt" - "os" + "fmt" + "os" ) // Create an AWS KMS key (KMS key) @@ -41,29 +19,29 @@ import ( // use the KMS key to encrypt a data encryption key (DEK). func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create KMS service client - svc := kms.New(sess) - - // Create the key - result, err := svc.CreateKey(&kms.CreateKeyInput{ - Tags: []*kms.Tag{ - { - TagKey: aws.String("CreatedBy"), - TagValue: aws.String("ExampleUser"), - }, - }, - }) - - if err != nil { - fmt.Println("Got error creating key: ", err) - os.Exit(1) - } - - fmt.Println(*result.KeyMetadata.KeyId) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create KMS service client + svc := kms.New(sess) + + // Create the key + result, err := svc.CreateKey(&kms.CreateKeyInput{ + Tags: []*kms.Tag{ + { + TagKey: aws.String("CreatedBy"), + TagValue: aws.String("ExampleUser"), + }, + }, + }) + + if err != nil { + fmt.Println("Got error creating key: ", err) + os.Exit(1) + } + + fmt.Println(*result.KeyMetadata.KeyId) } diff --git a/go/example_code/kms/kms_decrypt_data.go b/go/example_code/kms/kms_decrypt_data.go index c9ca506167e..ad1954716b6 100644 --- a/go/example_code/kms/kms_decrypt_data.go +++ b/go/example_code/kms/kms_decrypt_data.go @@ -1,61 +1,39 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Decrypts a string that was encrypted by KMS.] -// snippet-keyword:[AWS Key Management Service] -// snippet-keyword:[Decrypt function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[kms] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-03-14] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/kms" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/kms" - "fmt" - "os" + "fmt" + "os" ) func main() { - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - // Create KMS service client - svc := kms.New(sess) + // Create KMS service client + svc := kms.New(sess) - // Encrypted data - blob := []byte("1234567890") + // Encrypted data + blob := []byte("1234567890") - // Decrypt the data - result, err := svc.Decrypt(&kms.DecryptInput{CiphertextBlob: blob}) + // Decrypt the data + result, err := svc.Decrypt(&kms.DecryptInput{CiphertextBlob: blob}) - if err != nil { - fmt.Println("Got error decrypting data: ", err) - os.Exit(1) - } + if err != nil { + fmt.Println("Got error decrypting data: ", err) + os.Exit(1) + } - blob_string := string(result.Plaintext) + blob_string := string(result.Plaintext) - fmt.Println(blob_string) + fmt.Println(blob_string) } diff --git a/go/example_code/kms/kms_encrypt_data.go b/go/example_code/kms/kms_encrypt_data.go index ec0bc59b687..42c2b73ab0d 100644 --- a/go/example_code/kms/kms_encrypt_data.go +++ b/go/example_code/kms/kms_encrypt_data.go @@ -1,68 +1,46 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Encrypts a string using KMS.] -// snippet-keyword:[AWS Key Management Service] -// snippet-keyword:[Encrypt function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[kms] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/kms" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/kms" - "fmt" - "os" + "fmt" + "os" ) func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) - // Create KMS service client - svc := kms.New(sess) + // Create KMS service client + svc := kms.New(sess) - // Encrypt data key - // - // Replace the fictitious key ARN with a valid key ID + // Encrypt data key + // + // Replace the fictitious key ARN with a valid key ID - keyId := "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab" + keyId := "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab" - text := "1234567890" + text := "1234567890" - // Encrypt the data - result, err := svc.Encrypt(&kms.EncryptInput{ - KeyId: aws.String(keyId), - Plaintext: []byte(text), - }) + // Encrypt the data + result, err := svc.Encrypt(&kms.EncryptInput{ + KeyId: aws.String(keyId), + Plaintext: []byte(text), + }) - if err != nil { - fmt.Println("Got error encrypting data: ", err) - os.Exit(1) - } + if err != nil { + fmt.Println("Got error encrypting data: ", err) + os.Exit(1) + } - fmt.Println("Blob (base-64 byte array):") - fmt.Println(result.CiphertextBlob) + fmt.Println("Blob (base-64 byte array):") + fmt.Println(result.CiphertextBlob) } diff --git a/go/example_code/kms/kms_re_encrypt_data.go b/go/example_code/kms/kms_re_encrypt_data.go index 73b44f52bce..0e32856c8d4 100644 --- a/go/example_code/kms/kms_re_encrypt_data.go +++ b/go/example_code/kms/kms_re_encrypt_data.go @@ -1,66 +1,44 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Decrypts encrypted data and then immediately re-encrypts data under a new AWS KSM key (KMS key).] -// snippet-keyword:[AWS Key Management Service] -// snippet-keyword:[ReEncrypt function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[kms] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-14] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/kms" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/kms" - "fmt" - "os" + "fmt" + "os" ) func main() { - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - // Create KMS service client - svc := kms.New(sess) + // Create KMS service client + svc := kms.New(sess) - // Encrypt data key - // - // Replace the fictitious key ARN with a valid key ID + // Encrypt data key + // + // Replace the fictitious key ARN with a valid key ID - keyId := "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab" + keyId := "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab" - // Encrypted data - blob := []byte("1234567890") + // Encrypted data + blob := []byte("1234567890") - // Re-encrypt the data key - result, err := svc.ReEncrypt(&kms.ReEncryptInput{CiphertextBlob: blob, DestinationKeyId: &keyId}) + // Re-encrypt the data key + result, err := svc.ReEncrypt(&kms.ReEncryptInput{CiphertextBlob: blob, DestinationKeyId: &keyId}) - if err != nil { - fmt.Println("Got error re-encrypting data: ", err) - os.Exit(1) - } + if err != nil { + fmt.Println("Got error re-encrypting data: ", err) + os.Exit(1) + } - fmt.Println("Blob (base-64 byte array):") - fmt.Println(result.CiphertextBlob) + fmt.Println("Blob (base-64 byte array):") + fmt.Println(result.CiphertextBlob) } diff --git a/go/example_code/lambda/aws-go-sdk-lambda-example-configure-function-for-notification.go b/go/example_code/lambda/aws-go-sdk-lambda-example-configure-function-for-notification.go index f1fad3a5ce8..634734e3a27 100644 --- a/go/example_code/lambda/aws-go-sdk-lambda-example-configure-function-for-notification.go +++ b/go/example_code/lambda/aws-go-sdk-lambda-example-configure-function-for-notification.go @@ -1,82 +1,62 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Configures a Lambda function to accept notifications from a resource.] -// snippet-keyword:[AWS Lambda] -// snippet-keyword:[AddPermission function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[lambda] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-1-6] -/* - Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lambda.go.configure_function.complete] package main // snippet-start:[lambda.go.configure_function.imports] import ( - "flag" - "fmt" - "os" + "flag" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/lambda" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/lambda" ) + // snippet-end:[lambda.go.configure_function.imports] func main() { - // snippet-start:[lambda.go.configure_function.vars] - functionPtr := flag.String("f", "", "The name of the Lambda function") - sourcePtr := flag.String("a", "", "The ARN of the entity invoking the function") - flag.Parse() - - if *functionPtr == "" || *sourcePtr == "" { - fmt.Println("You must supply the name of the function and of the entity invoking the function") - flag.PrintDefaults() - os.Exit(1) - } - // snippet-end:[lambda.go.configure_function.vars] - - // Initialize a session - // snippet-start:[lambda.go.configure_function.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := lambda.New(sess) - // snippet-end:[lambda.go.configure_function.session] - - // snippet-start:[lambda.go.configure_function.struct] - permArgs := &lambda.AddPermissionInput{ - Action: aws.String("lambda:InvokeFunction"), - FunctionName: functionPtr, - Principal: aws.String("s3.amazonaws.com"), - SourceArn: sourcePtr, - StatementId: aws.String("lambda_s3_notification"), - } - // snippet-end:[lambda.go.configure_function.struct] - - // snippet-start:[lambda.go.configure_function.add_permission] - result, err := svc.AddPermission(permArgs) - if err != nil { - fmt.Println("Cannot configure function for notifications") - os.Exit(0) - } - - fmt.Println(result) - // snippet-end:[lambda.go.configure_function.add_permission] + // snippet-start:[lambda.go.configure_function.vars] + functionPtr := flag.String("f", "", "The name of the Lambda function") + sourcePtr := flag.String("a", "", "The ARN of the entity invoking the function") + flag.Parse() + + if *functionPtr == "" || *sourcePtr == "" { + fmt.Println("You must supply the name of the function and of the entity invoking the function") + flag.PrintDefaults() + os.Exit(1) + } + // snippet-end:[lambda.go.configure_function.vars] + + // Initialize a session + // snippet-start:[lambda.go.configure_function.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := lambda.New(sess) + // snippet-end:[lambda.go.configure_function.session] + + // snippet-start:[lambda.go.configure_function.struct] + permArgs := &lambda.AddPermissionInput{ + Action: aws.String("lambda:InvokeFunction"), + FunctionName: functionPtr, + Principal: aws.String("s3.amazonaws.com"), + SourceArn: sourcePtr, + StatementId: aws.String("lambda_s3_notification"), + } + // snippet-end:[lambda.go.configure_function.struct] + + // snippet-start:[lambda.go.configure_function.add_permission] + result, err := svc.AddPermission(permArgs) + if err != nil { + fmt.Println("Cannot configure function for notifications") + os.Exit(0) + } + + fmt.Println(result) + // snippet-end:[lambda.go.configure_function.add_permission] } + // snippet-end:[lambda.go.configure_function.complete] diff --git a/go/example_code/lambda/aws-go-sdk-lambda-example-run-function.go b/go/example_code/lambda/aws-go-sdk-lambda-example-run-function.go index 06a7e74f693..84bd6b9886e 100644 --- a/go/example_code/lambda/aws-go-sdk-lambda-example-run-function.go +++ b/go/example_code/lambda/aws-go-sdk-lambda-example-run-function.go @@ -1,14 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Runs a Lambda function.] -// snippet-keyword:[AWS Lambda] -// snippet-keyword:[Invoke function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[lambda] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. @@ -26,95 +17,95 @@ package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/lambda" - - "encoding/json" - "fmt" - "os" - "strconv" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/lambda" + + "encoding/json" + "fmt" + "os" + "strconv" ) type getItemsRequest struct { - SortBy string - SortOrder string - ItemsToGet int + SortBy string + SortOrder string + ItemsToGet int } type getItemsResponseError struct { - Message string `json:"message"` + Message string `json:"message"` } type getItemsResponseData struct { - Item string `json:"item"` + Item string `json:"item"` } type getItemsResponseBody struct { - Result string `json:"result"` - Data []getItemsResponseData `json:"data"` - Error getItemsResponseError `json:"error"` + Result string `json:"result"` + Data []getItemsResponseData `json:"data"` + Error getItemsResponseError `json:"error"` } type getItemsResponseHeaders struct { - ContentType string `json:"Content-Type"` + ContentType string `json:"Content-Type"` } type getItemsResponse struct { - StatusCode int `json:"statusCode"` - Headers getItemsResponseHeaders `json:"headers"` - Body getItemsResponseBody `json:"body"` + StatusCode int `json:"statusCode"` + Headers getItemsResponseHeaders `json:"headers"` + Body getItemsResponseBody `json:"body"` } func main() { - // Create Lambda service client - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - client := lambda.New(sess, &aws.Config{Region: aws.String("us-west-2")}) - - // Get the 10 most recent items - request := getItemsRequest{"time", "descending", 10} - - payload, err := json.Marshal(request) - if err != nil { - fmt.Println("Error marshalling MyGetItemsFunction request") - os.Exit(0) - } - - result, err := client.Invoke(&lambda.InvokeInput{FunctionName: aws.String("MyGetItemsFunction"), Payload: payload}) - if err != nil { - fmt.Println("Error calling MyGetItemsFunction") - os.Exit(0) - } - - var resp getItemsResponse - - err = json.Unmarshal(result.Payload, &resp) - if err != nil { - fmt.Println("Error unmarshalling MyGetItemsFunction response") - os.Exit(0) - } - - // If the status code is NOT 200, the call failed - if resp.StatusCode != 200 { - fmt.Println("Error getting items, StatusCode: " + strconv.Itoa(resp.StatusCode)) - os.Exit(0) - } - - // If the result is failure, we got an error - if resp.Body.Result == "failure" { - fmt.Println("Failed to get items") - os.Exit(0) - } - - // Print out items - if len(resp.Body.Data) > 0 { - for i := range resp.Body.Data { - fmt.Println(resp.Body.Data[i].Item) - } - } else { - fmt.Println("There were no items") - } + // Create Lambda service client + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + client := lambda.New(sess, &aws.Config{Region: aws.String("us-west-2")}) + + // Get the 10 most recent items + request := getItemsRequest{"time", "descending", 10} + + payload, err := json.Marshal(request) + if err != nil { + fmt.Println("Error marshalling MyGetItemsFunction request") + os.Exit(0) + } + + result, err := client.Invoke(&lambda.InvokeInput{FunctionName: aws.String("MyGetItemsFunction"), Payload: payload}) + if err != nil { + fmt.Println("Error calling MyGetItemsFunction") + os.Exit(0) + } + + var resp getItemsResponse + + err = json.Unmarshal(result.Payload, &resp) + if err != nil { + fmt.Println("Error unmarshalling MyGetItemsFunction response") + os.Exit(0) + } + + // If the status code is NOT 200, the call failed + if resp.StatusCode != 200 { + fmt.Println("Error getting items, StatusCode: " + strconv.Itoa(resp.StatusCode)) + os.Exit(0) + } + + // If the result is failure, we got an error + if resp.Body.Result == "failure" { + fmt.Println("Failed to get items") + os.Exit(0) + } + + // Print out items + if len(resp.Body.Data) > 0 { + for i := range resp.Body.Data { + fmt.Println(resp.Body.Data[i].Item) + } + } else { + fmt.Println("There were no items") + } } diff --git a/go/example_code/lambda/aws-go-sdk-lambda-example-show-functions.go b/go/example_code/lambda/aws-go-sdk-lambda-example-show-functions.go index 79f057826a6..1a4798207fc 100644 --- a/go/example_code/lambda/aws-go-sdk-lambda-example-show-functions.go +++ b/go/example_code/lambda/aws-go-sdk-lambda-example-show-functions.go @@ -1,14 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Lists your Lambda functions.] -// snippet-keyword:[AWS Lambda] -// snippet-keyword:[ListFunctions function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[lambda] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. @@ -26,35 +17,35 @@ package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/lambda" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/lambda" - "fmt" - "os" + "fmt" + "os" ) // Lists all of your Lambda functions in us-west-2 func main() { - // Initialize a session - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create Lambda service client - svc := lambda.New(sess, &aws.Config{Region: aws.String("us-west-2")}) - - result, err := svc.ListFunctions(nil) - if err != nil { - fmt.Println("Cannot list functions") - os.Exit(0) - } - - fmt.Println("Functions:") - - for _, f := range result.Functions { - fmt.Println("Name: " + aws.StringValue(f.FunctionName)) - fmt.Println("Description: " + aws.StringValue(f.Description)) - fmt.Println("") - } + // Initialize a session + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create Lambda service client + svc := lambda.New(sess, &aws.Config{Region: aws.String("us-west-2")}) + + result, err := svc.ListFunctions(nil) + if err != nil { + fmt.Println("Cannot list functions") + os.Exit(0) + } + + fmt.Println("Functions:") + + for _, f := range result.Functions { + fmt.Println("Name: " + aws.StringValue(f.FunctionName)) + fmt.Println("Description: " + aws.StringValue(f.Description)) + fmt.Println("") + } } diff --git a/go/example_code/polly/pollyDescribeVoices.go b/go/example_code/polly/pollyDescribeVoices.go index d08ad4427d5..b84b2e9c1f6 100644 --- a/go/example_code/polly/pollyDescribeVoices.go +++ b/go/example_code/polly/pollyDescribeVoices.go @@ -1,62 +1,40 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Lists the Polly voices.] -// snippet-keyword:[Amazon Polly] -// snippet-keyword:[DescribeVoices function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[polly] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/polly" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/polly" - "fmt" - "os" + "fmt" + "os" ) func main() { - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file. (~/.aws/credentials). - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create Polly client - svc := polly.New(sess) - - // Get voices for US English - input := &polly.DescribeVoicesInput{LanguageCode: aws.String("en-US")} - - resp, err := svc.DescribeVoices(input) - if err != nil { - fmt.Println("Got error calling DescribeVoices:") - fmt.Print(err.Error()) - os.Exit(1) - } - - for _, v := range resp.Voices { - fmt.Println("Name: " + *v.Name) - fmt.Println("Gender: " + *v.Gender) - fmt.Println("") - } + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file. (~/.aws/credentials). + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create Polly client + svc := polly.New(sess) + + // Get voices for US English + input := &polly.DescribeVoicesInput{LanguageCode: aws.String("en-US")} + + resp, err := svc.DescribeVoices(input) + if err != nil { + fmt.Println("Got error calling DescribeVoices:") + fmt.Print(err.Error()) + os.Exit(1) + } + + for _, v := range resp.Voices { + fmt.Println("Name: " + *v.Name) + fmt.Println("Gender: " + *v.Gender) + fmt.Println("") + } } diff --git a/go/example_code/polly/pollyListLexicons.go b/go/example_code/polly/pollyListLexicons.go index 4651d4beb86..fac70071c42 100644 --- a/go/example_code/polly/pollyListLexicons.go +++ b/go/example_code/polly/pollyListLexicons.go @@ -1,59 +1,37 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Lists the Polly lexicons.] -// snippet-keyword:[Amazon Polly] -// snippet-keyword:[ListLexicons function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[polly] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/polly" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/polly" - "fmt" - "os" + "fmt" + "os" ) func main() { - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file. (~/.aws/credentials). - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create Polly client - svc := polly.New(sess) - - resp, err := svc.ListLexicons(nil) - if err != nil { - fmt.Println("Got error calling ListLexicons:") - fmt.Print(err.Error()) - os.Exit(1) - } - - for _, l := range resp.Lexicons { - fmt.Println(*l.Name) - fmt.Println(" Alphabet: " + *l.Attributes.Alphabet) - fmt.Println(" Language: " + *l.Attributes.LanguageCode) - fmt.Println("") - } + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file. (~/.aws/credentials). + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create Polly client + svc := polly.New(sess) + + resp, err := svc.ListLexicons(nil) + if err != nil { + fmt.Println("Got error calling ListLexicons:") + fmt.Print(err.Error()) + os.Exit(1) + } + + for _, l := range resp.Lexicons { + fmt.Println(*l.Name) + fmt.Println(" Alphabet: " + *l.Attributes.Alphabet) + fmt.Println(" Language: " + *l.Attributes.LanguageCode) + fmt.Println("") + } } diff --git a/go/example_code/polly/pollySynthesizeSpeech.go b/go/example_code/polly/pollySynthesizeSpeech.go index ffbc6b0b9b4..9f22b834669 100644 --- a/go/example_code/polly/pollySynthesizeSpeech.go +++ b/go/example_code/polly/pollySynthesizeSpeech.go @@ -1,98 +1,76 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Gets text from a file and produces an MP3 file containing the synthesized speech.] -// snippet-keyword:[Amazon Polly] -// snippet-keyword:[SynthesizeSpeech function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[polly] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/polly" - - "fmt" - "os" - "strings" - "io" - "io/ioutil" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/polly" + + "fmt" + "io" + "io/ioutil" + "os" + "strings" ) func main() { - if len(os.Args) != 2 { - fmt.Println("You must supply an alarm name") - os.Exit(1) - } - - // The name of the text file to convert to MP3 - fileName := os.Args[1] - - // Open text file and get it's contents as a string - contents, err := ioutil.ReadFile(fileName) - if err != nil { - fmt.Println("Got error opening file " + fileName) - fmt.Print(err.Error()) - os.Exit(1) - } - - // Convert bytes to string - s := string(contents[:]) - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file. (~/.aws/credentials). - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create Polly client - svc := polly.New(sess) - - // Output to MP3 using voice Joanna - input := &polly.SynthesizeSpeechInput{OutputFormat: aws.String("mp3"), Text: aws.String(s), VoiceId: aws.String("Joanna")} - - output, err := svc.SynthesizeSpeech(input) - if err != nil { - fmt.Println("Got error calling SynthesizeSpeech:") - fmt.Print(err.Error()) - os.Exit(1) - } - - // Save as MP3 - names := strings.Split(fileName, ".") - name := names[0] - mp3File := name + ".mp3" - - outFile, err := os.Create(mp3File) - if err != nil { - fmt.Println("Got error creating " + mp3File + ":") - fmt.Print(err.Error()) - os.Exit(1) - } - - defer outFile.Close() - _, err = io.Copy(outFile, output.AudioStream) - if err != nil { - fmt.Println("Got error saving MP3:") - fmt.Print(err.Error()) - os.Exit(1) - } + if len(os.Args) != 2 { + fmt.Println("You must supply an alarm name") + os.Exit(1) + } + + // The name of the text file to convert to MP3 + fileName := os.Args[1] + + // Open text file and get it's contents as a string + contents, err := ioutil.ReadFile(fileName) + if err != nil { + fmt.Println("Got error opening file " + fileName) + fmt.Print(err.Error()) + os.Exit(1) + } + + // Convert bytes to string + s := string(contents[:]) + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file. (~/.aws/credentials). + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create Polly client + svc := polly.New(sess) + + // Output to MP3 using voice Joanna + input := &polly.SynthesizeSpeechInput{OutputFormat: aws.String("mp3"), Text: aws.String(s), VoiceId: aws.String("Joanna")} + + output, err := svc.SynthesizeSpeech(input) + if err != nil { + fmt.Println("Got error calling SynthesizeSpeech:") + fmt.Print(err.Error()) + os.Exit(1) + } + + // Save as MP3 + names := strings.Split(fileName, ".") + name := names[0] + mp3File := name + ".mp3" + + outFile, err := os.Create(mp3File) + if err != nil { + fmt.Println("Got error creating " + mp3File + ":") + fmt.Print(err.Error()) + os.Exit(1) + } + + defer outFile.Close() + _, err = io.Copy(outFile, output.AudioStream) + if err != nil { + fmt.Println("Got error saving MP3:") + fmt.Print(err.Error()) + os.Exit(1) + } } diff --git a/go/example_code/rds/rds_copy_snapshot_to_s3.go b/go/example_code/rds/rds_copy_snapshot_to_s3.go index b6b7616e293..278ac444793 100644 --- a/go/example_code/rds/rds_copy_snapshot_to_s3.go +++ b/go/example_code/rds/rds_copy_snapshot_to_s3.go @@ -1,25 +1,6 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[AWS] -// snippet-sourcedescription:[rds_copy_snapshot_to_s3 copies RDS cluster snapshots to S3.] -// snippet-keyword:[Amazon Relational Database Service] -// snippet-keyword:[Amazon RDS] -// snippet-keyword:[CopyDBSnaphotToS3 function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[rds] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[rds.go.copy_rds_snapshot_to_s3] package main diff --git a/go/example_code/rds/rds_create_cluster_snapshot.go b/go/example_code/rds/rds_create_cluster_snapshot.go index 7ce754622c7..eecae8b5a5c 100644 --- a/go/example_code/rds/rds_create_cluster_snapshot.go +++ b/go/example_code/rds/rds_create_cluster_snapshot.go @@ -1,93 +1,72 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[AWS] -// snippet-sourcedescription:[rds_create_cluster_snapshot creates a snapshot of an RDS cluster.] -// snippet-keyword:[Amazon Relational Database Service] -// snippet-keyword:[Amazon RDS] -// snippet-keyword:[CreateDBClusterSnapshot function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[rds] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[rds.go.create_cluster_snapshot] package main import ( - "fmt" - "os" - "strings" - "time" + "fmt" + "os" + "strings" + "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/rds" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/rds" ) // Creates a RDS Cluster snapshot in the region configured in the shared config // or AWS_REGION environment variable. // // Usage: -// go run rds_create_cluster_snapshot CLUSTER_NAME +// +// go run rds_create_cluster_snapshot CLUSTER_NAME func main() { - if len(os.Args) != 2 { - exitErrorf("Cluster name missing!\nUsage: %s cluster_name", os.Args[0]) - } + if len(os.Args) != 2 { + exitErrorf("Cluster name missing!\nUsage: %s cluster_name", os.Args[0]) + } - cluster := os.Args[1] + cluster := os.Args[1] - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) - // Create RDS service client - svc := rds.New(sess) + // Create RDS service client + svc := rds.New(sess) - // Get the current date and time to uniquely identify snapshot - currentTime := time.Now() - t := currentTime.Format("2006-01-02 15:04:05") - // Replace space with underscore - t = strings.Replace(t, " ", "_", -1) + // Get the current date and time to uniquely identify snapshot + currentTime := time.Now() + t := currentTime.Format("2006-01-02 15:04:05") + // Replace space with underscore + t = strings.Replace(t, " ", "_", -1) - // Create the RDS Cluster snapshot - _, err = svc.CreateDBClusterSnapshot(&rds.CreateDBClusterSnapshotInput{ - DBClusterIdentifier: aws.String(cluster), - DBClusterSnapshotIdentifier: aws.String(cluster + t), - }) - if err != nil { - exitErrorf("Unable to create snapshot in cluster %q, %v", cluster, err) - } + // Create the RDS Cluster snapshot + _, err = svc.CreateDBClusterSnapshot(&rds.CreateDBClusterSnapshotInput{ + DBClusterIdentifier: aws.String(cluster), + DBClusterSnapshotIdentifier: aws.String(cluster + t), + }) + if err != nil { + exitErrorf("Unable to create snapshot in cluster %q, %v", cluster, err) + } - // Wait until snapshot is created before finishing - fmt.Printf("Waiting for snapshot in cluster %q to be created...\n", cluster) + // Wait until snapshot is created before finishing + fmt.Printf("Waiting for snapshot in cluster %q to be created...\n", cluster) - err = svc.WaitUntilDBSnapshotAvailable(&rds.DescribeDBSnapshotsInput{ - DBInstanceIdentifier: aws.String(cluster), - }) - if err != nil { - exitErrorf("Error occurred while waiting for snapshot to be created in cluster, %v", cluster) - } + err = svc.WaitUntilDBSnapshotAvailable(&rds.DescribeDBSnapshotsInput{ + DBInstanceIdentifier: aws.String(cluster), + }) + if err != nil { + exitErrorf("Error occurred while waiting for snapshot to be created in cluster, %v", cluster) + } - fmt.Printf("Snapshot %q successfully created in cluster\n", cluster) + fmt.Printf("Snapshot %q successfully created in cluster\n", cluster) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } + // snippet-end:[rds.go.create_cluster_snapshot] diff --git a/go/example_code/rds/rds_create_snapshot.go b/go/example_code/rds/rds_create_snapshot.go index 337921de291..79b3ce41cbd 100644 --- a/go/example_code/rds/rds_create_snapshot.go +++ b/go/example_code/rds/rds_create_snapshot.go @@ -1,93 +1,72 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[AWS] -// snippet-sourcedescription:[rds_create_snapshot creates a snapshot of an RDS instance.] -// snippet-keyword:[Amazon Relational Database Service] -// snippet-keyword:[Amazon RDS] -// snippet-keyword:[CreateDBSnapshot function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[rds] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[rds.go.create_db_snapshot] package main import ( - "fmt" - "os" - "strings" - "time" + "fmt" + "os" + "strings" + "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/rds" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/rds" ) // Creates a RDS snapshot in the region configured in the shared config // or AWS_REGION environment variable. // // Usage: -// go run s3_create_snapshot INSTANCE_NAME +// +// go run s3_create_snapshot INSTANCE_NAME func main() { - if len(os.Args) != 2 { - exitErrorf("Instance name missing!\nUsage: %s instance_name", os.Args[0]) - } + if len(os.Args) != 2 { + exitErrorf("Instance name missing!\nUsage: %s instance_name", os.Args[0]) + } - instance := os.Args[1] + instance := os.Args[1] - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) - // Create RDS service client - svc := rds.New(sess) + // Create RDS service client + svc := rds.New(sess) - // Get the current date and time to uniquely identify snapshot - currentTime := time.Now() - t := currentTime.Format("2006-01-02 15:04:05") - // Replace space with underscore - t = strings.Replace(t, " ", "_", -1) + // Get the current date and time to uniquely identify snapshot + currentTime := time.Now() + t := currentTime.Format("2006-01-02 15:04:05") + // Replace space with underscore + t = strings.Replace(t, " ", "_", -1) - // Create the RDS snapshot - _, err = svc.CreateDBSnapshot(&rds.CreateDBSnapshotInput{ - DBInstanceIdentifier: aws.String(instance), - DBSnapshotIdentifier: aws.String(instance + t), - }) - if err != nil { - exitErrorf("Unable to create snapshot in instance %q, %v", instance, err) - } + // Create the RDS snapshot + _, err = svc.CreateDBSnapshot(&rds.CreateDBSnapshotInput{ + DBInstanceIdentifier: aws.String(instance), + DBSnapshotIdentifier: aws.String(instance + t), + }) + if err != nil { + exitErrorf("Unable to create snapshot in instance %q, %v", instance, err) + } - // Wait until snapshot is created before finishing - fmt.Printf("Waiting for snapshot in instance %q to be created...\n", instance) + // Wait until snapshot is created before finishing + fmt.Printf("Waiting for snapshot in instance %q to be created...\n", instance) - err = svc.WaitUntilDBSnapshotAvailable(&rds.DescribeDBSnapshotsInput{ - DBInstanceIdentifier: aws.String(instance), - }) - if err != nil { - exitErrorf("Error occurred while waiting for snapshot to be created in instance, %v", instance) - } + err = svc.WaitUntilDBSnapshotAvailable(&rds.DescribeDBSnapshotsInput{ + DBInstanceIdentifier: aws.String(instance), + }) + if err != nil { + exitErrorf("Error occurred while waiting for snapshot to be created in instance, %v", instance) + } - fmt.Printf("Snapshot %q successfully created in instance\n", instance) + fmt.Printf("Snapshot %q successfully created in instance\n", instance) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } + // snippet-end:[rds.go.create_db_snapshot] diff --git a/go/example_code/rds/rds_list_all_instances.go b/go/example_code/rds/rds_list_all_instances.go index 1a7127ea35f..574ad47cca4 100644 --- a/go/example_code/rds/rds_list_all_instances.go +++ b/go/example_code/rds/rds_list_all_instances.go @@ -1,65 +1,43 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[AWS] -// snippet-sourcedescription:[rds_list_all_instances lists your RDS instances.] -// snippet-keyword:[Amazon Relational Database Service] -// snippet-keyword:[Amazon RDS] -// snippet-keyword:[DescribeDBInstances function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[rds] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[rds.go.describe_db_instances] package main import ( - "fmt" - "os" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/rds" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/rds" ) func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create RDS service client - svc := rds.New(sess) - - result, err := svc.DescribeDBInstances(nil) - if err != nil { - exitErrorf("Unable to list instances, %v", err) - } - - fmt.Println("Instances:") - - for _, d := range result.DBInstances { - fmt.Printf("* %s created on %s\n", - aws.StringValue(d.DBInstanceIdentifier), aws.TimeValue(d.InstanceCreateTime)) - } + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create RDS service client + svc := rds.New(sess) + + result, err := svc.DescribeDBInstances(nil) + if err != nil { + exitErrorf("Unable to list instances, %v", err) + } + + fmt.Println("Instances:") + + for _, d := range result.DBInstances { + fmt.Printf("* %s created on %s\n", + aws.StringValue(d.DBInstanceIdentifier), aws.TimeValue(d.InstanceCreateTime)) + } } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } + // snippet-end:[rds.go.describe_db_instances] diff --git a/go/example_code/rds/rds_list_cluster_snapshots.go b/go/example_code/rds/rds_list_cluster_snapshots.go index 315ff09ccef..0689e94cd91 100644 --- a/go/example_code/rds/rds_list_cluster_snapshots.go +++ b/go/example_code/rds/rds_list_cluster_snapshots.go @@ -1,63 +1,41 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[AWS] -// snippet-sourcedescription:[rds_list_cluster_snapshots lists your RDS cluster snapshots.] -// snippet-keyword:[Amazon Relational Database Service] -// snippet-keyword:[Amazon RDS] -// snippet-keyword:[DescribeDBClusterSnapshots function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[rds] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[rds.go.describe_db_cluster_snapshots] package main import ( - "fmt" - "os" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/rds" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/rds" ) func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create RDS service client - svc := rds.New(sess) - - result, err := svc.DescribeDBClusterSnapshots(nil) - if err != nil { - exitErrorf("Unable to list snapshots, %v", err) - } - - for _, s := range result.DBClusterSnapshots { - fmt.Printf("* %s with status %s\n", - aws.StringValue(s.DBClusterSnapshotIdentifier), aws.StringValue(s.Status)) - } + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create RDS service client + svc := rds.New(sess) + + result, err := svc.DescribeDBClusterSnapshots(nil) + if err != nil { + exitErrorf("Unable to list snapshots, %v", err) + } + + for _, s := range result.DBClusterSnapshots { + fmt.Printf("* %s with status %s\n", + aws.StringValue(s.DBClusterSnapshotIdentifier), aws.StringValue(s.Status)) + } } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } + // snippet-end:[rds.go.describe_db_cluster_snapshots] diff --git a/go/example_code/rds/rds_list_instance_snapshots.go b/go/example_code/rds/rds_list_instance_snapshots.go index 524217c902b..eed2d17f01c 100644 --- a/go/example_code/rds/rds_list_instance_snapshots.go +++ b/go/example_code/rds/rds_list_instance_snapshots.go @@ -1,63 +1,41 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[AWS] -// snippet-sourcedescription:[rds_list_instance_snapshots lists your RDS instance snapshots.] -// snippet-keyword:[Amazon Relational Database Service] -// snippet-keyword:[Amazon RDS] -// snippet-keyword:[DescribeDBSnapshots function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[rds] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[rds.go.describe_db_snapshots] package main import ( - "fmt" - "os" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/rds" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/rds" ) func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create RDS service client - svc := rds.New(sess) - - result, err := svc.DescribeDBSnapshots(nil) - if err != nil { - exitErrorf("Unable to list snapshots, %v", err) - } - - for _, s := range result.DBSnapshots { - fmt.Printf("* %s with status %s\n", - aws.StringValue(s.DBSnapshotIdentifier), aws.StringValue(s.Status)) - } + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create RDS service client + svc := rds.New(sess) + + result, err := svc.DescribeDBSnapshots(nil) + if err != nil { + exitErrorf("Unable to list snapshots, %v", err) + } + + for _, s := range result.DBSnapshots { + fmt.Printf("* %s with status %s\n", + aws.StringValue(s.DBSnapshotIdentifier), aws.StringValue(s.Status)) + } } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } + // snippet-end:[rds.go.describe_db_snapshots] diff --git a/go/example_code/rds/rds_list_parameter_groups.go b/go/example_code/rds/rds_list_parameter_groups.go index fd8f9dc1289..9d5017c2e09 100644 --- a/go/example_code/rds/rds_list_parameter_groups.go +++ b/go/example_code/rds/rds_list_parameter_groups.go @@ -1,63 +1,41 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[AWS] -// snippet-sourcedescription:[rds_list_parameter_groups lists your RDS parameter groups.] -// snippet-keyword:[Amazon Relational Database Service] -// snippet-keyword:[Amazon RDS] -// snippet-keyword:[DescribeDBParameterGroups function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[rds] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[rds.go.describe_db_parameter_groups] package main import ( - "fmt" - "os" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/rds" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/rds" ) func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create RDS service client - svc := rds.New(sess) - - result, err := svc.DescribeDBParameterGroups(nil) - if err != nil { - exitErrorf("Unable to list parameter groups, %v", err) - } - - for _, p := range result.DBParameterGroups { - fmt.Printf("* %s with description: %s\n", - aws.StringValue(p.DBParameterGroupName), aws.StringValue(p.Description)) - } + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create RDS service client + svc := rds.New(sess) + + result, err := svc.DescribeDBParameterGroups(nil) + if err != nil { + exitErrorf("Unable to list parameter groups, %v", err) + } + + for _, p := range result.DBParameterGroups { + fmt.Printf("* %s with description: %s\n", + aws.StringValue(p.DBParameterGroupName), aws.StringValue(p.Description)) + } } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } + // snippet-end:[rds.go.describe_db_parameter_groups] diff --git a/go/example_code/rds/rds_list_security_group.go b/go/example_code/rds/rds_list_security_group.go index 04aa66d93bf..681f0d1b776 100644 --- a/go/example_code/rds/rds_list_security_group.go +++ b/go/example_code/rds/rds_list_security_group.go @@ -1,63 +1,41 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[AWS] -// snippet-sourcedescription:[rds_list_security_groups.go lists your RDS security groups.] -// snippet-keyword:[Amazon Relational Database Service] -// snippet-keyword:[Amazon RDS] -// snippet-keyword:[DescribeDBSecurityGroups function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[rds] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[rds.go.describe_db_security_groups] package main import ( - "fmt" - "os" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/rds" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/rds" ) func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create RDS service client - svc := rds.New(sess) - - result, err := svc.DescribeDBSecurityGroups(nil) - if err != nil { - exitErrorf("Unable to list security groups, %v", err) - } - - for _, s := range result.DBSecurityGroups { - fmt.Printf("* %s in VpcId: %s\n", - aws.StringValue(s.DBSecurityGroupName), aws.StringValue(s.VpcId)) - } + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create RDS service client + svc := rds.New(sess) + + result, err := svc.DescribeDBSecurityGroups(nil) + if err != nil { + exitErrorf("Unable to list security groups, %v", err) + } + + for _, s := range result.DBSecurityGroups { + fmt.Printf("* %s in VpcId: %s\n", + aws.StringValue(s.DBSecurityGroupName), aws.StringValue(s.VpcId)) + } } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } + // snippet-end:[rds.go.describe_db_security_groups] diff --git a/go/example_code/rds/rds_list_subnet_groups.go b/go/example_code/rds/rds_list_subnet_groups.go index 4208e181e27..9fabd835f38 100644 --- a/go/example_code/rds/rds_list_subnet_groups.go +++ b/go/example_code/rds/rds_list_subnet_groups.go @@ -1,63 +1,41 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[AWS] -// snippet-sourcedescription:[rds_list_subnet_groups.go lists your RDS subnet groups.] -// snippet-keyword:[Amazon Relational Database Service] -// snippet-keyword:[Amazon RDS] -// snippet-keyword:[DescribeDBSubnetGroups function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[rds] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[rds.go.describe_db_subnet_groups] package main import ( - "fmt" - "os" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/rds" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/rds" ) func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create RDS service client - svc := rds.New(sess) - - result, err := svc.DescribeDBSubnetGroups(nil) - if err != nil { - exitErrorf("Unable to list subnets groups, %v", err) - } - - for _, s := range result.DBSubnetGroups { - fmt.Printf("* %s in VpcId: %s\n", - aws.StringValue(s.DBSubnetGroupName), aws.StringValue(s.VpcId)) - } + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create RDS service client + svc := rds.New(sess) + + result, err := svc.DescribeDBSubnetGroups(nil) + if err != nil { + exitErrorf("Unable to list subnets groups, %v", err) + } + + for _, s := range result.DBSubnetGroups { + fmt.Printf("* %s in VpcId: %s\n", + aws.StringValue(s.DBSubnetGroupName), aws.StringValue(s.VpcId)) + } } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } + // snippet-end:[rds.go.describe_db_subnet_groups] diff --git a/go/example_code/rekognition/detect_faces.go b/go/example_code/rekognition/detect_faces.go index 92868899fc4..fb85cd040c8 100644 --- a/go/example_code/rekognition/detect_faces.go +++ b/go/example_code/rekognition/detect_faces.go @@ -1,25 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Deletes the website configuration on an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[DeleteBucketWebsite function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main diff --git a/go/example_code/s3/create_new_bucket_and_object.go b/go/example_code/s3/create_new_bucket_and_object.go index 743a0bd7d99..ab162fedcbe 100644 --- a/go/example_code/s3/create_new_bucket_and_object.go +++ b/go/example_code/s3/create_new_bucket_and_object.go @@ -1,81 +1,58 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Creates an S3 bucket and adds an item to it.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[CreateBucket function] -// snippet-keyword:[PutObject function] -// snippet-keyword:[WaitUntilBucketExists function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "log" - "strings" + "log" + "strings" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) // Downloads an item from an S3 Bucket in the region configured in the shared config // or AWS_REGION environment variable. // // Usage: -// go run s3_download.go +// +// go run s3_download.go func main() { - bucket := "myBucket" - key := "TestFile.txt" - - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create S3 service client - svc := s3.New(sess) - - _, err = svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: &bucket, - }) - if err != nil { - log.Println("Failed to create bucket", err) - return - } - - if err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{Bucket: &bucket}); err != nil { - log.Printf("Failed to wait for bucket to exist %s, %s\n", bucket, err) - return - } - - _, err = svc.PutObject(&s3.PutObjectInput{ - Body: strings.NewReader("Hello World!"), - Bucket: &bucket, - Key: &key, - }) - if err != nil { - log.Printf("Failed to upload data to %s/%s, %s\n", bucket, key, err) - return - } - - log.Printf("Successfully created bucket %s and uploaded data with key %s\n", bucket, key) + bucket := "myBucket" + key := "TestFile.txt" + + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create S3 service client + svc := s3.New(sess) + + _, err = svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: &bucket, + }) + if err != nil { + log.Println("Failed to create bucket", err) + return + } + + if err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{Bucket: &bucket}); err != nil { + log.Printf("Failed to wait for bucket to exist %s, %s\n", bucket, err) + return + } + + _, err = svc.PutObject(&s3.PutObjectInput{ + Body: strings.NewReader("Hello World!"), + Bucket: &bucket, + Key: &key, + }) + if err != nil { + log.Printf("Failed to upload data to %s/%s, %s\n", bucket, key, err) + return + } + + log.Printf("Successfully created bucket %s and uploaded data with key %s\n", bucket, key) } diff --git a/go/example_code/s3/crud/s3_crud_ops.go b/go/example_code/s3/crud/s3_crud_ops.go index 4c45795fee8..03bdafbff55 100644 --- a/go/example_code/s3/crud/s3_crud_ops.go +++ b/go/example_code/s3/crud/s3_crud_ops.go @@ -1,163 +1,134 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[s3_crud_ops.go performs CRUD (create, read, update, delete) operations on an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[CreateBucket function] -// snippet-keyword:[ListBuckets function] -// snippet-keyword:[GetBucketAcl function] -// snippet-keyword:[PutBucketAcl function] -// snippet-keyword:[DeleteBucket function] -// snippet-keyword:[WaitUntilBucketExists function] -// snippet-keyword:[WaitUntilBucketNotExists function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-05-21] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" + "errors" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) // Functions to perform CRUD (create, read, update, delete) operations in S3 // CreateBucket creates a bucket func CreateBucket(sess *session.Session, bucket string) error { - // Create S3 service client - svc := s3.New(sess) - - // Create the S3 Bucket - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: aws.String(bucket), - }) - if err != nil { - return err - } - - // Wait until bucket is created before finishing - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: aws.String(bucket), - }) - if err != nil { - return err - } - - return nil + // Create S3 service client + svc := s3.New(sess) + + // Create the S3 Bucket + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: aws.String(bucket), + }) + if err != nil { + return err + } + + // Wait until bucket is created before finishing + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: aws.String(bucket), + }) + if err != nil { + return err + } + + return nil } // GetBucket determines whether we have this bucket func GetBucket(sess *session.Session, bucket string) error { - // Create S3 service client - svc := s3.New(sess) - - // Do we have this Bucket? - _, err := svc.HeadBucket(&s3.HeadBucketInput{ - Bucket: aws.String(bucket), - }) - if err != nil { - return err - } - - return nil + // Create S3 service client + svc := s3.New(sess) + + // Do we have this Bucket? + _, err := svc.HeadBucket(&s3.HeadBucketInput{ + Bucket: aws.String(bucket), + }) + if err != nil { + return err + } + + return nil } // HasACL determines whether the bucket has read-only ACL func HasACL(sess *session.Session, bucket string) error { - // Create S3 service client - svc := s3.New(sess) - - acl, err := svc.GetBucketAcl(&s3.GetBucketAclInput{ - Bucket: aws.String(bucket), - }) - if err != nil { - return err - } - - // Determine whether the group allusers has read permission - for _, g := range acl.Grants { - if *g.Grantee.Type == "Group" && *g.Grantee.URI == "http://acs.amazonaws.com/groups/global/AllUsers" && *g.Permission == "READ" { - return nil - } - } - - return errors.New("All users do not have read access") + // Create S3 service client + svc := s3.New(sess) + + acl, err := svc.GetBucketAcl(&s3.GetBucketAclInput{ + Bucket: aws.String(bucket), + }) + if err != nil { + return err + } + + // Determine whether the group allusers has read permission + for _, g := range acl.Grants { + if *g.Grantee.Type == "Group" && *g.Grantee.URI == "http://acs.amazonaws.com/groups/global/AllUsers" && *g.Permission == "READ" { + return nil + } + } + + return errors.New("All users do not have read access") } // UpdateBucket changes the bucket to give all users read permission func UpdateBucket(sess *session.Session, bucket string) error { - // Create S3 service client - svc := s3.New(sess) - - // Give all users read permission - _, err := svc.PutBucketAcl(&s3.PutBucketAclInput{ - ACL: aws.String("public-read"), - Bucket: aws.String(bucket), - }) - if err != nil { - return err - } - - // Do all users have read permission? - err = HasACL(sess, bucket) - if err != nil { - return err - } - - return nil + // Create S3 service client + svc := s3.New(sess) + + // Give all users read permission + _, err := svc.PutBucketAcl(&s3.PutBucketAclInput{ + ACL: aws.String("public-read"), + Bucket: aws.String(bucket), + }) + if err != nil { + return err + } + + // Do all users have read permission? + err = HasACL(sess, bucket) + if err != nil { + return err + } + + return nil } // DeleteBucket deletes a bucket func DeleteBucket(sess *session.Session, bucket string) error { - // Create S3 service client - svc := s3.New(sess) - - // Delete the S3 Bucket - _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: aws.String(bucket), - }) - if err != nil { - return err - } - - // Wait until bucket is gone before finishing - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: aws.String(bucket), - }) - if err != nil { - return err - } - - // Make sure it's really gone - _, err = svc.HeadBucket(&s3.HeadBucketInput{ - Bucket: aws.String(bucket), - }) - // We expect this to fail if bucket does not exist - if err != nil { - return nil - } - - return errors.New("Could not delete bucket") + // Create S3 service client + svc := s3.New(sess) + + // Delete the S3 Bucket + _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: aws.String(bucket), + }) + if err != nil { + return err + } + + // Wait until bucket is gone before finishing + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: aws.String(bucket), + }) + if err != nil { + return err + } + + // Make sure it's really gone + _, err = svc.HeadBucket(&s3.HeadBucketInput{ + Bucket: aws.String(bucket), + }) + // We expect this to fail if bucket does not exist + if err != nil { + return nil + } + + return errors.New("Could not delete bucket") } func main() {} diff --git a/go/example_code/s3/crud/s3_crud_ops_test.go b/go/example_code/s3/crud/s3_crud_ops_test.go index 33fe41ede5f..19faacd017c 100644 --- a/go/example_code/s3/crud/s3_crud_ops_test.go +++ b/go/example_code/s3/crud/s3_crud_ops_test.go @@ -1,25 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[s3_crud_ops_test.go tests functions in s3_crud_ops.go.] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-05-21] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main diff --git a/go/example_code/s3/delete-buckets-by-prefix/s3_delete_buckets.go b/go/example_code/s3/delete-buckets-by-prefix/s3_delete_buckets.go index 403af117210..b4796602f42 100644 --- a/go/example_code/s3/delete-buckets-by-prefix/s3_delete_buckets.go +++ b/go/example_code/s3/delete-buckets-by-prefix/s3_delete_buckets.go @@ -1,16 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( @@ -76,7 +65,8 @@ func deleteBucketsByPrefix(sess *session.Session, prefix string) error { // that start with the given text // // Usage: -// go run s3_delete_buckets -p PREFIX +// +// go run s3_delete_buckets -p PREFIX func main() { prefixPtr := flag.String("p", "", "The prefix of the buckets to delete") flag.Parse() diff --git a/go/example_code/s3/delete-buckets-by-prefix/s3_delete_buckets_test.go b/go/example_code/s3/delete-buckets-by-prefix/s3_delete_buckets_test.go index c7406c95e14..b27380bd0d0 100644 --- a/go/example_code/s3/delete-buckets-by-prefix/s3_delete_buckets_test.go +++ b/go/example_code/s3/delete-buckets-by-prefix/s3_delete_buckets_test.go @@ -1,16 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( diff --git a/go/example_code/s3/enforce_content_md5.go b/go/example_code/s3/enforce_content_md5.go index d3ae6102842..c74d0cb6d96 100644 --- a/go/example_code/s3/enforce_content_md5.go +++ b/go/example_code/s3/enforce_content_md5.go @@ -1,82 +1,61 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Enforces MD5 checksum on items uploaded to an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[PutObjectRequest function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "encoding/base64" - "fmt" - "crypto/md5" - "strings" - "time" - "net/http" + "crypto/md5" + "encoding/base64" + "fmt" + "net/http" + "strings" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) // Downloads an item from an S3 Bucket in the region configured in the shared config // or AWS_REGION environment variable. // // Usage: -// go run s3_download.go +// +// go run s3_download.go func main() { - h := md5.New() - content := strings.NewReader("") - content.WriteTo(h) - - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create S3 service client - svc := s3.New(sess) - - resp, _ := svc.PutObjectRequest(&s3.PutObjectInput{ - Bucket: aws.String("testBucket"), - Key: aws.String("testKey"), - }) - - md5s := base64.StdEncoding.EncodeToString(h.Sum(nil)) - resp.HTTPRequest.Header.Set("Content-MD5", md5s) - - url, err := resp.Presign(15 * time.Minute) - if err != nil { - fmt.Println("error presigning request", err) - return - } - - req, err := http.NewRequest("PUT", url, strings.NewReader("")) - req.Header.Set("Content-MD5", md5s) - if err != nil { - fmt.Println("error creating request", url) - return - } - - defClient, err := http.DefaultClient.Do(req) - fmt.Println(defClient, err) + h := md5.New() + content := strings.NewReader("") + content.WriteTo(h) + + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create S3 service client + svc := s3.New(sess) + + resp, _ := svc.PutObjectRequest(&s3.PutObjectInput{ + Bucket: aws.String("testBucket"), + Key: aws.String("testKey"), + }) + + md5s := base64.StdEncoding.EncodeToString(h.Sum(nil)) + resp.HTTPRequest.Header.Set("Content-MD5", md5s) + + url, err := resp.Presign(15 * time.Minute) + if err != nil { + fmt.Println("error presigning request", err) + return + } + + req, err := http.NewRequest("PUT", url, strings.NewReader("")) + req.Header.Set("Content-MD5", md5s) + if err != nil { + fmt.Println("error creating request", url) + return + } + + defClient, err := http.DefaultClient.Do(req) + fmt.Println(defClient, err) } diff --git a/go/example_code/s3/generate_presigned_url.go b/go/example_code/s3/generate_presigned_url.go index 8bf3a1bf6a0..07bfdbbb9f8 100644 --- a/go/example_code/s3/generate_presigned_url.go +++ b/go/example_code/s3/generate_presigned_url.go @@ -1,61 +1,40 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Generates a pre-signed URL for an S3 bucket item.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[GetObjectRequest function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "log" - "time" + "log" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) // Downloads an item from an S3 Bucket // // Usage: -// go run s3_download.go +// +// go run s3_download.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create S3 service client - svc := s3.New(sess) - - req, _ := svc.GetObjectRequest(&s3.GetObjectInput{ - Bucket: aws.String("myBucket"), - Key: aws.String("myKey"), - }) - urlStr, err := req.Presign(15 * time.Minute) - - if err != nil { - log.Println("Failed to sign request", err) - } - - log.Println("The URL is", urlStr) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create S3 service client + svc := s3.New(sess) + + req, _ := svc.GetObjectRequest(&s3.GetObjectInput{ + Bucket: aws.String("myBucket"), + Key: aws.String("myKey"), + }) + urlStr, err := req.Presign(15 * time.Minute) + + if err != nil { + log.Println("Failed to sign request", err) + } + + log.Println("The URL is", urlStr) } diff --git a/go/example_code/s3/generate_presigned_url_specific_payload.go b/go/example_code/s3/generate_presigned_url_specific_payload.go index fe871745aaf..2c777cc9afc 100644 --- a/go/example_code/s3/generate_presigned_url_specific_payload.go +++ b/go/example_code/s3/generate_presigned_url_specific_payload.go @@ -1,55 +1,33 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Generates a pre-signed URL for a PUT operation that checks whether the expected content was uploaded.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[PutObjectRequest function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "log" - "strings" - "time" + "log" + "strings" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create S3 service client - svc := s3.New(sess) - - req, _ := svc.PutObjectRequest(&s3.PutObjectInput{ - Bucket: aws.String("myBucket"), - Key: aws.String("myKey"), - Body: strings.NewReader("EXPECTED CONTENTS"), - }) - str, err := req.Presign(15 * time.Minute) - - log.Println("The URL is:", str, " err:", err) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create S3 service client + svc := s3.New(sess) + + req, _ := svc.PutObjectRequest(&s3.PutObjectInput{ + Bucket: aws.String("myBucket"), + Key: aws.String("myKey"), + Body: strings.NewReader("EXPECTED CONTENTS"), + }) + str, err := req.Presign(15 * time.Minute) + + log.Println("The URL is:", str, " err:", err) } diff --git a/go/example_code/s3/list_all_buckets.go b/go/example_code/s3/list_all_buckets.go index 9c971434cc1..dfb014397ea 100644 --- a/go/example_code/s3/list_all_buckets.go +++ b/go/example_code/s3/list_all_buckets.go @@ -1,56 +1,34 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Lists all of your S3 buckets.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[ListBuckets function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "log" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create S3 service client - svc := s3.New(sess) - - result, err := svc.ListBuckets(&s3.ListBucketsInput{}) - if err != nil { - log.Println("Failed to list buckets", err) - return - } - - log.Println("Buckets:") - - for _, bucket := range result.Buckets { - log.Printf("%s : %s\n", aws.StringValue(bucket.Name), bucket.CreationDate) - } + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create S3 service client + svc := s3.New(sess) + + result, err := svc.ListBuckets(&s3.ListBucketsInput{}) + if err != nil { + log.Println("Failed to list buckets", err) + return + } + + log.Println("Buckets:") + + for _, bucket := range result.Buckets { + log.Printf("%s : %s\n", aws.StringValue(bucket.Name), bucket.CreationDate) + } } diff --git a/go/example_code/s3/s3.go b/go/example_code/s3/s3.go index 5f9f35635b4..674af18b669 100644 --- a/go/example_code/s3/s3.go +++ b/go/example_code/s3/s3.go @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * @@ -10,115 +12,105 @@ * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. -*/ -// snippet-sourcedescription:[s3.go demonstrates how to list, create, and delete a bucket in Amazon S3.] -// snippet-service:[s3] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ListBuckets] -// snippet-keyword:[CreateBucket] -// snippet-keyword:[DeleteBucket] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2017-07-11] -// snippet-sourceauthor:[AWS] + */ // snippet-start:[s3.go.bucket_operations.list_create_delete] package main import ( - "fmt" - "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "fmt" + "os" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) func main() { - if len(os.Args) < 3 { - fmt.Printf("Usage: go run s3.go \n" + - "Example: go run s3.go my-test-bucket us-east-2\n") - os.Exit(1) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - svc := s3.New(sess, &aws.Config{ - Region: aws.String(os.Args[2]), - }) - - listMyBuckets(svc) - createMyBucket(svc, os.Args[1], os.Args[2]) - listMyBuckets(svc) - deleteMyBucket(svc, os.Args[1]) - listMyBuckets(svc) + if len(os.Args) < 3 { + fmt.Printf("Usage: go run s3.go \n" + + "Example: go run s3.go my-test-bucket us-east-2\n") + os.Exit(1) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + svc := s3.New(sess, &aws.Config{ + Region: aws.String(os.Args[2]), + }) + + listMyBuckets(svc) + createMyBucket(svc, os.Args[1], os.Args[2]) + listMyBuckets(svc) + deleteMyBucket(svc, os.Args[1]) + listMyBuckets(svc) } // List all of your available buckets in this AWS Region. func listMyBuckets(svc *s3.S3) { - result, err := svc.ListBuckets(nil) + result, err := svc.ListBuckets(nil) - if err != nil { - exitErrorf("Unable to list buckets, %v", err) - } + if err != nil { + exitErrorf("Unable to list buckets, %v", err) + } - fmt.Println("My buckets now are:\n") + fmt.Println("My buckets now are:\n") - for _, b := range result.Buckets { - fmt.Printf(aws.StringValue(b.Name) + "\n") - } + for _, b := range result.Buckets { + fmt.Printf(aws.StringValue(b.Name) + "\n") + } - fmt.Printf("\n") + fmt.Printf("\n") } // Create a bucket in this AWS Region. func createMyBucket(svc *s3.S3, bucketName string, region string) { - fmt.Printf("\nCreating a new bucket named '" + bucketName + "'...\n\n") - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: aws.String(bucketName), - CreateBucketConfiguration: &s3.CreateBucketConfiguration{ - LocationConstraint: aws.String(region), - }, - }) - - if err != nil { - exitErrorf("Unable to create bucket, %v", err) - } - - // Wait until bucket is created before finishing - fmt.Printf("Waiting for bucket %q to be created...\n", bucketName) - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: aws.String(bucketName), - }) + fmt.Printf("\nCreating a new bucket named '" + bucketName + "'...\n\n") + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: aws.String(bucketName), + CreateBucketConfiguration: &s3.CreateBucketConfiguration{ + LocationConstraint: aws.String(region), + }, + }) + + if err != nil { + exitErrorf("Unable to create bucket, %v", err) + } + + // Wait until bucket is created before finishing + fmt.Printf("Waiting for bucket %q to be created...\n", bucketName) + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: aws.String(bucketName), + }) } // Delete the bucket you just created. func deleteMyBucket(svc *s3.S3, bucketName string) { - fmt.Printf("\nDeleting the bucket named '" + bucketName + "'...\n\n") - - _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: aws.String(bucketName), - }) - - if err != nil { - exitErrorf("Unable to delete bucket, %v", err) - } - - // Wait until bucket is deleted before finishing - fmt.Printf("Waiting for bucket %q to be deleted...\n", bucketName) - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: aws.String(bucketName), - }) + fmt.Printf("\nDeleting the bucket named '" + bucketName + "'...\n\n") + + _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: aws.String(bucketName), + }) + + if err != nil { + exitErrorf("Unable to delete bucket, %v", err) + } + + // Wait until bucket is deleted before finishing + fmt.Printf("Waiting for bucket %q to be deleted...\n", bucketName) + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: aws.String(bucketName), + }) } // If there's an error, display it. func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } + // snippet-end:[s3.go.bucket_operations.list_create_delete] diff --git a/go/example_code/s3/s3_copy_object.go b/go/example_code/s3/s3_copy_object.go index 65018409056..33987e5b1cc 100644 --- a/go/example_code/s3/s3_copy_object.go +++ b/go/example_code/s3/s3_copy_object.go @@ -1,82 +1,60 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Copies a bucket item to another bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[CopyObject function] -// snippet-keyword:[WaitUntilObjectExists function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "fmt" - "net/url" - "os" + "fmt" + "net/url" + "os" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) // Copies the item in the bucket to another bucket. // // Usage: -// go run s3_copy_object.go BUCKET ITEM OTHER_BUCKET +// +// go run s3_copy_object.go BUCKET ITEM OTHER_BUCKET func main() { - if len(os.Args) != 4 { - exitErrorf("Bucket, item, and other bucket names required\nUsage: go run s3_copy_object bucket item other-bucket") - } - - bucket := os.Args[1] - item := os.Args[2] - other := os.Args[3] - - source := bucket + "/" + item - - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create S3 service client - svc := s3.New(sess) - - // Copy the item - _, err = svc.CopyObject(&s3.CopyObjectInput{Bucket: aws.String(other), - CopySource: aws.String(url.QueryEscape(source)), Key: aws.String(item)}) - if err != nil { - exitErrorf("Unable to copy item from bucket %q to bucket %q, %v", bucket, other, err) - } - - // Wait to see if the item got copied - err = svc.WaitUntilObjectExists(&s3.HeadObjectInput{Bucket: aws.String(other), Key: aws.String(item)}) - if err != nil { - exitErrorf("Error occurred while waiting for item %q to be copied to bucket %q, %v", bucket, item, other, err) - } - - fmt.Printf("Item %q successfully copied from bucket %q to bucket %q\n", item, bucket, other) + if len(os.Args) != 4 { + exitErrorf("Bucket, item, and other bucket names required\nUsage: go run s3_copy_object bucket item other-bucket") + } + + bucket := os.Args[1] + item := os.Args[2] + other := os.Args[3] + + source := bucket + "/" + item + + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create S3 service client + svc := s3.New(sess) + + // Copy the item + _, err = svc.CopyObject(&s3.CopyObjectInput{Bucket: aws.String(other), + CopySource: aws.String(url.QueryEscape(source)), Key: aws.String(item)}) + if err != nil { + exitErrorf("Unable to copy item from bucket %q to bucket %q, %v", bucket, other, err) + } + + // Wait to see if the item got copied + err = svc.WaitUntilObjectExists(&s3.HeadObjectInput{Bucket: aws.String(other), Key: aws.String(item)}) + if err != nil { + exitErrorf("Error occurred while waiting for item %q to be copied to bucket %q, %v", bucket, item, other, err) + } + + fmt.Printf("Item %q successfully copied from bucket %q to bucket %q\n", item, bucket, other) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/s3/s3_create_bucket.go b/go/example_code/s3/s3_create_bucket.go index 5301a640d0e..03d87c1cb24 100644 --- a/go/example_code/s3/s3_create_bucket.go +++ b/go/example_code/s3/s3_create_bucket.go @@ -1,83 +1,61 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Creates an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[CreateBucket function] -// snippet-keyword:[WaitUntilBucketExists function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "fmt" - "os" + "fmt" + "os" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) // Creates an S3 Bucket in the region configured in the shared config // or AWS_REGION environment variable. // // Usage: -// go run s3_create_bucket BUCKET_NAME +// +// go run s3_create_bucket BUCKET_NAME func main() { - if len(os.Args) != 2 { - exitErrorf("Bucket name missing!\nUsage: %s bucket_name", os.Args[0]) - } - - bucket := os.Args[1] - - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create S3 service client - svc := s3.New(sess) - - // Create the S3 Bucket - _, err = svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: aws.String(bucket), - }) - if err != nil { - exitErrorf("Unable to create bucket %q, %v", bucket, err) - } - - // Wait until bucket is created before finishing - fmt.Printf("Waiting for bucket %q to be created...\n", bucket) - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: aws.String(bucket), - }) - if err != nil { - exitErrorf("Error occurred while waiting for bucket to be created, %v", bucket) - } - - fmt.Printf("Bucket %q successfully created\n", bucket) + if len(os.Args) != 2 { + exitErrorf("Bucket name missing!\nUsage: %s bucket_name", os.Args[0]) + } + + bucket := os.Args[1] + + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create S3 service client + svc := s3.New(sess) + + // Create the S3 Bucket + _, err = svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: aws.String(bucket), + }) + if err != nil { + exitErrorf("Unable to create bucket %q, %v", bucket, err) + } + + // Wait until bucket is created before finishing + fmt.Printf("Waiting for bucket %q to be created...\n", bucket) + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: aws.String(bucket), + }) + if err != nil { + exitErrorf("Error occurred while waiting for bucket to be created, %v", bucket) + } + + fmt.Printf("Bucket %q successfully created\n", bucket) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/s3/s3_delete_bucket.go b/go/example_code/s3/s3_delete_bucket.go index 82ff591bc27..8510f087fd6 100644 --- a/go/example_code/s3/s3_delete_bucket.go +++ b/go/example_code/s3/s3_delete_bucket.go @@ -1,84 +1,62 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Deletes an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[DeleteBucket function] -// snippet-keyword:[WaitUntilBucketNotExists function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "fmt" - "os" + "fmt" + "os" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) // Deletes an S3 Bucket in the region configured in the shared config // or AWS_REGION environment variable. // // Usage: -// go run s3_delete_bucket BUCKET_NAME +// +// go run s3_delete_bucket BUCKET_NAME func main() { - if len(os.Args) != 2 { - exitErrorf("bucket name required\nUsage: %s bucket_name", os.Args[0]) - } - - bucket := os.Args[1] - - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create S3 service client - svc := s3.New(sess) - - // Delete the S3 Bucket - // It must be empty or else the call fails - _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: aws.String(bucket), - }) - if err != nil { - exitErrorf("Unable to delete bucket %q, %v", bucket, err) - } - - // Wait until bucket is deleted before finishing - fmt.Printf("Waiting for bucket %q to be deleted...\n", bucket) - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: aws.String(bucket), - }) - if err != nil { - exitErrorf("Error occurred while waiting for bucket to be deleted, %v", bucket) - } - - fmt.Printf("Bucket %q successfully deleted\n", bucket) + if len(os.Args) != 2 { + exitErrorf("bucket name required\nUsage: %s bucket_name", os.Args[0]) + } + + bucket := os.Args[1] + + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create S3 service client + svc := s3.New(sess) + + // Delete the S3 Bucket + // It must be empty or else the call fails + _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: aws.String(bucket), + }) + if err != nil { + exitErrorf("Unable to delete bucket %q, %v", bucket, err) + } + + // Wait until bucket is deleted before finishing + fmt.Printf("Waiting for bucket %q to be deleted...\n", bucket) + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: aws.String(bucket), + }) + if err != nil { + exitErrorf("Error occurred while waiting for bucket to be deleted, %v", bucket) + } + + fmt.Printf("Bucket %q successfully deleted\n", bucket) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/s3/s3_delete_bucket_policy.go b/go/example_code/s3/s3_delete_bucket_policy.go index 9722472baed..cc86be33b08 100644 --- a/go/example_code/s3/s3_delete_bucket_policy.go +++ b/go/example_code/s3/s3_delete_bucket_policy.go @@ -1,79 +1,58 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Deletes a policy for an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[DeleteBucketPolicy function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "fmt" - "os" - "path/filepath" + "fmt" + "os" + "path/filepath" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) // Deletes the policy on a bucket. If the bucket doesn't exist, or there was // and error an error message will be printed instead. // // Usage: -// go run s3_delete_bucket_policy.go BUCKET_NAME +// +// go run s3_delete_bucket_policy.go BUCKET_NAME func main() { - if len(os.Args) != 2 { - exitErrorf("bucket name required\nUsage: %s bucket_name", - filepath.Base(os.Args[0])) - } - bucket := os.Args[1] - - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create S3 service client - svc := s3.New(sess) - - // Call S3 to delete the policy on the bucket. - _, err = svc.DeleteBucketPolicy(&s3.DeleteBucketPolicyInput{ - Bucket: aws.String(bucket), - }) - if err != nil { - if aerr, ok := err.(awserr.Error); ok && aerr.Code() == s3.ErrCodeNoSuchBucket { - // Special error handling for the when the bucket doesn't - // exists so we can give a more direct error message from the CLI. - exitErrorf("Bucket %q does not exist", bucket) - } - exitErrorf("Unable to delete bucket %q policy, %v", bucket, err) - } - - fmt.Printf("Successfully deleted the policy on bucket %q.\n", bucket) + if len(os.Args) != 2 { + exitErrorf("bucket name required\nUsage: %s bucket_name", + filepath.Base(os.Args[0])) + } + bucket := os.Args[1] + + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create S3 service client + svc := s3.New(sess) + + // Call S3 to delete the policy on the bucket. + _, err = svc.DeleteBucketPolicy(&s3.DeleteBucketPolicyInput{ + Bucket: aws.String(bucket), + }) + if err != nil { + if aerr, ok := err.(awserr.Error); ok && aerr.Code() == s3.ErrCodeNoSuchBucket { + // Special error handling for the when the bucket doesn't + // exists so we can give a more direct error message from the CLI. + exitErrorf("Bucket %q does not exist", bucket) + } + exitErrorf("Unable to delete bucket %q policy, %v", bucket, err) + } + + fmt.Printf("Successfully deleted the policy on bucket %q.\n", bucket) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/s3/s3_delete_bucket_website.go b/go/example_code/s3/s3_delete_bucket_website.go index 960e6ad8ecf..2cf4a938d0e 100644 --- a/go/example_code/s3/s3_delete_bucket_website.go +++ b/go/example_code/s3/s3_delete_bucket_website.go @@ -1,38 +1,16 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Deletes the website configuration on an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[DeleteBucketWebsite function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "fmt" - "os" - "path/filepath" + "fmt" + "os" + "path/filepath" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) // Deletes the bucket's website configuration. Allows setting the index suffix, @@ -43,39 +21,40 @@ import ( // that configuration // // Usage: -// go run s3_delete_bucket_website.go BUCKET_NAME +// +// go run s3_delete_bucket_website.go BUCKET_NAME func main() { - if len(os.Args) != 2 { - exitErrorf("bucket name required\nUsage: %s bucket_name", - filepath.Base(os.Args[0])) - } - - bucket := os.Args[1] - - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create S3 service client - svc := s3.New(sess) - - // Deletes the website configuration on the bucket. Will return successfully - // when the website configuration was deleted, or if the bucket does not - // have a website configuration. - _, err = svc.DeleteBucketWebsite(&s3.DeleteBucketWebsiteInput{ - Bucket: aws.String(bucket), - }) - if err != nil { - exitErrorf("Unable to delete bucket %q website configuration, %v", - bucket, err) - } - - fmt.Printf("Successfully delete bucket %q website configuration\n", bucket) + if len(os.Args) != 2 { + exitErrorf("bucket name required\nUsage: %s bucket_name", + filepath.Base(os.Args[0])) + } + + bucket := os.Args[1] + + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create S3 service client + svc := s3.New(sess) + + // Deletes the website configuration on the bucket. Will return successfully + // when the website configuration was deleted, or if the bucket does not + // have a website configuration. + _, err = svc.DeleteBucketWebsite(&s3.DeleteBucketWebsiteInput{ + Bucket: aws.String(bucket), + }) + if err != nil { + exitErrorf("Unable to delete bucket %q website configuration, %v", + bucket, err) + } + + fmt.Printf("Successfully delete bucket %q website configuration\n", bucket) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/s3/s3_delete_object.go b/go/example_code/s3/s3_delete_object.go index 4afe2e5c193..a9a343b8686 100644 --- a/go/example_code/s3/s3_delete_object.go +++ b/go/example_code/s3/s3_delete_object.go @@ -1,81 +1,59 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Deletes an item from an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[DeleteObject function] -// snippet-keyword:[WaitUntilObjectNotExists function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "fmt" - "os" + "fmt" + "os" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) // Deletes the specified object in the specified S3 Bucket in the region configured in the shared config // or AWS_REGION environment variable. // // Usage: -// go run s3_delete_object BUCKET_NAME OBJECT_NAME +// +// go run s3_delete_object BUCKET_NAME OBJECT_NAME func main() { - if len(os.Args) != 3 { - exitErrorf("Bucket and object name required\nUsage: %s bucket_name object_name", - os.Args[0]) - } - - bucket := os.Args[1] - obj := os.Args[2] - - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create S3 service client - svc := s3.New(sess) - - // Delete the item - _, err = svc.DeleteObject(&s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: aws.String(obj)}) - if err != nil { - exitErrorf("Unable to delete object %q from bucket %q, %v", obj, bucket, err) - } - - err = svc.WaitUntilObjectNotExists(&s3.HeadObjectInput{ - Bucket: aws.String(bucket), - Key: aws.String(obj), - }) - if err != nil { - exitErrorf("Error occurred while waiting for object %q to be deleted, %v", obj, err) - } - - fmt.Printf("Object %q successfully deleted\n", obj) + if len(os.Args) != 3 { + exitErrorf("Bucket and object name required\nUsage: %s bucket_name object_name", + os.Args[0]) + } + + bucket := os.Args[1] + obj := os.Args[2] + + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create S3 service client + svc := s3.New(sess) + + // Delete the item + _, err = svc.DeleteObject(&s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: aws.String(obj)}) + if err != nil { + exitErrorf("Unable to delete object %q from bucket %q, %v", obj, bucket, err) + } + + err = svc.WaitUntilObjectNotExists(&s3.HeadObjectInput{ + Bucket: aws.String(bucket), + Key: aws.String(obj), + }) + if err != nil { + exitErrorf("Error occurred while waiting for object %q to be deleted, %v", obj, err) + } + + fmt.Printf("Object %q successfully deleted\n", obj) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/s3/s3_delete_objects.go b/go/example_code/s3/s3_delete_objects.go index e7406a78114..5f1eec145ba 100644 --- a/go/example_code/s3/s3_delete_objects.go +++ b/go/example_code/s3/s3_delete_objects.go @@ -1,77 +1,54 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Deletes all of the items in an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[s3manager.NewBatchDeleteWithClient function] -// snippet-keyword:[s3manager.NewDeleteListIterator function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - - "fmt" - "os" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + + "fmt" + "os" ) // Deletes all of the objects in the specified S3 Bucket in the region configured in the shared config // or AWS_REGION environment variable. // // Usage: -// go run s3_delete_objects BUCKET +// +// go run s3_delete_objects BUCKET func main() { - if len(os.Args) != 2 { - exitErrorf("Bucket name required\nUsage: %s BUCKET", os.Args[0]) - } + if len(os.Args) != 2 { + exitErrorf("Bucket name required\nUsage: %s BUCKET", os.Args[0]) + } - bucket := os.Args[1] + bucket := os.Args[1] - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, _ := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, _ := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) - // Create S3 service client - svc := s3.New(sess) + // Create S3 service client + svc := s3.New(sess) - // Setup BatchDeleteIterator to iterate through a list of objects. - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: aws.String(bucket), - }) + // Setup BatchDeleteIterator to iterate through a list of objects. + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: aws.String(bucket), + }) - // Traverse iterator deleting each object - if err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter); err != nil { - exitErrorf("Unable to delete objects from bucket %q, %v", bucket, err) - } + // Traverse iterator deleting each object + if err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter); err != nil { + exitErrorf("Unable to delete objects from bucket %q, %v", bucket, err) + } - fmt.Printf("Deleted object(s) from bucket: %s", bucket) + fmt.Printf("Deleted object(s) from bucket: %s", bucket) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/s3/s3_download_object.go b/go/example_code/s3/s3_download_object.go index f56d4d2433a..ba9f6c2b8bd 100644 --- a/go/example_code/s3/s3_download_object.go +++ b/go/example_code/s3/s3_download_object.go @@ -1,84 +1,61 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[s3manager.NewDownloader] -// snippet-keyword:[Download function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - - "fmt" - "os" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + + "fmt" + "os" ) // Downloads an item from an S3 Bucket in the region configured in the shared config // or AWS_REGION environment variable. // // Usage: -// go run s3_download_object.go BUCKET ITEM +// +// go run s3_download_object.go BUCKET ITEM func main() { - if len(os.Args) != 3 { - exitErrorf("Bucket and item names required\nUsage: %s bucket_name item_name", - os.Args[0]) - } - - bucket := os.Args[1] - item := os.Args[2] - - file, err := os.Create(item) - if err != nil { - exitErrorf("Unable to open file %q, %v", item, err) - } - - defer file.Close() - - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, _ := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - downloader := s3manager.NewDownloader(sess) - - numBytes, err := downloader.Download(file, - &s3.GetObjectInput{ - Bucket: aws.String(bucket), - Key: aws.String(item), - }) - if err != nil { - exitErrorf("Unable to download item %q, %v", item, err) - } - - fmt.Println("Downloaded", file.Name(), numBytes, "bytes") + if len(os.Args) != 3 { + exitErrorf("Bucket and item names required\nUsage: %s bucket_name item_name", + os.Args[0]) + } + + bucket := os.Args[1] + item := os.Args[2] + + file, err := os.Create(item) + if err != nil { + exitErrorf("Unable to open file %q, %v", item, err) + } + + defer file.Close() + + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, _ := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + downloader := s3manager.NewDownloader(sess) + + numBytes, err := downloader.Download(file, + &s3.GetObjectInput{ + Bucket: aws.String(bucket), + Key: aws.String(item), + }) + if err != nil { + exitErrorf("Unable to download item %q, %v", item, err) + } + + fmt.Println("Downloaded", file.Name(), numBytes, "bytes") } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/s3/s3_encrypt_on_server_with_kms.go b/go/example_code/s3/s3_encrypt_on_server_with_kms.go index 9409e77f509..9b5eddf0ca5 100644 --- a/go/example_code/s3/s3_encrypt_on_server_with_kms.go +++ b/go/example_code/s3/s3_encrypt_on_server_with_kms.go @@ -1,74 +1,51 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Adds an item to an S3 bucket with server-side encryption set to AWS KMS.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[PutObject function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" - "fmt" - "os" - "strings" + "fmt" + "os" + "strings" ) func main() { - if len(os.Args) != 2 { - fmt.Println("You must supply a key") - os.Exit(1) - } - - key := os.Args[1] - bucket := "myBucket" - object := "myItem" - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := s3.New(sess) - - input := &s3.PutObjectInput{ - Body: strings.NewReader(object), - Bucket: aws.String(bucket), - Key: aws.String(object), - ServerSideEncryption: aws.String("aws:kms"), - SSEKMSKeyId: aws.String(key), - } - - _, err := svc.PutObject(input) - if err != nil { - fmt.Println("Got an error adding object to bucket") - fmt.Println(err.Error()) - os.Exit(1) - } - - fmt.Println("Added object " + object + " to bucket " + bucket + " with AWS KMS encryption") + if len(os.Args) != 2 { + fmt.Println("You must supply a key") + os.Exit(1) + } + + key := os.Args[1] + bucket := "myBucket" + object := "myItem" + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := s3.New(sess) + + input := &s3.PutObjectInput{ + Body: strings.NewReader(object), + Bucket: aws.String(bucket), + Key: aws.String(object), + ServerSideEncryption: aws.String("aws:kms"), + SSEKMSKeyId: aws.String(key), + } + + _, err := svc.PutObject(input) + if err != nil { + fmt.Println("Got an error adding object to bucket") + fmt.Println(err.Error()) + os.Exit(1) + } + + fmt.Println("Added object " + object + " to bucket " + bucket + " with AWS KMS encryption") } diff --git a/go/example_code/s3/s3_get_bucket_acl.go b/go/example_code/s3/s3_get_bucket_acl.go index 1f8465292e6..9c5391ea73f 100644 --- a/go/example_code/s3/s3_get_bucket_acl.go +++ b/go/example_code/s3/s3_get_bucket_acl.go @@ -1,84 +1,62 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Gets the ACLs for an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[GetBucketAcl function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - - "fmt" - "os" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + + "fmt" + "os" ) // Gets the ACL for a bucket // // Usage: -// go run s3_get_bucket_acl.go BUCKET +// +// go run s3_get_bucket_acl.go BUCKET func main() { - if len(os.Args) != 2 { - exitErrorf("Bucket name required\nUsage: go run", os.Args[0], "BUCKET") - } - - bucket := os.Args[1] - - // Initialize a session that loads credentials from the shared credentials file ~/.aws/credentials - // and the region from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create S3 service client - svc := s3.New(sess) - - // Get bucket ACL - result, err := svc.GetBucketAcl(&s3.GetBucketAclInput{Bucket: &bucket}) - if err != nil { - exitErrorf(err.Error()) - } - - fmt.Println("Owner:", *result.Owner.DisplayName) - fmt.Println("") - fmt.Println("Grants") - - for _, g := range result.Grants { - // If we add a canned ACL, the name is nil - if g.Grantee.DisplayName == nil { - fmt.Println(" Grantee: EVERYONE") - } else { - fmt.Println(" Grantee: ", *g.Grantee.DisplayName) - } - - fmt.Println(" Type: ", *g.Grantee.Type) - fmt.Println(" Permission:", *g.Permission) - fmt.Println("") - } + if len(os.Args) != 2 { + exitErrorf("Bucket name required\nUsage: go run", os.Args[0], "BUCKET") + } + + bucket := os.Args[1] + + // Initialize a session that loads credentials from the shared credentials file ~/.aws/credentials + // and the region from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create S3 service client + svc := s3.New(sess) + + // Get bucket ACL + result, err := svc.GetBucketAcl(&s3.GetBucketAclInput{Bucket: &bucket}) + if err != nil { + exitErrorf(err.Error()) + } + + fmt.Println("Owner:", *result.Owner.DisplayName) + fmt.Println("") + fmt.Println("Grants") + + for _, g := range result.Grants { + // If we add a canned ACL, the name is nil + if g.Grantee.DisplayName == nil { + fmt.Println(" Grantee: EVERYONE") + } else { + fmt.Println(" Grantee: ", *g.Grantee.DisplayName) + } + + fmt.Println(" Type: ", *g.Grantee.Type) + fmt.Println(" Permission:", *g.Permission) + fmt.Println("") + } } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/s3/s3_get_bucket_object_acl.go b/go/example_code/s3/s3_get_bucket_object_acl.go index 8b3bcaf23d7..939dcd91584 100644 --- a/go/example_code/s3/s3_get_bucket_object_acl.go +++ b/go/example_code/s3/s3_get_bucket_object_acl.go @@ -1,79 +1,57 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Gets the ACLs for an S3 bucket item.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[GetObjectAcl function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - - "fmt" - "os" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + + "fmt" + "os" ) // Gets the ACL for a bucket object // // Usage: -// go run s3_get_bucket_object_acl.go BUCKET OBJECT +// +// go run s3_get_bucket_object_acl.go BUCKET OBJECT func main() { - if len(os.Args) != 3 { - exitErrorf("Bucket and object names required\nUsage: go run", os.Args[0], "BUCKET OBJECT") - } - - bucket := os.Args[1] - key := os.Args[2] - - // Initialize a session that loads credentials from the shared credentials file ~/.aws/credentials - // and the region from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create S3 service client - svc := s3.New(sess) - - // Get bucket ACL - result, err := svc.GetObjectAcl(&s3.GetObjectAclInput{Bucket: &bucket, Key: &key}) - if err != nil { - exitErrorf(err.Error()) - } - - fmt.Println("Owner:", *result.Owner.DisplayName) - fmt.Println("") - fmt.Println("Grants") - - for _, g := range result.Grants { - fmt.Println(" Grantee: ", *g.Grantee.DisplayName) - fmt.Println(" Type: ", *g.Grantee.Type) - fmt.Println(" Permission:", *g.Permission) - fmt.Println("") - } + if len(os.Args) != 3 { + exitErrorf("Bucket and object names required\nUsage: go run", os.Args[0], "BUCKET OBJECT") + } + + bucket := os.Args[1] + key := os.Args[2] + + // Initialize a session that loads credentials from the shared credentials file ~/.aws/credentials + // and the region from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create S3 service client + svc := s3.New(sess) + + // Get bucket ACL + result, err := svc.GetObjectAcl(&s3.GetObjectAclInput{Bucket: &bucket, Key: &key}) + if err != nil { + exitErrorf(err.Error()) + } + + fmt.Println("Owner:", *result.Owner.DisplayName) + fmt.Println("") + fmt.Println("Grants") + + for _, g := range result.Grants { + fmt.Println(" Grantee: ", *g.Grantee.DisplayName) + fmt.Println(" Type: ", *g.Grantee.Type) + fmt.Println(" Permission:", *g.Permission) + fmt.Println("") + } } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/s3/s3_get_bucket_policy.go b/go/example_code/s3/s3_get_bucket_policy.go index 2c646878ce7..ac3e86cecc2 100644 --- a/go/example_code/s3/s3_get_bucket_policy.go +++ b/go/example_code/s3/s3_get_bucket_policy.go @@ -1,94 +1,73 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Gets the policy of an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[GetBucketPolicy function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "bytes" - "encoding/json" - "fmt" - "os" - "path/filepath" + "bytes" + "encoding/json" + "fmt" + "os" + "path/filepath" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) // Prints the policy for a bucket. If the bucket doesn't exist, or there was // and error an error message will be printed instead. // // Usage: -// go run s3_get_bucket_policy.go BUCKET_NAME +// +// go run s3_get_bucket_policy.go BUCKET_NAME func main() { - if len(os.Args) != 2 { - exitErrorf("bucket name required\nUsage: %s bucket_name", - filepath.Base(os.Args[0])) - } - - bucket := os.Args[1] + if len(os.Args) != 2 { + exitErrorf("bucket name required\nUsage: %s bucket_name", + filepath.Base(os.Args[0])) + } + + bucket := os.Args[1] - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) - // Create S3 service client - svc := s3.New(sess) + // Create S3 service client + svc := s3.New(sess) - // Call S3 to retrieve the policy for the selected bucket. - result, err := svc.GetBucketPolicy(&s3.GetBucketPolicyInput{ - Bucket: aws.String(bucket), - }) - if err != nil { - // Special error handling for the when the bucket doesn't - // exists so we can give a more direct error message from the CLI. - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case s3.ErrCodeNoSuchBucket: - exitErrorf("Bucket %q does not exist.", bucket) - case "NoSuchBucketPolicy": - exitErrorf("Bucket %q does not have a policy.", bucket) - } - } - exitErrorf("Unable to get bucket %q policy, %v.", bucket, err) - } + // Call S3 to retrieve the policy for the selected bucket. + result, err := svc.GetBucketPolicy(&s3.GetBucketPolicyInput{ + Bucket: aws.String(bucket), + }) + if err != nil { + // Special error handling for the when the bucket doesn't + // exists so we can give a more direct error message from the CLI. + if aerr, ok := err.(awserr.Error); ok { + switch aerr.Code() { + case s3.ErrCodeNoSuchBucket: + exitErrorf("Bucket %q does not exist.", bucket) + case "NoSuchBucketPolicy": + exitErrorf("Bucket %q does not have a policy.", bucket) + } + } + exitErrorf("Unable to get bucket %q policy, %v.", bucket, err) + } - out := bytes.Buffer{} - policyStr := aws.StringValue(result.Policy) - if err := json.Indent(&out, []byte(policyStr), "", " "); err != nil { - exitErrorf("Failed to pretty print bucket policy, %v.", err) - } + out := bytes.Buffer{} + policyStr := aws.StringValue(result.Policy) + if err := json.Indent(&out, []byte(policyStr), "", " "); err != nil { + exitErrorf("Failed to pretty print bucket policy, %v.", err) + } - fmt.Printf("%q's Bucket Policy:\n", bucket) - fmt.Println(out.String()) + fmt.Printf("%q's Bucket Policy:\n", bucket) + fmt.Println(out.String()) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/s3/s3_get_bucket_website.go b/go/example_code/s3/s3_get_bucket_website.go index 89b356d231a..d80bdc9e182 100644 --- a/go/example_code/s3/s3_get_bucket_website.go +++ b/go/example_code/s3/s3_get_bucket_website.go @@ -1,79 +1,58 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Gets the website configuration for an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[GetBucketWebsite function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "fmt" - "os" + "fmt" + "os" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) // Retrieves the bucket's website configuration. // // Usage: -// go run s3_get_bucket_website.go BUCKET_NAME +// +// go run s3_get_bucket_website.go BUCKET_NAME func main() { - if len(os.Args) != 2 { - exitErrorf("bucket name required\nUsage: %s bucket_name", os.Args[0]) - } - - bucket := os.Args[1] - - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create S3 service client - svc := s3.New(sess) - - // Call S3 to retrieve the website configuration for the bucket - result, err := svc.GetBucketWebsite(&s3.GetBucketWebsiteInput{ - Bucket: aws.String(bucket), - }) - if err != nil { - // Check for the NoSuchWebsiteConfiguration error code telling us - // that the bucket does not have a website configured. - if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoSuchWebsiteConfiguration" { - exitErrorf("Bucket %s does not have website configuration\n", bucket) - } - exitErrorf("Unable to get bucket website config, %v", err) - } - - // Print out the details about the bucket's website config. - fmt.Println("Bucket Website Configuration:") - fmt.Println(result) + if len(os.Args) != 2 { + exitErrorf("bucket name required\nUsage: %s bucket_name", os.Args[0]) + } + + bucket := os.Args[1] + + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create S3 service client + svc := s3.New(sess) + + // Call S3 to retrieve the website configuration for the bucket + result, err := svc.GetBucketWebsite(&s3.GetBucketWebsiteInput{ + Bucket: aws.String(bucket), + }) + if err != nil { + // Check for the NoSuchWebsiteConfiguration error code telling us + // that the bucket does not have a website configured. + if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoSuchWebsiteConfiguration" { + exitErrorf("Bucket %s does not have website configuration\n", bucket) + } + exitErrorf("Unable to get bucket website config, %v", err) + } + + // Print out the details about the bucket's website config. + fmt.Println("Bucket Website Configuration:") + fmt.Println(result) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/s3/s3_list_buckets.go b/go/example_code/s3/s3_list_buckets.go index 99bf89fe30f..93181c7f72c 100644 --- a/go/example_code/s3/s3_list_buckets.go +++ b/go/example_code/s3/s3_list_buckets.go @@ -1,63 +1,41 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Lists your S3 buckets.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[ListBuckets function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "fmt" - "os" + "fmt" + "os" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create S3 service client - svc := s3.New(sess) - - result, err := svc.ListBuckets(nil) - if err != nil { - exitErrorf("Unable to list buckets, %v", err) - } - - fmt.Println("Buckets:") - - for _, b := range result.Buckets { - fmt.Printf("* %s created on %s\n", - aws.StringValue(b.Name), aws.TimeValue(b.CreationDate)) - } + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create S3 service client + svc := s3.New(sess) + + result, err := svc.ListBuckets(nil) + if err != nil { + exitErrorf("Unable to list buckets, %v", err) + } + + fmt.Println("Buckets:") + + for _, b := range result.Buckets { + fmt.Printf("* %s created on %s\n", + aws.StringValue(b.Name), aws.TimeValue(b.CreationDate)) + } } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/s3/s3_list_objects.go b/go/example_code/s3/s3_list_objects.go index 570c9364aa2..3cb157dcd65 100644 --- a/go/example_code/s3/s3_list_objects.go +++ b/go/example_code/s3/s3_list_objects.go @@ -1,79 +1,58 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Lists the items in an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[ListObjectsV2 function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-04-06] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "fmt" - "os" + "fmt" + "os" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) // Lists the items in the specified S3 Bucket // // Usage: -// go run s3_list_objects.go BUCKET_NAME +// +// go run s3_list_objects.go BUCKET_NAME func main() { - if len(os.Args) != 2 { - exitErrorf("Bucket name required\nUsage: %s bucket_name", - os.Args[0]) - } - - bucket := os.Args[1] - - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create S3 service client - svc := s3.New(sess) - - // Get the list of items - resp, err := svc.ListObjectsV2(&s3.ListObjectsV2Input{Bucket: aws.String(bucket)}) - if err != nil { - exitErrorf("Unable to list items in bucket %q, %v", bucket, err) - } - - for _, item := range resp.Contents { - fmt.Println("Name: ", *item.Key) - fmt.Println("Last modified:", *item.LastModified) - fmt.Println("Size: ", *item.Size) - fmt.Println("Storage class:", *item.StorageClass) - fmt.Println("") - } - - fmt.Println("Found", len(resp.Contents), "items in bucket", bucket) - fmt.Println("") + if len(os.Args) != 2 { + exitErrorf("Bucket name required\nUsage: %s bucket_name", + os.Args[0]) + } + + bucket := os.Args[1] + + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create S3 service client + svc := s3.New(sess) + + // Get the list of items + resp, err := svc.ListObjectsV2(&s3.ListObjectsV2Input{Bucket: aws.String(bucket)}) + if err != nil { + exitErrorf("Unable to list items in bucket %q, %v", bucket, err) + } + + for _, item := range resp.Contents { + fmt.Println("Name: ", *item.Key) + fmt.Println("Last modified:", *item.LastModified) + fmt.Println("Size: ", *item.Size) + fmt.Println("Storage class:", *item.StorageClass) + fmt.Println("") + } + + fmt.Println("Found", len(resp.Contents), "items in bucket", bucket) + fmt.Println("") } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/s3/s3_make_bucket_public.go b/go/example_code/s3/s3_make_bucket_public.go index 9c4cc38c237..ca153afe478 100644 --- a/go/example_code/s3/s3_make_bucket_public.go +++ b/go/example_code/s3/s3_make_bucket_public.go @@ -1,79 +1,57 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Makes an S3 bucket public.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[PutBucketAcl function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" - "fmt" - "os" + "fmt" + "os" ) func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } // Gives everyone read-only access to BUCKET. // // Usage: -// go run s3_make_bucket_public.go BUCKET +// +// go run s3_make_bucket_public.go BUCKET func main() { - if len(os.Args) < 2 { - exitErrorf("Bucket name required.\nUsage: go run", os.Args[0], "BUCKET") - } - - bucket := os.Args[1] - - // private | public-read | public-read-write | authenticated-read - // See https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#CannedACL for details - acl := "public-read" - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and region from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create S3 service client - svc := s3.New(sess) - - params := &s3.PutBucketAclInput{ - Bucket: &bucket, - ACL: &acl, - } - - // Set bucket ACL - _, err := svc.PutBucketAcl(params) - if err != nil { - exitErrorf(err.Error()) - } - - fmt.Println("Bucket " + bucket + " is now public") + if len(os.Args) < 2 { + exitErrorf("Bucket name required.\nUsage: go run", os.Args[0], "BUCKET") + } + + bucket := os.Args[1] + + // private | public-read | public-read-write | authenticated-read + // See https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#CannedACL for details + acl := "public-read" + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and region from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create S3 service client + svc := s3.New(sess) + + params := &s3.PutBucketAclInput{ + Bucket: &bucket, + ACL: &acl, + } + + // Set bucket ACL + _, err := svc.PutBucketAcl(params) + if err != nil { + exitErrorf(err.Error()) + } + + fmt.Println("Bucket " + bucket + " is now public") } diff --git a/go/example_code/s3/s3_put_bucket_acl.go b/go/example_code/s3/s3_put_bucket_acl.go index f5fbcf4f895..8475051db97 100644 --- a/go/example_code/s3/s3_put_bucket_acl.go +++ b/go/example_code/s3/s3_put_bucket_acl.go @@ -1,117 +1,94 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Sets the ACL on an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[GetBucketAcl function] -// snippet-keyword:[PutBucketAcl function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - - "fmt" - "os" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + + "fmt" + "os" ) // Allows person with EMAIL address PERMISSION access to BUCKET // If PERMISSION is missing, they get READ access. // // Usage: -// go run s3_put_bucket_acl.go BUCKET EMAIL [PERMISSION] +// +// go run s3_put_bucket_acl.go BUCKET EMAIL [PERMISSION] func main() { - if len(os.Args) < 3 { - exitErrorf("Bucket name and email address required; permission optional (READ if omitted)\nUsage: go run", os.Args[0], "BUCKET EMAIL [PERMISSION]") - } - - bucket := os.Args[1] - address := os.Args[2] - - permission := "READ" - - if len(os.Args) == 4 { - permission = os.Args[3] - - if !(permission == "FULL_CONTROL" || permission == "WRITE" || permission == "WRITE_ACP" || permission == "READ" || permission == "READ_ACP") { - fmt.Println("Illegal permission value. It must be one of:") - fmt.Println("FULL_CONTROL, WRITE, WRITE_ACP, READ, or READ_ACP") - os.Exit(1) - - } - } - - userType := "AmazonCustomerByEmail" - - // Initialize a session that loads credentials from the shared credentials file ~/.aws/credentials - // and the region from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create S3 service client - svc := s3.New(sess) - - // Get existing ACL - result, err := svc.GetBucketAcl(&s3.GetBucketAclInput{Bucket: &bucket}) - if err != nil { - exitErrorf(err.Error()) - } - - owner := *result.Owner.DisplayName - ownerId := *result.Owner.ID - - // Existing grants - grants := result.Grants - - // Create new grantee to add to grants - var newGrantee = s3.Grantee{EmailAddress: &address, Type: &userType} - var newGrant = s3.Grant{Grantee: &newGrantee, Permission: &permission} - - // Add them to the grants - grants = append(grants, &newGrant) - - params := &s3.PutBucketAclInput{ - Bucket: &bucket, - AccessControlPolicy: &s3.AccessControlPolicy{ - Grants: grants, - Owner: &s3.Owner{ - DisplayName: &owner, - ID: &ownerId, - }, - }, - } - - // Set bucket ACL - _, err = svc.PutBucketAcl(params) - if err != nil { - exitErrorf(err.Error()) - } - - fmt.Println("Congratulations. You gave user with email address", address, permission, "permission to bucket", bucket) + if len(os.Args) < 3 { + exitErrorf("Bucket name and email address required; permission optional (READ if omitted)\nUsage: go run", os.Args[0], "BUCKET EMAIL [PERMISSION]") + } + + bucket := os.Args[1] + address := os.Args[2] + + permission := "READ" + + if len(os.Args) == 4 { + permission = os.Args[3] + + if !(permission == "FULL_CONTROL" || permission == "WRITE" || permission == "WRITE_ACP" || permission == "READ" || permission == "READ_ACP") { + fmt.Println("Illegal permission value. It must be one of:") + fmt.Println("FULL_CONTROL, WRITE, WRITE_ACP, READ, or READ_ACP") + os.Exit(1) + + } + } + + userType := "AmazonCustomerByEmail" + + // Initialize a session that loads credentials from the shared credentials file ~/.aws/credentials + // and the region from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create S3 service client + svc := s3.New(sess) + + // Get existing ACL + result, err := svc.GetBucketAcl(&s3.GetBucketAclInput{Bucket: &bucket}) + if err != nil { + exitErrorf(err.Error()) + } + + owner := *result.Owner.DisplayName + ownerId := *result.Owner.ID + + // Existing grants + grants := result.Grants + + // Create new grantee to add to grants + var newGrantee = s3.Grantee{EmailAddress: &address, Type: &userType} + var newGrant = s3.Grant{Grantee: &newGrantee, Permission: &permission} + + // Add them to the grants + grants = append(grants, &newGrant) + + params := &s3.PutBucketAclInput{ + Bucket: &bucket, + AccessControlPolicy: &s3.AccessControlPolicy{ + Grants: grants, + Owner: &s3.Owner{ + DisplayName: &owner, + ID: &ownerId, + }, + }, + } + + // Set bucket ACL + _, err = svc.PutBucketAcl(params) + if err != nil { + exitErrorf(err.Error()) + } + + fmt.Println("Congratulations. You gave user with email address", address, permission, "permission to bucket", bucket) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/s3/s3_put_bucket_object_acl.go b/go/example_code/s3/s3_put_bucket_object_acl.go index 6dea211f514..e1e6399ec65 100644 --- a/go/example_code/s3/s3_put_bucket_object_acl.go +++ b/go/example_code/s3/s3_put_bucket_object_acl.go @@ -1,117 +1,94 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Sets the ACL on an S3 bucket item.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[GetObjectAcl function] -// snippet-keyword:[PutObjectAcl function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - - "fmt" - "os" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + + "fmt" + "os" ) // Allows person with EMAIL address PERMISSION access to BUCKET OBJECT // If PERMISSION is missing, they get READ access. // // Usage: -// go run s3_put_bucket_acl.go BUCKET OBJECT EMAIL [PERMISSION] +// +// go run s3_put_bucket_acl.go BUCKET OBJECT EMAIL [PERMISSION] func main() { - if len(os.Args) < 4 { - exitErrorf("Bucket name, object name, and email address required; permission optional (READ if omitted)\nUsage: go run", os.Args[0], "BUCKET OBJECT EMAIL [PERMISSION]") - } - - bucket := os.Args[1] - key := os.Args[2] - address := os.Args[3] - - permission := "READ" - - if len(os.Args) == 5 { - permission = os.Args[4] - - if !(permission == "FULL_CONTROL" || permission == "WRITE" || permission == "WRITE_ACP" || permission == "READ" || permission == "READ_ACP") { - fmt.Println("Illegal permission value. It must be one of:") - fmt.Println("FULL_CONTROL, WRITE, WRITE_ACP, READ, or READ_ACP") - os.Exit(1) - } - } - - // Initialize a session that loads credentials from the shared credentials file ~/.aws/credentials - // and the region from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create S3 service client - svc := s3.New(sess) - - // Get existing ACL - result, err := svc.GetObjectAcl(&s3.GetObjectAclInput{Bucket: &bucket, Key: &key}) - if err != nil { - exitErrorf(err.Error()) - } - - owner := *result.Owner.DisplayName - ownerId := *result.Owner.ID - - // Existing grants - grants := result.Grants - - // Create new grantee to add to grants - userType := "AmazonCustomerByEmail" - var newGrantee = s3.Grantee{EmailAddress: &address, Type: &userType} - var newGrant = s3.Grant{Grantee: &newGrantee, Permission: &permission} - - // Add them to the grants - grants = append(grants, &newGrant) - - params := &s3.PutObjectAclInput{ - Bucket: &bucket, - Key: &key, - AccessControlPolicy: &s3.AccessControlPolicy{ - Grants: grants, - Owner: &s3.Owner{ - DisplayName: &owner, - ID: &ownerId, - }, - }, - } - - // Set bucket ACL - _, err = svc.PutObjectAcl(params) - if err != nil { - exitErrorf(err.Error()) - } - - fmt.Println("Congratulations. You gave user with email address", address, permission, "permission to bucket", bucket, "object", key) + if len(os.Args) < 4 { + exitErrorf("Bucket name, object name, and email address required; permission optional (READ if omitted)\nUsage: go run", os.Args[0], "BUCKET OBJECT EMAIL [PERMISSION]") + } + + bucket := os.Args[1] + key := os.Args[2] + address := os.Args[3] + + permission := "READ" + + if len(os.Args) == 5 { + permission = os.Args[4] + + if !(permission == "FULL_CONTROL" || permission == "WRITE" || permission == "WRITE_ACP" || permission == "READ" || permission == "READ_ACP") { + fmt.Println("Illegal permission value. It must be one of:") + fmt.Println("FULL_CONTROL, WRITE, WRITE_ACP, READ, or READ_ACP") + os.Exit(1) + } + } + + // Initialize a session that loads credentials from the shared credentials file ~/.aws/credentials + // and the region from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create S3 service client + svc := s3.New(sess) + + // Get existing ACL + result, err := svc.GetObjectAcl(&s3.GetObjectAclInput{Bucket: &bucket, Key: &key}) + if err != nil { + exitErrorf(err.Error()) + } + + owner := *result.Owner.DisplayName + ownerId := *result.Owner.ID + + // Existing grants + grants := result.Grants + + // Create new grantee to add to grants + userType := "AmazonCustomerByEmail" + var newGrantee = s3.Grantee{EmailAddress: &address, Type: &userType} + var newGrant = s3.Grant{Grantee: &newGrantee, Permission: &permission} + + // Add them to the grants + grants = append(grants, &newGrant) + + params := &s3.PutObjectAclInput{ + Bucket: &bucket, + Key: &key, + AccessControlPolicy: &s3.AccessControlPolicy{ + Grants: grants, + Owner: &s3.Owner{ + DisplayName: &owner, + ID: &ownerId, + }, + }, + } + + // Set bucket ACL + _, err = svc.PutObjectAcl(params) + if err != nil { + exitErrorf(err.Error()) + } + + fmt.Println("Congratulations. You gave user with email address", address, permission, "permission to bucket", bucket, "object", key) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/s3/s3_require_server_encryption.go b/go/example_code/s3/s3_require_server_encryption.go index 46f71d21bd4..d0000276a22 100644 --- a/go/example_code/s3/s3_require_server_encryption.go +++ b/go/example_code/s3/s3_require_server_encryption.go @@ -1,102 +1,79 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Adds a policy to an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[PutBucketPolicy function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" - "fmt" - "os" - "encoding/json" + "encoding/json" + "fmt" + "os" ) func main() { - bucket := "myBucket" + bucket := "myBucket" - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and the region from the shard configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and the region from the shard configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - svc := s3.New(sess) + svc := s3.New(sess) - PolicyDoc := map[string]interface{}{ - "Version": "2012-10-17", - "Statement": []map[string]interface{}{ - { - "Sid": "DenyIncorrectEncryptionHeader", - "Effect": "Deny", - "Principal": "*", - "Action": "s3:PutObject", - "Resource": "arn:aws:s3:::" + bucket + "/*", - "Condition": map[string]interface{}{ - "StringNotEquals": map[string]interface{}{ - "s3:x-amz-server-side-encryption": "aws:kms", - }, - }, - }, - { - "Sid": "DenyUnEncryptedObjectUploads", - "Effect": "Deny", - "Principal": "*", - "Action": "s3:PutObject", - "Resource": "arn:aws:s3:::" + bucket + "/*", - "Condition": map[string]interface{}{ - "Null": map[string]interface{}{ - "s3:x-amz-server-side-encryption": "true", - }, - }, - }, - }, - } + PolicyDoc := map[string]interface{}{ + "Version": "2012-10-17", + "Statement": []map[string]interface{}{ + { + "Sid": "DenyIncorrectEncryptionHeader", + "Effect": "Deny", + "Principal": "*", + "Action": "s3:PutObject", + "Resource": "arn:aws:s3:::" + bucket + "/*", + "Condition": map[string]interface{}{ + "StringNotEquals": map[string]interface{}{ + "s3:x-amz-server-side-encryption": "aws:kms", + }, + }, + }, + { + "Sid": "DenyUnEncryptedObjectUploads", + "Effect": "Deny", + "Principal": "*", + "Action": "s3:PutObject", + "Resource": "arn:aws:s3:::" + bucket + "/*", + "Condition": map[string]interface{}{ + "Null": map[string]interface{}{ + "s3:x-amz-server-side-encryption": "true", + }, + }, + }, + }, + } - // Marshal the policy into a JSON value so that it can be sent to S3. - policy, err := json.Marshal(PolicyDoc) - if err != nil { - fmt.Println("Error marshalling policy:") - fmt.Println(err.Error()) - os.Exit(1) - } + // Marshal the policy into a JSON value so that it can be sent to S3. + policy, err := json.Marshal(PolicyDoc) + if err != nil { + fmt.Println("Error marshalling policy:") + fmt.Println(err.Error()) + os.Exit(1) + } - input := &s3.PutBucketPolicyInput{ - Bucket: aws.String(bucket), - Policy: aws.String(string(policy)), - } + input := &s3.PutBucketPolicyInput{ + Bucket: aws.String(bucket), + Policy: aws.String(string(policy)), + } - _, err = svc.PutBucketPolicy(input) - if err != nil { - fmt.Println("Got an error adding policy to bucket " + bucket + ":") - fmt.Println(err.Error()) - os.Exit(1) - } + _, err = svc.PutBucketPolicy(input) + if err != nil { + fmt.Println("Got an error adding policy to bucket " + bucket + ":") + fmt.Println(err.Error()) + os.Exit(1) + } - fmt.Println("Set policy for " + bucket) + fmt.Println("Set policy for " + bucket) } diff --git a/go/example_code/s3/s3_restore_object.go b/go/example_code/s3/s3_restore_object.go index 1ecac5acff9..a9c5918c834 100644 --- a/go/example_code/s3/s3_restore_object.go +++ b/go/example_code/s3/s3_restore_object.go @@ -1,72 +1,51 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Restores an item in an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[RestoreObject function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "fmt" - "os" + "fmt" + "os" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) // Restores an object in an S3 Bucket in the region configured in the shared config // or AWS_REGION environment variable. // // Usage: -// go run s3_restore_object.go BUCKET_NAME OBJECT_NAME +// +// go run s3_restore_object.go BUCKET_NAME OBJECT_NAME func main() { - if len(os.Args) != 3 { - exitErrorf("Bucket name and object name required\nUsage: %s bucket_name object_name", - os.Args[0]) - } - - bucket := os.Args[1] - obj := os.Args[2] - - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create S3 service client - svc := s3.New(sess) - - // Restore the object from Glacier for up to 30 days - _, err = svc.RestoreObject(&s3.RestoreObjectInput{Bucket: aws.String(bucket), Key: aws.String(obj), RestoreRequest: &s3.RestoreRequest{Days: aws.Int64(30)}}) - if err != nil { - exitErrorf("Could not restore %s in bucket %s, %v", obj, bucket, err) - } - - fmt.Printf("%q should be restored to %q in about 4 hours\n", obj, bucket) + if len(os.Args) != 3 { + exitErrorf("Bucket name and object name required\nUsage: %s bucket_name object_name", + os.Args[0]) + } + + bucket := os.Args[1] + obj := os.Args[2] + + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create S3 service client + svc := s3.New(sess) + + // Restore the object from Glacier for up to 30 days + _, err = svc.RestoreObject(&s3.RestoreObjectInput{Bucket: aws.String(bucket), Key: aws.String(obj), RestoreRequest: &s3.RestoreRequest{Days: aws.Int64(30)}}) + if err != nil { + exitErrorf("Could not restore %s in bucket %s, %v", obj, bucket, err) + } + + fmt.Printf("%q should be restored to %q in about 4 hours\n", obj, bucket) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/s3/s3_set_bucket_policy.go b/go/example_code/s3/s3_set_bucket_policy.go index 383b9570bdd..6d49dc2cb6b 100644 --- a/go/example_code/s3/s3_set_bucket_policy.go +++ b/go/example_code/s3/s3_set_bucket_policy.go @@ -1,106 +1,85 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Sets the policy for an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[PutBucketPolicy function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "encoding/json" - "fmt" - "os" - "path/filepath" + "encoding/json" + "fmt" + "os" + "path/filepath" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) // Sets a read only anonymous user policy for a bucket. If the bucket doesn't // exist, or there was and error an error message will be printed instead. // // Usage: -// go run s3_put_bucket_policy.go BUCKET_NAME +// +// go run s3_put_bucket_policy.go BUCKET_NAME func main() { - if len(os.Args) != 2 { - exitErrorf("bucket name required\nUsage: %s bucket_name", - filepath.Base(os.Args[0])) - } - bucket := os.Args[1] + if len(os.Args) != 2 { + exitErrorf("bucket name required\nUsage: %s bucket_name", + filepath.Base(os.Args[0])) + } + bucket := os.Args[1] - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) - // Create S3 service client - svc := s3.New(sess) + // Create S3 service client + svc := s3.New(sess) - // Create a policy using map interface. Filling in the bucket as the - // resource. - readOnlyAnonUserPolicy := map[string]interface{}{ - "Version": "2012-10-17", - "Statement": []map[string]interface{}{ - { - "Sid": "AddPerm", - "Effect": "Allow", - "Principal": "*", - "Action": []string{ - "s3:GetObject", - }, - "Resource": []string{ - fmt.Sprintf("arn:aws:s3:::%s/*", bucket), - }, - }, - }, - } + // Create a policy using map interface. Filling in the bucket as the + // resource. + readOnlyAnonUserPolicy := map[string]interface{}{ + "Version": "2012-10-17", + "Statement": []map[string]interface{}{ + { + "Sid": "AddPerm", + "Effect": "Allow", + "Principal": "*", + "Action": []string{ + "s3:GetObject", + }, + "Resource": []string{ + fmt.Sprintf("arn:aws:s3:::%s/*", bucket), + }, + }, + }, + } - // Marshal the policy into a JSON value so that it can be sent to S3. - policy, err := json.Marshal(readOnlyAnonUserPolicy) - if err != nil { - exitErrorf("Failed to marshal policy, %v", err) - } + // Marshal the policy into a JSON value so that it can be sent to S3. + policy, err := json.Marshal(readOnlyAnonUserPolicy) + if err != nil { + exitErrorf("Failed to marshal policy, %v", err) + } - // Call S3 to put the policy for the bucket. - _, err = svc.PutBucketPolicy(&s3.PutBucketPolicyInput{ - Bucket: aws.String(bucket), - Policy: aws.String(string(policy)), - }) - if err != nil { - if aerr, ok := err.(awserr.Error); ok && aerr.Code() == s3.ErrCodeNoSuchBucket { - // Special error handling for the when the bucket doesn't - // exists so we can give a more direct error message from the CLI. - exitErrorf("Bucket %q does not exist", bucket) - } - exitErrorf("Unable to set bucket %q policy, %v", bucket, err) - } + // Call S3 to put the policy for the bucket. + _, err = svc.PutBucketPolicy(&s3.PutBucketPolicyInput{ + Bucket: aws.String(bucket), + Policy: aws.String(string(policy)), + }) + if err != nil { + if aerr, ok := err.(awserr.Error); ok && aerr.Code() == s3.ErrCodeNoSuchBucket { + // Special error handling for the when the bucket doesn't + // exists so we can give a more direct error message from the CLI. + exitErrorf("Bucket %q does not exist", bucket) + } + exitErrorf("Unable to set bucket %q policy, %v", bucket, err) + } - fmt.Printf("Successfully set bucket %q's policy\n", bucket) + fmt.Printf("Successfully set bucket %q's policy\n", bucket) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/s3/s3_set_bucket_website.go b/go/example_code/s3/s3_set_bucket_website.go index abc69009652..8f04b60f7f8 100644 --- a/go/example_code/s3/s3_set_bucket_website.go +++ b/go/example_code/s3/s3_set_bucket_website.go @@ -1,38 +1,16 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Sets the website configuration for an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[PutBucketWebsite function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "fmt" - "os" - "path/filepath" + "fmt" + "os" + "path/filepath" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) // Sets the bucket's website configuration. Allows setting the index suffix, @@ -42,62 +20,63 @@ import ( // that configuration // // Usage: -// go run s3_set_bucket_website.go BUCKET_NAME INDEX_PAGE ERROR_PAGE +// +// go run s3_set_bucket_website.go BUCKET_NAME INDEX_PAGE ERROR_PAGE func main() { - if len(os.Args) != 4 { - exitErrorf("bucket name and index suffix page required\nUsage: %s bucket_name index_page [error_page]", - filepath.Base(os.Args[0])) - } + if len(os.Args) != 4 { + exitErrorf("bucket name and index suffix page required\nUsage: %s bucket_name index_page [error_page]", + filepath.Base(os.Args[0])) + } - bucket := fromArgs(os.Args, 1) - indexSuffix := fromArgs(os.Args, 2) - errorPage := fromArgs(os.Args, 3) + bucket := fromArgs(os.Args, 1) + indexSuffix := fromArgs(os.Args, 2) + errorPage := fromArgs(os.Args, 3) - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) - // Create S3 service client - svc := s3.New(sess) + // Create S3 service client + svc := s3.New(sess) - // Create SetBucketWebsite parameters based on CLI input - params := s3.PutBucketWebsiteInput{ - Bucket: aws.String(bucket), - WebsiteConfiguration: &s3.WebsiteConfiguration{ - IndexDocument: &s3.IndexDocument{ - Suffix: aws.String(indexSuffix), - }, - }, - } + // Create SetBucketWebsite parameters based on CLI input + params := s3.PutBucketWebsiteInput{ + Bucket: aws.String(bucket), + WebsiteConfiguration: &s3.WebsiteConfiguration{ + IndexDocument: &s3.IndexDocument{ + Suffix: aws.String(indexSuffix), + }, + }, + } - // Add the error page if set on CLI - if len(errorPage) > 0 { - params.WebsiteConfiguration.ErrorDocument = &s3.ErrorDocument{ - Key: aws.String(errorPage), - } - } + // Add the error page if set on CLI + if len(errorPage) > 0 { + params.WebsiteConfiguration.ErrorDocument = &s3.ErrorDocument{ + Key: aws.String(errorPage), + } + } - // Set the website configuration on the bucket. Replacing any existing - // configuration. - _, err = svc.PutBucketWebsite(¶ms) - if err != nil { - exitErrorf("Unable to set bucket %q website configuration, %v", - bucket, err) - } + // Set the website configuration on the bucket. Replacing any existing + // configuration. + _, err = svc.PutBucketWebsite(¶ms) + if err != nil { + exitErrorf("Unable to set bucket %q website configuration, %v", + bucket, err) + } - fmt.Printf("Successfully set bucket %q website configuration\n", bucket) + fmt.Printf("Successfully set bucket %q website configuration\n", bucket) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } func fromArgs(args []string, idx int) string { - if len(args) > idx { - return args[idx] - } - return "" + if len(args) > idx { + return args[idx] + } + return "" } diff --git a/go/example_code/s3/s3_set_cors.go b/go/example_code/s3/s3_set_cors.go index e0d5f4d9379..acd42d582cf 100644 --- a/go/example_code/s3/s3_set_cors.go +++ b/go/example_code/s3/s3_set_cors.go @@ -1,42 +1,20 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Sets CORS permission on an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[PutBucketCors function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-1-6] -/* - Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.set_cors.complete] package main // snippet-start:[s3.go.set_cors.imports] import ( - "flag" - "fmt" - "os" - "strings" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "flag" + "fmt" + "os" + "strings" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.set_cors.imports] // Configures CORS rules for a bucket by setting the allowed @@ -46,81 +24,84 @@ import ( // list of HTTP methods. // // Usage: -// go run s3_set_cors.go -b BUCKET_NAME get put +// +// go run s3_set_cors.go -b BUCKET_NAME get put func main() { - // snippet-start:[s3.go.set_cors.vars] - bucketPtr := flag.String("b", "", "Bucket to set CORS on, (required)") - - flag.Parse() - - if *bucketPtr == "" { - exitErrorf("-b Bucket name required") - } - - methods := filterMethods(flag.Args()) - // snippet-end:[s3.go.set_cors.vars] - - // Initialize a session - // snippet-start:[s3.go.set_cors.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := s3.New(sess) - // snippet-end:[s3.go.set_cors.session] - - // Create a CORS rule for the bucket - // snippet-start:[s3.go.set_cors.rule] - rule := s3.CORSRule{ - AllowedHeaders: aws.StringSlice([]string{"Authorization"}), - AllowedOrigins: aws.StringSlice([]string{"*"}), - MaxAgeSeconds: aws.Int64(3000), - - // Add HTTP methods CORS request that were specified in the CLI. - AllowedMethods: aws.StringSlice(methods), - } - // snippet-end:[s3.go.set_cors.rule] - - // Create the parameters for the PutBucketCors API call, add add - // the rule created to it. - // snippet-start:[s3.go.set_cors.put] - params := s3.PutBucketCorsInput{ - Bucket: bucketPtr, - CORSConfiguration: &s3.CORSConfiguration{ - CORSRules: []*s3.CORSRule{&rule}, - }, - } - - _, err := svc.PutBucketCors(¶ms) - if err != nil { - // Print the error message - exitErrorf("Unable to set Bucket %q's CORS, %v", *bucketPtr, err) - } - - // Print the updated CORS config for the bucket - fmt.Printf("Updated bucket %q CORS for %v\n", *bucketPtr, methods) - // snippet-end:[s3.go.set_cors.put] + // snippet-start:[s3.go.set_cors.vars] + bucketPtr := flag.String("b", "", "Bucket to set CORS on, (required)") + + flag.Parse() + + if *bucketPtr == "" { + exitErrorf("-b Bucket name required") + } + + methods := filterMethods(flag.Args()) + // snippet-end:[s3.go.set_cors.vars] + + // Initialize a session + // snippet-start:[s3.go.set_cors.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := s3.New(sess) + // snippet-end:[s3.go.set_cors.session] + + // Create a CORS rule for the bucket + // snippet-start:[s3.go.set_cors.rule] + rule := s3.CORSRule{ + AllowedHeaders: aws.StringSlice([]string{"Authorization"}), + AllowedOrigins: aws.StringSlice([]string{"*"}), + MaxAgeSeconds: aws.Int64(3000), + + // Add HTTP methods CORS request that were specified in the CLI. + AllowedMethods: aws.StringSlice(methods), + } + // snippet-end:[s3.go.set_cors.rule] + + // Create the parameters for the PutBucketCors API call, add add + // the rule created to it. + // snippet-start:[s3.go.set_cors.put] + params := s3.PutBucketCorsInput{ + Bucket: bucketPtr, + CORSConfiguration: &s3.CORSConfiguration{ + CORSRules: []*s3.CORSRule{&rule}, + }, + } + + _, err := svc.PutBucketCors(¶ms) + if err != nil { + // Print the error message + exitErrorf("Unable to set Bucket %q's CORS, %v", *bucketPtr, err) + } + + // Print the updated CORS config for the bucket + fmt.Printf("Updated bucket %q CORS for %v\n", *bucketPtr, methods) + // snippet-end:[s3.go.set_cors.put] } // snippet-start:[s3.go.set_cors.exit] func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } + // snippet-end:[s3.go.set_cors.exit] // snippet-start:[s3.go.set_cors.filter] func filterMethods(methods []string) []string { - filtered := make([]string, 0, len(methods)) - for _, m := range methods { - v := strings.ToUpper(m) - switch v { - case "POST", "GET", "PUT", "PATCH", "DELETE": - filtered = append(filtered, v) - } - } - - return filtered + filtered := make([]string, 0, len(methods)) + for _, m := range methods { + v := strings.ToUpper(m) + switch v { + case "POST", "GET", "PUT", "PATCH", "DELETE": + filtered = append(filtered, v) + } + } + + return filtered } + // snippet-end:[s3.go.set_cors.filter] // snippet-end:[s3.go.set_cors.complete] diff --git a/go/example_code/s3/s3_set_default_encryption.go b/go/example_code/s3/s3_set_default_encryption.go index 16e62c44f5c..1d2b4f6e24e 100644 --- a/go/example_code/s3/s3_set_default_encryption.go +++ b/go/example_code/s3/s3_set_default_encryption.go @@ -1,71 +1,48 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Enables KMS server-side encryption on any objects added to to an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[PutBucketEncryption function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" - "fmt" - "os" + "fmt" + "os" ) func main() { - if len(os.Args) != 2 { - fmt.Println("You must supply a key") - os.Exit(1) - } - - key := os.Args[1] - bucket := "myBucket" - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := s3.New(sess) - - // Encrypt with KMS by default - defEnc := &s3.ServerSideEncryptionByDefault{KMSMasterKeyID: aws.String(key), SSEAlgorithm: aws.String(s3.ServerSideEncryptionAwsKms)} - rule := &s3.ServerSideEncryptionRule{ApplyServerSideEncryptionByDefault: defEnc} - rules := []*s3.ServerSideEncryptionRule{rule} - serverConfig := &s3.ServerSideEncryptionConfiguration{Rules: rules} - input := &s3.PutBucketEncryptionInput{Bucket: aws.String(bucket), ServerSideEncryptionConfiguration: serverConfig} - - _, err := svc.PutBucketEncryption(input) - if err != nil { - fmt.Println("Got an error adding default KMS encryption to bucket", bucket) - fmt.Println(err.Error()) - os.Exit(1) - } - - fmt.Println("Bucket " + bucket + " now has KMS encryption by default") + if len(os.Args) != 2 { + fmt.Println("You must supply a key") + os.Exit(1) + } + + key := os.Args[1] + bucket := "myBucket" + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := s3.New(sess) + + // Encrypt with KMS by default + defEnc := &s3.ServerSideEncryptionByDefault{KMSMasterKeyID: aws.String(key), SSEAlgorithm: aws.String(s3.ServerSideEncryptionAwsKms)} + rule := &s3.ServerSideEncryptionRule{ApplyServerSideEncryptionByDefault: defEnc} + rules := []*s3.ServerSideEncryptionRule{rule} + serverConfig := &s3.ServerSideEncryptionConfiguration{Rules: rules} + input := &s3.PutBucketEncryptionInput{Bucket: aws.String(bucket), ServerSideEncryptionConfiguration: serverConfig} + + _, err := svc.PutBucketEncryption(input) + if err != nil { + fmt.Println("Got an error adding default KMS encryption to bucket", bucket) + fmt.Println(err.Error()) + os.Exit(1) + } + + fmt.Println("Bucket " + bucket + " now has KMS encryption by default") } diff --git a/go/example_code/s3/s3_upload_directory.go b/go/example_code/s3/s3_upload_directory.go index 4ab8859682c..6670f1d18fc 100644 --- a/go/example_code/s3/s3_upload_directory.go +++ b/go/example_code/s3/s3_upload_directory.go @@ -1,108 +1,109 @@ -// snippet-sourcetype:[full-example] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" - "path/filepath" + "fmt" + "os" + "path/filepath" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3/s3manager" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3/s3manager" ) const exitError = 1 func main() { - if len(os.Args) != 4 { - exitErrorf("region, bucket and directory path required\nUsage: %s region bucket_name path", - os.Args[0]) - } - - region := os.Args[1] - bucket := os.Args[2] - path := os.Args[3] - di := NewDirectoryIterator(bucket, path) - - sess, err := session.NewSession(&aws.Config{ - Region: aws.String(region)}, - ) - if err != nil { - exitErrorf("failed to create a session %q, %v", err) - } - - uploader := s3manager.NewUploader(sess) - - if err := uploader.UploadWithIterator(aws.BackgroundContext(), di); err != nil { - exitErrorf("failed to upload %q, %v", err) - } - fmt.Printf("successfully uploaded %q to %q", path, bucket) + if len(os.Args) != 4 { + exitErrorf("region, bucket and directory path required\nUsage: %s region bucket_name path", + os.Args[0]) + } + + region := os.Args[1] + bucket := os.Args[2] + path := os.Args[3] + di := NewDirectoryIterator(bucket, path) + + sess, err := session.NewSession(&aws.Config{ + Region: aws.String(region)}, + ) + if err != nil { + exitErrorf("failed to create a session %q, %v", err) + } + + uploader := s3manager.NewUploader(sess) + + if err := uploader.UploadWithIterator(aws.BackgroundContext(), di); err != nil { + exitErrorf("failed to upload %q, %v", err) + } + fmt.Printf("successfully uploaded %q to %q", path, bucket) } // DirectoryIterator represents an iterator of a specified directory type DirectoryIterator struct { - filePaths []string - bucket string - next struct { - path string - f *os.File - } - err error + filePaths []string + bucket string + next struct { + path string + f *os.File + } + err error } // NewDirectoryIterator builds a new DirectoryIterator func NewDirectoryIterator(bucket, dir string) s3manager.BatchUploadIterator { - var paths []string - filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { - if !info.IsDir() { - paths = append(paths, path) - } - return nil - }) - - return &DirectoryIterator{ - filePaths: paths, - bucket: bucket, - } + var paths []string + filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + if !info.IsDir() { + paths = append(paths, path) + } + return nil + }) + + return &DirectoryIterator{ + filePaths: paths, + bucket: bucket, + } } // Next returns whether next file exists or not func (di *DirectoryIterator) Next() bool { - if len(di.filePaths) == 0 { - di.next.f = nil - return false - } - - f, err := os.Open(di.filePaths[0]) - di.err = err - di.next.f = f - di.next.path = di.filePaths[0] - di.filePaths = di.filePaths[1:] - - return true && di.Err() == nil + if len(di.filePaths) == 0 { + di.next.f = nil + return false + } + + f, err := os.Open(di.filePaths[0]) + di.err = err + di.next.f = f + di.next.path = di.filePaths[0] + di.filePaths = di.filePaths[1:] + + return true && di.Err() == nil } // Err returns error of DirectoryIterator func (di *DirectoryIterator) Err() error { - return di.err + return di.err } // UploadObject uploads a file func (di *DirectoryIterator) UploadObject() s3manager.BatchUploadObject { - f := di.next.f - return s3manager.BatchUploadObject{ - Object: &s3manager.UploadInput{ - Bucket: &di.bucket, - Key: &di.next.path, - Body: f, - }, - After: func() error { - return f.Close() - }, - } + f := di.next.f + return s3manager.BatchUploadObject{ + Object: &s3manager.UploadInput{ + Bucket: &di.bucket, + Key: &di.next.path, + Body: f, + }, + After: func() error { + return f.Close() + }, + } } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(exitError) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(exitError) } diff --git a/go/example_code/s3/s3_upload_object.go b/go/example_code/s3/s3_upload_object.go index d40c1fda3b6..e84f4001828 100644 --- a/go/example_code/s3/s3_upload_object.go +++ b/go/example_code/s3/s3_upload_object.go @@ -1,98 +1,76 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Uploads a file to an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[s3manager.NewUploader] -// snippet-keyword:[Upload function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - "fmt" - "os" + "fmt" + "os" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3/s3manager" ) // Creates a S3 Bucket in the region configured in the shared config // or AWS_REGION environment variable. // // Usage: -// go run s3_upload_object.go BUCKET_NAME FILENAME +// +// go run s3_upload_object.go BUCKET_NAME FILENAME func main() { - if len(os.Args) != 3 { - exitErrorf("bucket and file name required\nUsage: %s bucket_name filename", - os.Args[0]) - } - - bucket := os.Args[1] - filename := os.Args[2] - - file, err := os.Open(filename) - if err != nil { - exitErrorf("Unable to open file %q, %v", filename, err) - } - - defer file.Close() - - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Setup the S3 Upload Manager. Also see the SDK doc for the Upload Manager - // for more information on configuring part size, and concurrency. - // - // http://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/#NewUploader - uploader := s3manager.NewUploader(sess) - - // Upload the file's body to S3 bucket as an object with the key being the - // same as the filename. - _, err = uploader.Upload(&s3manager.UploadInput{ - Bucket: aws.String(bucket), - - // Can also use the `filepath` standard library package to modify the - // filename as need for an S3 object key. Such as turning absolute path - // to a relative path. - Key: aws.String(filename), - - // The file to be uploaded. io.ReadSeeker is preferred as the Uploader - // will be able to optimize memory when uploading large content. io.Reader - // is supported, but will require buffering of the reader's bytes for - // each part. - Body: file, - }) - if err != nil { - // Print the error and exit. - exitErrorf("Unable to upload %q to %q, %v", filename, bucket, err) - } - - fmt.Printf("Successfully uploaded %q to %q\n", filename, bucket) + if len(os.Args) != 3 { + exitErrorf("bucket and file name required\nUsage: %s bucket_name filename", + os.Args[0]) + } + + bucket := os.Args[1] + filename := os.Args[2] + + file, err := os.Open(filename) + if err != nil { + exitErrorf("Unable to open file %q, %v", filename, err) + } + + defer file.Close() + + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Setup the S3 Upload Manager. Also see the SDK doc for the Upload Manager + // for more information on configuring part size, and concurrency. + // + // http://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/#NewUploader + uploader := s3manager.NewUploader(sess) + + // Upload the file's body to S3 bucket as an object with the key being the + // same as the filename. + _, err = uploader.Upload(&s3manager.UploadInput{ + Bucket: aws.String(bucket), + + // Can also use the `filepath` standard library package to modify the + // filename as need for an S3 object key. Such as turning absolute path + // to a relative path. + Key: aws.String(filename), + + // The file to be uploaded. io.ReadSeeker is preferred as the Uploader + // will be able to optimize memory when uploading large content. io.Reader + // is supported, but will require buffering of the reader's bytes for + // each part. + Body: file, + }) + if err != nil { + // Print the error and exit. + exitErrorf("Unable to upload %q to %q, %v", filename, bucket, err) + } + + fmt.Printf("Successfully uploaded %q to %q\n", filename, bucket) } func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } diff --git a/go/example_code/s3/upload_arbitrary_sized_stream.go b/go/example_code/s3/upload_arbitrary_sized_stream.go index e4c27c73522..3fc97c28a3c 100644 --- a/go/example_code/s3/upload_arbitrary_sized_stream.go +++ b/go/example_code/s3/upload_arbitrary_sized_stream.go @@ -1,75 +1,52 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Uploads a file, as a stream, to an S3 bucket.] -// snippet-keyword:[Amazon Simple Storage Service] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[s3manager.NewUploader] -// snippet-keyword:[Upload function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[s3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - "compress/gzip" - "io" - "log" - "os" + "compress/gzip" + "io" + "log" + "os" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3/s3manager" ) func main() { - file, err := os.Open("upload_file") - if err != nil { - log.Fatal("Failed to open file", err) - } - - // Not required, but you could zip the file before uploading it - // using io.Pipe read/writer to stream gzip'd file contents. - reader, writer := io.Pipe() - - go func() { - gw := gzip.NewWriter(writer) - io.Copy(gw, file) - file.Close() - gw.Close() - writer.Close() - }() - - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - uploader := s3manager.NewUploader(sess) - - result, err := uploader.Upload(&s3manager.UploadInput{ - Body: reader, - Bucket: aws.String("myBucket"), - Key: aws.String("myKey"), - }) - if err != nil { - log.Fatalln("Failed to upload", err) - } - - log.Println("Successfully uploaded to", result.Location) + file, err := os.Open("upload_file") + if err != nil { + log.Fatal("Failed to open file", err) + } + + // Not required, but you could zip the file before uploading it + // using io.Pipe read/writer to stream gzip'd file contents. + reader, writer := io.Pipe() + + go func() { + gw := gzip.NewWriter(writer) + io.Copy(gw, file) + file.Close() + gw.Close() + writer.Close() + }() + + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + uploader := s3manager.NewUploader(sess) + + result, err := uploader.Upload(&s3manager.UploadInput{ + Body: reader, + Bucket: aws.String("myBucket"), + Key: aws.String("myKey"), + }) + if err != nil { + log.Fatalln("Failed to upload", err) + } + + log.Println("Successfully uploaded to", result.Location) } diff --git a/go/example_code/ses/ses_delete_address.go b/go/example_code/ses/ses_delete_address.go index 797df997d45..e9e3cc29973 100644 --- a/go/example_code/ses/ses_delete_address.go +++ b/go/example_code/ses/ses_delete_address.go @@ -1,75 +1,52 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Deletes an SES email address.] -// snippet-keyword:[Amazon Simple Email Service] -// snippet-keyword:[Amazon SES] -// snippet-keyword:[DeleteVerifiedEmailAddress function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ses] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" - - //go get -u github.com/aws/aws-sdk-go - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ses" + "fmt" + "os" + + //go get -u github.com/aws/aws-sdk-go + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ses" ) const ( - // Replace sender@example.com with your "From" address - Sender = "sender@example.com" - - // Replace recipient@example.com with a "To" address - Recipient = "recipient@example.com" + // Replace sender@example.com with your "From" address + Sender = "sender@example.com" + + // Replace recipient@example.com with a "To" address + Recipient = "recipient@example.com" ) func main() { - // Create a new session in the us-west-2 region - // Replace us-west-2 with the AWS Region you're using for Amazon SES - sess, err := session.NewSession(&aws.Config{ - Region:aws.String("us-west-2")}, - ) - - if err != nil { - fmt.Println("Got error creating SES session:") - fmt.Println(err.Error()) - os.Exit(1) - } - - // Create an SES session - svc := ses.New(sess) - - // Remove email address - _, delErr := svc.DeleteVerifiedEmailAddress(&ses.DeleteVerifiedEmailAddressInput{EmailAddress: aws.String(Recipient)}) - - // Display error message if it occurs - if delErr != nil { - fmt.Println("Got error attempting to remove email address: " + Recipient) - fmt.Println(delErr.Error()) - os.Exit(1) - } - - // Display success message - fmt.Println("Removed email address: " + Recipient) + // Create a new session in the us-west-2 region + // Replace us-west-2 with the AWS Region you're using for Amazon SES + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + if err != nil { + fmt.Println("Got error creating SES session:") + fmt.Println(err.Error()) + os.Exit(1) + } + + // Create an SES session + svc := ses.New(sess) + + // Remove email address + _, delErr := svc.DeleteVerifiedEmailAddress(&ses.DeleteVerifiedEmailAddressInput{EmailAddress: aws.String(Recipient)}) + + // Display error message if it occurs + if delErr != nil { + fmt.Println("Got error attempting to remove email address: " + Recipient) + fmt.Println(delErr.Error()) + os.Exit(1) + } + + // Display success message + fmt.Println("Removed email address: " + Recipient) } diff --git a/go/example_code/ses/ses_get_statistics.go b/go/example_code/ses/ses_get_statistics.go index 577cbe858e8..8730ca4bcdd 100644 --- a/go/example_code/ses/ses_get_statistics.go +++ b/go/example_code/ses/ses_get_statistics.go @@ -1,71 +1,48 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Gets statistics about SES.] -// snippet-keyword:[Amazon Simple Email Service] -// snippet-keyword:[Amazon SES] -// snippet-keyword:[GetSendStatistics function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ses] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - //go get -u github.com/aws/aws-sdk-go - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ses" + //go get -u github.com/aws/aws-sdk-go + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ses" - "fmt" + "fmt" ) func main() { - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file ~/.aws/credentials - // and configuration from the shared configuration file ~/.aws/config. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create an SES session. - svc := ses.New(sess) - - // Attempt to send the email. - result, err := svc.GetSendStatistics(nil) - - // Display any error message - if err != nil { - fmt.Println(err.Error()) - return - } - - dps := result.SendDataPoints - - fmt.Println("Got", len(dps), "datapoints") - fmt.Println("") - - for _, dp := range dps { - fmt.Println("Timestamp: ", dp.Timestamp) - fmt.Println("Attempts: ", aws.Int64Value(dp.DeliveryAttempts)) - fmt.Println("Bounces: ", aws.Int64Value(dp.Bounces)) - fmt.Println("Complaints:", aws.Int64Value(dp.Complaints)) - fmt.Println("Rejects: ", aws.Int64Value(dp.Rejects)) - fmt.Println("") - } + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file ~/.aws/credentials + // and configuration from the shared configuration file ~/.aws/config. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create an SES session. + svc := ses.New(sess) + + // Attempt to send the email. + result, err := svc.GetSendStatistics(nil) + + // Display any error message + if err != nil { + fmt.Println(err.Error()) + return + } + + dps := result.SendDataPoints + + fmt.Println("Got", len(dps), "datapoints") + fmt.Println("") + + for _, dp := range dps { + fmt.Println("Timestamp: ", dp.Timestamp) + fmt.Println("Attempts: ", aws.Int64Value(dp.DeliveryAttempts)) + fmt.Println("Bounces: ", aws.Int64Value(dp.Bounces)) + fmt.Println("Complaints:", aws.Int64Value(dp.Complaints)) + fmt.Println("Rejects: ", aws.Int64Value(dp.Rejects)) + fmt.Println("") + } } diff --git a/go/example_code/ses/ses_list_emails.go b/go/example_code/ses/ses_list_emails.go index 053b04c9a50..ec9278b9d00 100644 --- a/go/example_code/ses/ses_list_emails.go +++ b/go/example_code/ses/ses_list_emails.go @@ -1,72 +1,48 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Lists the valid SES email addresses.] -// snippet-keyword:[Amazon Simple Email Service] -// snippet-keyword:[Amazon SES] -// snippet-keyword:[GetIdentityVerificationAttributes function] -// snippet-keyword:[ListIdentities function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ses] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "os" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ses" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ses" ) func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create SES service client - svc := ses.New(sess) - - result, err := svc.ListIdentities(&ses.ListIdentitiesInput{IdentityType: aws.String("EmailAddress")}) - - if err != nil { - fmt.Println(err) - os.Exit(1) - } - - for _, email := range result.Identities { - var e = []*string{email} - - verified, err := svc.GetIdentityVerificationAttributes(&ses.GetIdentityVerificationAttributesInput{Identities: e}) - - if err != nil { - fmt.Println(err) - os.Exit(1) - } - - for _, va := range verified.VerificationAttributes { - if *va.VerificationStatus == "Success" { - fmt.Println(*email) - } - } - } + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create SES service client + svc := ses.New(sess) + + result, err := svc.ListIdentities(&ses.ListIdentitiesInput{IdentityType: aws.String("EmailAddress")}) + + if err != nil { + fmt.Println(err) + os.Exit(1) + } + + for _, email := range result.Identities { + var e = []*string{email} + + verified, err := svc.GetIdentityVerificationAttributes(&ses.GetIdentityVerificationAttributesInput{Identities: e}) + + if err != nil { + fmt.Println(err) + os.Exit(1) + } + + for _, va := range verified.VerificationAttributes { + if *va.VerificationStatus == "Success" { + fmt.Println(*email) + } + } + } } diff --git a/go/example_code/ses/ses_send_email.go b/go/example_code/ses/ses_send_email.go index da7a219fb71..4e6cfd7723b 100644 --- a/go/example_code/ses/ses_send_email.go +++ b/go/example_code/ses/ses_send_email.go @@ -1,134 +1,110 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Sends a message to an SES email address.] -// snippet-keyword:[Amazon Simple Email Service] -// snippet-keyword:[Amazon SES] -// snippet-keyword:[SendEmail function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ses] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - - //go get -u github.com/aws/aws-sdk-go - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ses" - "github.com/aws/aws-sdk-go/aws/awserr" + "fmt" + + //go get -u github.com/aws/aws-sdk-go + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ses" ) const ( - // Replace sender@example.com with your "From" address. - // This address must be verified with Amazon SES. - Sender = "sender@example.com" - - // Replace recipient@example.com with a "To" address. If your account - // is still in the sandbox, this address must be verified. - Recipient = "recipient@example.com" - - // Specify a configuration set. To use a configuration - // set, comment the next line and line 92. - //ConfigurationSet = "ConfigSet" - - // The subject line for the email. - Subject = "Amazon SES Test (AWS SDK for Go)" - - // The HTML body for the email. - HtmlBody = "

Amazon SES Test Email (AWS SDK for Go)

This email was sent with " + - "Amazon SES using the " + - "AWS SDK for Go.

" - - //The email body for recipients with non-HTML email clients. - TextBody = "This email was sent with Amazon SES using the AWS SDK for Go." - - // The character encoding for the email. - CharSet = "UTF-8" + // Replace sender@example.com with your "From" address. + // This address must be verified with Amazon SES. + Sender = "sender@example.com" + + // Replace recipient@example.com with a "To" address. If your account + // is still in the sandbox, this address must be verified. + Recipient = "recipient@example.com" + + // Specify a configuration set. To use a configuration + // set, comment the next line and line 92. + //ConfigurationSet = "ConfigSet" + + // The subject line for the email. + Subject = "Amazon SES Test (AWS SDK for Go)" + + // The HTML body for the email. + HtmlBody = "

Amazon SES Test Email (AWS SDK for Go)

This email was sent with " + + "Amazon SES using the " + + "AWS SDK for Go.

" + + //The email body for recipients with non-HTML email clients. + TextBody = "This email was sent with Amazon SES using the AWS SDK for Go." + + // The character encoding for the email. + CharSet = "UTF-8" ) func main() { - // Create a new session in the us-west-2 region. - // Replace us-west-2 with the AWS Region you're using for Amazon SES. - sess, err := session.NewSession(&aws.Config{ - Region:aws.String("us-west-2")}, - ) - - // Create an SES session. - svc := ses.New(sess) - - // Assemble the email. - input := &ses.SendEmailInput{ - Destination: &ses.Destination{ - CcAddresses: []*string{ - }, - ToAddresses: []*string{ - aws.String(Recipient), - }, - }, - Message: &ses.Message{ - Body: &ses.Body{ - Html: &ses.Content{ - Charset: aws.String(CharSet), - Data: aws.String(HtmlBody), - }, - Text: &ses.Content{ - Charset: aws.String(CharSet), - Data: aws.String(TextBody), - }, - }, - Subject: &ses.Content{ - Charset: aws.String(CharSet), - Data: aws.String(Subject), - }, - }, - Source: aws.String(Sender), - // Uncomment to use a configuration set - //ConfigurationSetName: aws.String(ConfigurationSet), - } - - // Attempt to send the email. - result, err := svc.SendEmail(input) - - // Display error messages if they occur. - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case ses.ErrCodeMessageRejected: - fmt.Println(ses.ErrCodeMessageRejected, aerr.Error()) - case ses.ErrCodeMailFromDomainNotVerifiedException: - fmt.Println(ses.ErrCodeMailFromDomainNotVerifiedException, aerr.Error()) - case ses.ErrCodeConfigurationSetDoesNotExistException: - fmt.Println(ses.ErrCodeConfigurationSetDoesNotExistException, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - - return - } - - fmt.Println("Email Sent to address: " + Recipient) - fmt.Println(result) + // Create a new session in the us-west-2 region. + // Replace us-west-2 with the AWS Region you're using for Amazon SES. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create an SES session. + svc := ses.New(sess) + + // Assemble the email. + input := &ses.SendEmailInput{ + Destination: &ses.Destination{ + CcAddresses: []*string{}, + ToAddresses: []*string{ + aws.String(Recipient), + }, + }, + Message: &ses.Message{ + Body: &ses.Body{ + Html: &ses.Content{ + Charset: aws.String(CharSet), + Data: aws.String(HtmlBody), + }, + Text: &ses.Content{ + Charset: aws.String(CharSet), + Data: aws.String(TextBody), + }, + }, + Subject: &ses.Content{ + Charset: aws.String(CharSet), + Data: aws.String(Subject), + }, + }, + Source: aws.String(Sender), + // Uncomment to use a configuration set + //ConfigurationSetName: aws.String(ConfigurationSet), + } + + // Attempt to send the email. + result, err := svc.SendEmail(input) + + // Display error messages if they occur. + if err != nil { + if aerr, ok := err.(awserr.Error); ok { + switch aerr.Code() { + case ses.ErrCodeMessageRejected: + fmt.Println(ses.ErrCodeMessageRejected, aerr.Error()) + case ses.ErrCodeMailFromDomainNotVerifiedException: + fmt.Println(ses.ErrCodeMailFromDomainNotVerifiedException, aerr.Error()) + case ses.ErrCodeConfigurationSetDoesNotExistException: + fmt.Println(ses.ErrCodeConfigurationSetDoesNotExistException, aerr.Error()) + default: + fmt.Println(aerr.Error()) + } + } else { + // Print the error, cast err to awserr.Error to get the Code and + // Message from an error. + fmt.Println(err.Error()) + } + + return + } + + fmt.Println("Email Sent to address: " + Recipient) + fmt.Println(result) } diff --git a/go/example_code/ses/ses_send_verification.go b/go/example_code/ses/ses_send_verification.go index 00672d21968..647665be87d 100644 --- a/go/example_code/ses/ses_send_verification.go +++ b/go/example_code/ses/ses_send_verification.go @@ -1,85 +1,62 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Verifies an SES email address.] -// snippet-keyword:[Amazon Simple Email Service] -// snippet-keyword:[Amazon SES] -// snippet-keyword:[VerifyEmailAddress function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[ses] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - - //go get -u github.com/aws/aws-sdk-go - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/ses" - "github.com/aws/aws-sdk-go/aws/awserr" + "fmt" + + //go get -u github.com/aws/aws-sdk-go + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/ses" ) const ( - // Replace sender@example.com with your "From" address. - // This address must be verified with Amazon SES. - Sender = "sender@example.com" - - // Replace recipient@example.com with a "To" address. If your account - // is still in the sandbox, this address must be verified. - Recipient = "recipient@example.com" + // Replace sender@example.com with your "From" address. + // This address must be verified with Amazon SES. + Sender = "sender@example.com" + + // Replace recipient@example.com with a "To" address. If your account + // is still in the sandbox, this address must be verified. + Recipient = "recipient@example.com" ) func main() { - // Create a new session in the us-west-2 region. - // Replace us-west-2 with the AWS Region you're using for Amazon SES. - sess, err := session.NewSession(&aws.Config{ - Region:aws.String("us-west-2")}, - ) - - // Create an SES session. - svc := ses.New(sess) - - // Attempt to send the email. - _, err = svc.VerifyEmailAddress(&ses.VerifyEmailAddressInput{EmailAddress: aws.String(Recipient)}) - - // Display error messages if they occur. - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - switch aerr.Code() { - case ses.ErrCodeMessageRejected: - fmt.Println(ses.ErrCodeMessageRejected, aerr.Error()) - case ses.ErrCodeMailFromDomainNotVerifiedException: - fmt.Println(ses.ErrCodeMailFromDomainNotVerifiedException, aerr.Error()) - case ses.ErrCodeConfigurationSetDoesNotExistException: - fmt.Println(ses.ErrCodeConfigurationSetDoesNotExistException, aerr.Error()) - default: - fmt.Println(aerr.Error()) - } - } else { - // Print the error, cast err to awserr.Error to get the Code and - // Message from an error. - fmt.Println(err.Error()) - } - - return - } - - fmt.Println("Verification sent to address: " + Recipient) + // Create a new session in the us-west-2 region. + // Replace us-west-2 with the AWS Region you're using for Amazon SES. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create an SES session. + svc := ses.New(sess) + + // Attempt to send the email. + _, err = svc.VerifyEmailAddress(&ses.VerifyEmailAddressInput{EmailAddress: aws.String(Recipient)}) + + // Display error messages if they occur. + if err != nil { + if aerr, ok := err.(awserr.Error); ok { + switch aerr.Code() { + case ses.ErrCodeMessageRejected: + fmt.Println(ses.ErrCodeMessageRejected, aerr.Error()) + case ses.ErrCodeMailFromDomainNotVerifiedException: + fmt.Println(ses.ErrCodeMailFromDomainNotVerifiedException, aerr.Error()) + case ses.ErrCodeConfigurationSetDoesNotExistException: + fmt.Println(ses.ErrCodeConfigurationSetDoesNotExistException, aerr.Error()) + default: + fmt.Println(aerr.Error()) + } + } else { + // Print the error, cast err to awserr.Error to get the Code and + // Message from an error. + fmt.Println(err.Error()) + } + + return + } + + fmt.Println("Verification sent to address: " + Recipient) } diff --git a/go/example_code/sns/SnsCreateTopic.go b/go/example_code/sns/SnsCreateTopic.go index c1eb6a3b06b..bd2f914c7af 100644 --- a/go/example_code/sns/SnsCreateTopic.go +++ b/go/example_code/sns/SnsCreateTopic.go @@ -1,63 +1,41 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[SnsCreateTopic.go TOPIC creates the SNS topic TOPIC.] -// snippet-keyword:[Amazon Simple Notification Service] -// snippet-keyword:[Amazon SNS] -// snippet-keyword:[CreateTopic function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[sns] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-02-25] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sns.go.create_topic] package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sns" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sns" - "fmt" - "os" + "fmt" + "os" ) func main() { - if len(os.Args) < 2 { - fmt.Println("You must supply a topic name") - fmt.Println("Usage: go run SnsCreateTopic.go TOPIC") - os.Exit(1) - } - - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file. (~/.aws/credentials). - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := sns.New(sess) - - result, err := svc.CreateTopic(&sns.CreateTopicInput{ - Name: aws.String(os.Args[1]), - }) - if err != nil { - fmt.Println(err.Error()) - os.Exit(1) - } - - fmt.Println(*result.TopicArn) + if len(os.Args) < 2 { + fmt.Println("You must supply a topic name") + fmt.Println("Usage: go run SnsCreateTopic.go TOPIC") + os.Exit(1) + } + + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file. (~/.aws/credentials). + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := sns.New(sess) + + result, err := svc.CreateTopic(&sns.CreateTopicInput{ + Name: aws.String(os.Args[1]), + }) + if err != nil { + fmt.Println(err.Error()) + os.Exit(1) + } + + fmt.Println(*result.TopicArn) } + // snippet-end:[sns.go.create_topic] diff --git a/go/example_code/sns/SnsListSubscriptions.go b/go/example_code/sns/SnsListSubscriptions.go index 3b242004e84..60c209d15d1 100644 --- a/go/example_code/sns/SnsListSubscriptions.go +++ b/go/example_code/sns/SnsListSubscriptions.go @@ -1,58 +1,36 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[SnsListSubscriptions.go lists your SNS subscriptions.] -// snippet-keyword:[Amazon Simple Notification Service] -// snippet-keyword:[Amazon SNS] -// snippet-keyword:[ListSubscriptions function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[sns] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-02-25] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sns.go.list_subscriptions] package main import ( - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sns" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sns" - "fmt" - "os" + "fmt" + "os" ) func main() { - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file. (~/.aws/credentials). - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := sns.New(sess) - - result, err := svc.ListSubscriptions(nil) - if err != nil { - fmt.Println(err.Error()) - os.Exit(1) - } - - for _, s := range result.Subscriptions { - fmt.Println(*s.SubscriptionArn) - fmt.Println(" " + *s.TopicArn) - fmt.Println("") - } + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file. (~/.aws/credentials). + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := sns.New(sess) + + result, err := svc.ListSubscriptions(nil) + if err != nil { + fmt.Println(err.Error()) + os.Exit(1) + } + + for _, s := range result.Subscriptions { + fmt.Println(*s.SubscriptionArn) + fmt.Println(" " + *s.TopicArn) + fmt.Println("") + } } + // snippet-end:[sns.go.list_subscriptions] diff --git a/go/example_code/sns/SnsListTopics.go b/go/example_code/sns/SnsListTopics.go index 2eeff139d57..ef654150da7 100644 --- a/go/example_code/sns/SnsListTopics.go +++ b/go/example_code/sns/SnsListTopics.go @@ -1,56 +1,34 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[SnsListTopics.go lists your SNS topics.] -// snippet-keyword:[Amazon Simple Notification Service] -// snippet-keyword:[Amazon SNS] -// snippet-keyword:[ListTopics function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[sns] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-02-25] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sns.go.list_topics] package main import ( - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sns" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sns" - "fmt" - "os" + "fmt" + "os" ) func main() { - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file. (~/.aws/credentials). - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := sns.New(sess) - - result, err := svc.ListTopics(nil) - if err != nil { - fmt.Println(err.Error()) - os.Exit(1) - } - - for _, t := range result.Topics { - fmt.Println(*t.TopicArn) - } + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file. (~/.aws/credentials). + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := sns.New(sess) + + result, err := svc.ListTopics(nil) + if err != nil { + fmt.Println(err.Error()) + os.Exit(1) + } + + for _, t := range result.Topics { + fmt.Println(*t.TopicArn) + } } + // snippet-end:[sns.go.list_topics] diff --git a/go/example_code/sns/SnsPublish.go b/go/example_code/sns/SnsPublish.go index 15cc0086b9a..0a672040764 100644 --- a/go/example_code/sns/SnsPublish.go +++ b/go/example_code/sns/SnsPublish.go @@ -1,69 +1,47 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[SnsPublish.go -m MESSAGE -t TOPIC-ARN sends MESSAGE to all of the users subscribed to the SNS topic with the ARN TOPIC-ARN.] -// snippet-keyword:[Amazon Simple Notification Service] -// snippet-keyword:[Amazon SNS] -// snippet-keyword:[Publish function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[sns] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-1-6] -/* - Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sns.go.publish] package main import ( - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sns" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sns" - "flag" - "fmt" - "os" + "flag" + "fmt" + "os" ) func main() { - msgPtr := flag.String("m", "", "The message to send to the subscribed users of the topic") - topicPtr := flag.String("t", "", "The ARN of the topic to which the user subscribes") - - flag.Parse() - - if *msgPtr == "" || *topicPtr == "" { - fmt.Println("You must supply a message and topic ARN") - fmt.Println("Usage: go run SnsPublish.go -m MESSAGE -t TOPIC-ARN") - os.Exit(1) - } - - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file. (~/.aws/credentials). - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := sns.New(sess) - - result, err := svc.Publish(&sns.PublishInput{ - Message: msgPtr, - TopicArn: topicPtr, - }) - if err != nil { - fmt.Println(err.Error()) - os.Exit(1) - } - - fmt.Println(*result.MessageId) + msgPtr := flag.String("m", "", "The message to send to the subscribed users of the topic") + topicPtr := flag.String("t", "", "The ARN of the topic to which the user subscribes") + + flag.Parse() + + if *msgPtr == "" || *topicPtr == "" { + fmt.Println("You must supply a message and topic ARN") + fmt.Println("Usage: go run SnsPublish.go -m MESSAGE -t TOPIC-ARN") + os.Exit(1) + } + + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file. (~/.aws/credentials). + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := sns.New(sess) + + result, err := svc.Publish(&sns.PublishInput{ + Message: msgPtr, + TopicArn: topicPtr, + }) + if err != nil { + fmt.Println(err.Error()) + os.Exit(1) + } + + fmt.Println(*result.MessageId) } + // snippet-end:[sns.go.publish] diff --git a/go/example_code/sns/SnsSubscribe.go b/go/example_code/sns/SnsSubscribe.go index 05dcd81b8ec..056247b3d8a 100644 --- a/go/example_code/sns/SnsSubscribe.go +++ b/go/example_code/sns/SnsSubscribe.go @@ -1,72 +1,50 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[SnsSubscribe.go -e EMAIL -t TOPIC-ARN subscribes the user with email address EMAIL to the SNS topic with the ARN TOPIC-ARN.] -// snippet-keyword:[Amazon Simple Notification Service] -// snippet-keyword:[Amazon SNS] -// snippet-keyword:[Subscribe function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[sns] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-1-6] -/* - Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sns.go.subscribe] package main import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sns" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sns" - "flag" - "fmt" - "os" + "flag" + "fmt" + "os" ) func main() { - emailPtr := flag.String("e", "", "The email address of the user subscribing to the topic") - topicPtr := flag.String("t", "", "The ARN of the topic to which the user subscribes") - - flag.Parse() - - if *emailPtr == "" || *topicPtr == "" { - fmt.Println("You must supply an email address and topic ARN") - fmt.Println("Usage: go run SnsSubscribe.go -e EMAIL -t TOPIC-ARN") - os.Exit(1) - } - - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file. (~/.aws/credentials). - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := sns.New(sess) - - result, err := svc.Subscribe(&sns.SubscribeInput{ - Endpoint: emailPtr, - Protocol: aws.String("email"), - ReturnSubscriptionArn: aws.Bool(true), // Return the ARN, even if user has yet to confirm - TopicArn: topicPtr, - }) - if err != nil { - fmt.Println(err.Error()) - os.Exit(1) - } - - fmt.Println(*result.SubscriptionArn) + emailPtr := flag.String("e", "", "The email address of the user subscribing to the topic") + topicPtr := flag.String("t", "", "The ARN of the topic to which the user subscribes") + + flag.Parse() + + if *emailPtr == "" || *topicPtr == "" { + fmt.Println("You must supply an email address and topic ARN") + fmt.Println("Usage: go run SnsSubscribe.go -e EMAIL -t TOPIC-ARN") + os.Exit(1) + } + + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file. (~/.aws/credentials). + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := sns.New(sess) + + result, err := svc.Subscribe(&sns.SubscribeInput{ + Endpoint: emailPtr, + Protocol: aws.String("email"), + ReturnSubscriptionArn: aws.Bool(true), // Return the ARN, even if user has yet to confirm + TopicArn: topicPtr, + }) + if err != nil { + fmt.Println(err.Error()) + os.Exit(1) + } + + fmt.Println(*result.SubscriptionArn) } + // snippet-end:[sns.go.subscribe] diff --git a/go/example_code/sqs/sqs_changingvisibility.go b/go/example_code/sqs/sqs_changingvisibility.go index 298eff0cb4c..d830845e20d 100644 --- a/go/example_code/sqs/sqs_changingvisibility.go +++ b/go/example_code/sqs/sqs_changingvisibility.go @@ -1,89 +1,65 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Changes the visibility timeout for an SQS queue.] -// snippet-keyword:[Amazon Simple Queue Service] -// snippet-keyword:[Amazon SQS] -// snippet-keyword:[ChangeMessageVisibility function] -// snippet-keyword:[ReceiveMessage function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[sqs] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // Usage: // go run sqs_changingvisibility.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) - // Create a SQS service client. - svc := sqs.New(sess) + // Create a SQS service client. + svc := sqs.New(sess) - // URL to our queue - qURL := "QueueURL" + // URL to our queue + qURL := "QueueURL" - result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{ - AttributeNames: []*string{ - aws.String(sqs.MessageSystemAttributeNameSentTimestamp), - }, - MaxNumberOfMessages: aws.Int64(1), - MessageAttributeNames: []*string{ - aws.String(sqs.QueueAttributeNameAll), - }, - QueueUrl: &qURL, - }) + result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{ + AttributeNames: []*string{ + aws.String(sqs.MessageSystemAttributeNameSentTimestamp), + }, + MaxNumberOfMessages: aws.Int64(1), + MessageAttributeNames: []*string{ + aws.String(sqs.QueueAttributeNameAll), + }, + QueueUrl: &qURL, + }) - if err != nil { - fmt.Println("Error", err) - return - } + if err != nil { + fmt.Println("Error", err) + return + } - // Check if we have any messages - if len(result.Messages) == 0 { - fmt.Println("Received no messages") - return - } + // Check if we have any messages + if len(result.Messages) == 0 { + fmt.Println("Received no messages") + return + } - // 30 seconds timeout - duration := int64(30) - resultVisibility, err := svc.ChangeMessageVisibility(&sqs.ChangeMessageVisibilityInput{ - ReceiptHandle: result.Messages[0].ReceiptHandle, - QueueUrl: &qURL, - VisibilityTimeout: &duration, - }) + // 30 seconds timeout + duration := int64(30) + resultVisibility, err := svc.ChangeMessageVisibility(&sqs.ChangeMessageVisibilityInput{ + ReceiptHandle: result.Messages[0].ReceiptHandle, + QueueUrl: &qURL, + VisibilityTimeout: &duration, + }) - if err != nil { - fmt.Println("Visibility Error", err) - return - } + if err != nil { + fmt.Println("Visibility Error", err) + return + } - fmt.Println("Time Changed", resultVisibility) + fmt.Println("Time Changed", resultVisibility) } diff --git a/go/example_code/sqs/sqs_createqueues.go b/go/example_code/sqs/sqs_createqueues.go index 173e3ba97d2..96f566d5464 100644 --- a/go/example_code/sqs/sqs_createqueues.go +++ b/go/example_code/sqs/sqs_createqueues.go @@ -1,62 +1,39 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Creates an SQS queue.] -// snippet-keyword:[Amazon Simple Queue Service] -// snippet-keyword:[Amazon SQS] -// snippet-keyword:[CreateQueue function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[sqs] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // Usage: // go run sqs_createqueues.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create a SQS service client. - svc := sqs.New(sess) - - result, err := svc.CreateQueue(&sqs.CreateQueueInput{ - QueueName: aws.String("SQS_QUEUE_NAME"), - Attributes: map[string]*string{ - "DelaySeconds": aws.String("60"), - "MessageRetentionPeriod": aws.String("86400"), - }, - }) - if err != nil { - fmt.Println("Error", err) - return - } - - fmt.Println("Success", *result.QueueUrl) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create a SQS service client. + svc := sqs.New(sess) + + result, err := svc.CreateQueue(&sqs.CreateQueueInput{ + QueueName: aws.String("SQS_QUEUE_NAME"), + Attributes: map[string]*string{ + "DelaySeconds": aws.String("60"), + "MessageRetentionPeriod": aws.String("86400"), + }, + }) + if err != nil { + fmt.Println("Error", err) + return + } + + fmt.Println("Success", *result.QueueUrl) } diff --git a/go/example_code/sqs/sqs_deadletterqueue.go b/go/example_code/sqs/sqs_deadletterqueue.go index 764454f8279..55ef019aae3 100644 --- a/go/example_code/sqs/sqs_deadletterqueue.go +++ b/go/example_code/sqs/sqs_deadletterqueue.go @@ -1,77 +1,54 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Sets the attributes on an SQS queue.] -// snippet-keyword:[Amazon Simple Queue Service] -// snippet-keyword:[Amazon SQS] -// snippet-keyword:[SetQueueAttributes function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[sqs] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "fmt" + "encoding/json" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // Usage: // go run sqs_deadletterqueue.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create a SQS service client. - svc := sqs.New(sess) - - // Our redrive policy for our queue - policy := map[string]string{ - "deadLetterTargetArn": "SQS_QUEUE_ARN", - "maxReceiveCount": "10", - } - - // Marshal our policy to be used as input for our SetQueueAttributes - // call. - b, err := json.Marshal(policy) - if err != nil { - fmt.Println("Failed to marshal policy:", err) - return - } - - result, err := svc.SetQueueAttributes(&sqs.SetQueueAttributesInput{ - QueueUrl: aws.String("SQS_QUEUE_URL"), - Attributes: map[string]*string{ - sqs.QueueAttributeNameRedrivePolicy: aws.String(string(b)), - }, - }) - - if err != nil { - fmt.Println("Error", err) - return - } - - fmt.Println("Success", result) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create a SQS service client. + svc := sqs.New(sess) + + // Our redrive policy for our queue + policy := map[string]string{ + "deadLetterTargetArn": "SQS_QUEUE_ARN", + "maxReceiveCount": "10", + } + + // Marshal our policy to be used as input for our SetQueueAttributes + // call. + b, err := json.Marshal(policy) + if err != nil { + fmt.Println("Failed to marshal policy:", err) + return + } + + result, err := svc.SetQueueAttributes(&sqs.SetQueueAttributesInput{ + QueueUrl: aws.String("SQS_QUEUE_URL"), + Attributes: map[string]*string{ + sqs.QueueAttributeNameRedrivePolicy: aws.String(string(b)), + }, + }) + + if err != nil { + fmt.Println("Error", err) + return + } + + fmt.Println("Success", result) } diff --git a/go/example_code/sqs/sqs_deletemessage.go b/go/example_code/sqs/sqs_deletemessage.go index 74694937173..39c61924cd3 100644 --- a/go/example_code/sqs/sqs_deletemessage.go +++ b/go/example_code/sqs/sqs_deletemessage.go @@ -1,84 +1,60 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Deletes an SQS message.] -// snippet-keyword:[Amazon Simple Queue Service] -// snippet-keyword:[Amazon SQS] -// snippet-keyword:[DeleteMessage function] -// snippet-keyword:[ReceiveMessage function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[sqs] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // Usage: // go run sqs_deletemessage.go func main() { - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := sqs.New(sess) - - // URL to our queue - qURL := "QueueURL" - - result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{ - AttributeNames: []*string{ - aws.String(sqs.MessageSystemAttributeNameSentTimestamp), - }, - MessageAttributeNames: []*string{ - aws.String(sqs.QueueAttributeNameAll), - }, - QueueUrl: &qURL, - MaxNumberOfMessages: aws.Int64(1), - VisibilityTimeout: aws.Int64(20), // 20 seconds - WaitTimeSeconds: aws.Int64(0), - }) - - if err != nil { - fmt.Println("Error", err) - return - } - - if len(result.Messages) == 0 { - fmt.Println("Received no messages") - return - } - - resultDelete, err := svc.DeleteMessage(&sqs.DeleteMessageInput{ - QueueUrl: &qURL, - ReceiptHandle: result.Messages[0].ReceiptHandle, - }) - - if err != nil { - fmt.Println("Delete Error", err) - return - } - - fmt.Println("Message Deleted", resultDelete) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := sqs.New(sess) + + // URL to our queue + qURL := "QueueURL" + + result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{ + AttributeNames: []*string{ + aws.String(sqs.MessageSystemAttributeNameSentTimestamp), + }, + MessageAttributeNames: []*string{ + aws.String(sqs.QueueAttributeNameAll), + }, + QueueUrl: &qURL, + MaxNumberOfMessages: aws.Int64(1), + VisibilityTimeout: aws.Int64(20), // 20 seconds + WaitTimeSeconds: aws.Int64(0), + }) + + if err != nil { + fmt.Println("Error", err) + return + } + + if len(result.Messages) == 0 { + fmt.Println("Received no messages") + return + } + + resultDelete, err := svc.DeleteMessage(&sqs.DeleteMessageInput{ + QueueUrl: &qURL, + ReceiptHandle: result.Messages[0].ReceiptHandle, + }) + + if err != nil { + fmt.Println("Delete Error", err) + return + } + + fmt.Println("Message Deleted", resultDelete) } diff --git a/go/example_code/sqs/sqs_deletequeue.go b/go/example_code/sqs/sqs_deletequeue.go index 197ea2dae2c..e06e0f58acf 100644 --- a/go/example_code/sqs/sqs_deletequeue.go +++ b/go/example_code/sqs/sqs_deletequeue.go @@ -1,59 +1,36 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Deletes an SQS queue.] -// snippet-keyword:[Amazon Simple Queue Service] -// snippet-keyword:[Amazon SQS] -// snippet-keyword:[DeleteQueue function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[sqs] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // Usage: // go run sqs_deletequeue.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) - // Create a SQS service client. - svc := sqs.New(sess) + // Create a SQS service client. + svc := sqs.New(sess) - result, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ - QueueUrl: aws.String("SQS_QUEUE_URL"), - }) + result, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ + QueueUrl: aws.String("SQS_QUEUE_URL"), + }) - if err != nil { - fmt.Println("Error", err) - return - } + if err != nil { + fmt.Println("Error", err) + return + } - fmt.Println("Success", result) + fmt.Println("Success", result) } diff --git a/go/example_code/sqs/sqs_getqueueurl.go b/go/example_code/sqs/sqs_getqueueurl.go index c37d34e4ef8..92d07804a09 100644 --- a/go/example_code/sqs/sqs_getqueueurl.go +++ b/go/example_code/sqs/sqs_getqueueurl.go @@ -1,59 +1,36 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Gets the URL for an SQS queue.] -// snippet-keyword:[Amazon Simple Queue Service] -// snippet-keyword:[Amazon SQS] -// snippet-keyword:[GetQueueUrl function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[sqs] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // Usage: // go run sqs_getqueueurl.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) - // Create a SQS service client. - svc := sqs.New(sess) + // Create a SQS service client. + svc := sqs.New(sess) - result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ - QueueName: aws.String("SQS_QUEUE_NAME"), - }) + result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ + QueueName: aws.String("SQS_QUEUE_NAME"), + }) - if err != nil { - fmt.Println("Error", err) - return - } + if err != nil { + fmt.Println("Error", err) + return + } - fmt.Println("Success", *result.QueueUrl) + fmt.Println("Success", *result.QueueUrl) } diff --git a/go/example_code/sqs/sqs_listqueues.go b/go/example_code/sqs/sqs_listqueues.go index b0ebab211b6..4e90bff6607 100644 --- a/go/example_code/sqs/sqs_listqueues.go +++ b/go/example_code/sqs/sqs_listqueues.go @@ -1,65 +1,42 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Lists your SQS queues.] -// snippet-keyword:[Amazon Simple Queue Service] -// snippet-keyword:[Amazon SQS] -// snippet-keyword:[ListQueues function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[sqs] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // Usage: // go run sqs_listqueues.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2")}, - ) - - // Create a SQS service client. - svc := sqs.New(sess) - - // List the queues available in a given region. - result, err := svc.ListQueues(nil) - if err != nil { - fmt.Println("Error", err) - return - } - - fmt.Println("Success") - // As these are pointers, printing them out directly would not be useful. - for i, urls := range result.QueueUrls { - // Avoid dereferencing a nil pointer. - if urls == nil { - continue - } - fmt.Printf("%d: %s\n", i, *urls) - } + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2")}, + ) + + // Create a SQS service client. + svc := sqs.New(sess) + + // List the queues available in a given region. + result, err := svc.ListQueues(nil) + if err != nil { + fmt.Println("Error", err) + return + } + + fmt.Println("Success") + // As these are pointers, printing them out directly would not be useful. + for i, urls := range result.QueueUrls { + // Avoid dereferencing a nil pointer. + if urls == nil { + continue + } + fmt.Printf("%d: %s\n", i, *urls) + } } diff --git a/go/example_code/sqs/sqs_longpolling_create_queue.go b/go/example_code/sqs/sqs_longpolling_create_queue.go index 8ed89d0f72e..0e6e63229ef 100644 --- a/go/example_code/sqs/sqs_longpolling_create_queue.go +++ b/go/example_code/sqs/sqs_longpolling_create_queue.go @@ -1,94 +1,74 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Creates an SQS queue with long polling enabled.] -// snippet-keyword:[Amazon Simple Queue Service] -// snippet-keyword:[Amazon SQS] -// snippet-keyword:[CreateQueue function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[sqs] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-1-6] -/* - Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sqs.go.longpolling_create_queue.complete] package main // snippet-start:[sqs.go.longpolling_create_queue.imports] import ( - "flag" - "fmt" - "os" - "strconv" + "flag" + "fmt" + "os" + "strconv" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) + // snippet-end:[sqs.go.longpolling_create_queue.imports] // Creates a new SQS queue with long polling enabled. If the Queue already exists // no error will be returned. // // Usage: -// go run sqs_longpolling_create_queue.go -n queue_name -t timeout +// +// go run sqs_longpolling_create_queue.go -n queue_name -t timeout func main() { - // snippet-start:[sqs.go.longpolling_create_queue.vars] - namePtr := flag.String("n", "", "Queue name") - timeoutPtr := flag.Int("t", 20, "(Optional) Timeout in seconds for long polling") + // snippet-start:[sqs.go.longpolling_create_queue.vars] + namePtr := flag.String("n", "", "Queue name") + timeoutPtr := flag.Int("t", 20, "(Optional) Timeout in seconds for long polling") - flag.Parse() + flag.Parse() - if *namePtr == "" { - flag.PrintDefaults() - exitErrorf("Queue name required") - } - // snippet-end:[sqs.go.longpolling_create_queue.vars] + if *namePtr == "" { + flag.PrintDefaults() + exitErrorf("Queue name required") + } + // snippet-end:[sqs.go.longpolling_create_queue.vars] - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file. (~/.aws/credentials). - // snippet-start:[sqs.go.longpolling_create_queue.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[sqs.go.longpolling_create_queue.session] + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file. (~/.aws/credentials). + // snippet-start:[sqs.go.longpolling_create_queue.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[sqs.go.longpolling_create_queue.session] - // snippet-start:[sqs.go.longpolling_create_queue.create] - svc := sqs.New(sess) + // snippet-start:[sqs.go.longpolling_create_queue.create] + svc := sqs.New(sess) - // Create the Queue with long polling enabled - result, err := svc.CreateQueue(&sqs.CreateQueueInput{ - QueueName: namePtr, - Attributes: aws.StringMap(map[string]string{ - "ReceiveMessageWaitTimeSeconds": strconv.Itoa(*timeoutPtr), - }), - }) - if err != nil { - exitErrorf("Unable to create queue %q, %v.", *namePtr, err) - } + // Create the Queue with long polling enabled + result, err := svc.CreateQueue(&sqs.CreateQueueInput{ + QueueName: namePtr, + Attributes: aws.StringMap(map[string]string{ + "ReceiveMessageWaitTimeSeconds": strconv.Itoa(*timeoutPtr), + }), + }) + if err != nil { + exitErrorf("Unable to create queue %q, %v.", *namePtr, err) + } - fmt.Printf("Successfully created queue %q. URL: %s\n", *namePtr, - aws.StringValue(result.QueueUrl)) + fmt.Printf("Successfully created queue %q. URL: %s\n", *namePtr, + aws.StringValue(result.QueueUrl)) - // snippet-end:[sqs.go.longpolling_create_queue.create] + // snippet-end:[sqs.go.longpolling_create_queue.create] } // snippet-start:[sqs.go.longpolling_create_queue.exit] func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } + // snippet-end:[sqs.go.longpolling_create_queue.exit] // snippet-end:[sqs.go.longpolling_create_queue.complete] diff --git a/go/example_code/sqs/sqs_longpolling_existing_queue.go b/go/example_code/sqs/sqs_longpolling_existing_queue.go index ee70ae1aace..6a184ab4ca9 100644 --- a/go/example_code/sqs/sqs_longpolling_existing_queue.go +++ b/go/example_code/sqs/sqs_longpolling_existing_queue.go @@ -1,108 +1,87 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Enables long polling on an SQS queue.] -// snippet-keyword:[Amazon Simple Queue Service] -// snippet-keyword:[Amazon SQS] -// snippet-keyword:[GetQueueUrl function] -// snippet-keyword:[SetQueueAttributes function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[sqs] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-1-6] -/* - Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sqs.go.longpolling_existing_queue.complete] package main // snippet-start:[sqs.go.longpolling_existing_queue.imports] import ( - "flag" - "fmt" - "os" - "strconv" + "flag" + "fmt" + "os" + "strconv" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) + // snippet-end:[sqs.go.longpolling_existing_queue.imports] // Updates the existing queue to use the long polling option. // // Usage: -// go run sqs_longpolling_existing_queue.go -n queue_name -t timeout +// +// go run sqs_longpolling_existing_queue.go -n queue_name -t timeout func main() { - // snippet-start:[sqs.go.longpolling_existing_queue.vars] - namePtr := flag.String("n", "", "Queue name") - timeoutPtr := flag.Int("t", 20, "(Optional) Timeout in seconds for long polling") + // snippet-start:[sqs.go.longpolling_existing_queue.vars] + namePtr := flag.String("n", "", "Queue name") + timeoutPtr := flag.Int("t", 20, "(Optional) Timeout in seconds for long polling") - flag.Parse() + flag.Parse() - if *namePtr == "" { - flag.PrintDefaults() - exitErrorf("Queue name required") - } - // snippet-end:[sqs.go.longpolling_existing_queue.vars] + if *namePtr == "" { + flag.PrintDefaults() + exitErrorf("Queue name required") + } + // snippet-end:[sqs.go.longpolling_existing_queue.vars] - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file. (~/.aws/credentials). - // snippet-start:[sqs.go.longpolling_existing_queue.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file. (~/.aws/credentials). + // snippet-start:[sqs.go.longpolling_existing_queue.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - svc := sqs.New(sess) - // snippet-end:[sqs.go.longpolling_existing_queue.session] + svc := sqs.New(sess) + // snippet-end:[sqs.go.longpolling_existing_queue.session] - // Need to convert the queue name into a URL. Make the GetQueueUrl - // API call to retrieve the URL. This is needed for setting attributes - // on the queue. - // snippet-start:[sqs.go.longpolling_existing_queue.url] - resultURL, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ - QueueName: namePtr, - }) - if err != nil { - if aerr, ok := err.(awserr.Error); ok && aerr.Code() == sqs.ErrCodeQueueDoesNotExist { - exitErrorf("Unable to find queue %q.", *namePtr) - } - exitErrorf("Unable to get queue %q, %v.", *namePtr, err) - } - // snippet-end:[sqs.go.longpolling_existing_queue.url] + // Need to convert the queue name into a URL. Make the GetQueueUrl + // API call to retrieve the URL. This is needed for setting attributes + // on the queue. + // snippet-start:[sqs.go.longpolling_existing_queue.url] + resultURL, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ + QueueName: namePtr, + }) + if err != nil { + if aerr, ok := err.(awserr.Error); ok && aerr.Code() == sqs.ErrCodeQueueDoesNotExist { + exitErrorf("Unable to find queue %q.", *namePtr) + } + exitErrorf("Unable to get queue %q, %v.", *namePtr, err) + } + // snippet-end:[sqs.go.longpolling_existing_queue.url] - // Update the queue enabling long polling. - // snippet-start:[sqs.go.longpolling_existing_queue.enable] - _, err = svc.SetQueueAttributes(&sqs.SetQueueAttributesInput{ - QueueUrl: resultURL.QueueUrl, - Attributes: aws.StringMap(map[string]string{ - "ReceiveMessageWaitTimeSeconds": strconv.Itoa(*timeoutPtr), - }), - }) - if err != nil { - exitErrorf("Unable to update queue %q, %v.", *namePtr, err) - } + // Update the queue enabling long polling. + // snippet-start:[sqs.go.longpolling_existing_queue.enable] + _, err = svc.SetQueueAttributes(&sqs.SetQueueAttributesInput{ + QueueUrl: resultURL.QueueUrl, + Attributes: aws.StringMap(map[string]string{ + "ReceiveMessageWaitTimeSeconds": strconv.Itoa(*timeoutPtr), + }), + }) + if err != nil { + exitErrorf("Unable to update queue %q, %v.", *namePtr, err) + } - fmt.Printf("Successfully updated queue %q.\n", *namePtr) - // snippet-end:[sqs.go.longpolling_existing_queue.enable] + fmt.Printf("Successfully updated queue %q.\n", *namePtr) + // snippet-end:[sqs.go.longpolling_existing_queue.enable] } // snippet-start:[sqs.go.longpolling_existing_queue.error] func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } + // snippet-end:[sqs.go.longpolling_existing_queue.error] // snippet-end:[sqs.go.longpolling_existing_queue.complete] diff --git a/go/example_code/sqs/sqs_longpolling_receive_message.go b/go/example_code/sqs/sqs_longpolling_receive_message.go index 8d8598223af..b6b653884c1 100644 --- a/go/example_code/sqs/sqs_longpolling_receive_message.go +++ b/go/example_code/sqs/sqs_longpolling_receive_message.go @@ -1,115 +1,94 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Enables long polling on message receipt.] -// snippet-keyword:[Amazon Simple Queue Service] -// snippet-keyword:[Amazon SQS] -// snippet-keyword:[GetQueueUrl function] -// snippet-keyword:[ReceiveMessage function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[sqs] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-1-6] -/* - Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sqs.go.longpolling_receive_message.complete] package main // snippet-start:[sqs.go.longpolling_receive_message.imports] import ( - "flag" - "fmt" - "os" + "flag" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) + // snippet-end:[sqs.go.longpolling_receive_message.imports] // Receive message from Queue with long polling enabled. // // Usage: -// go run sqs_longpolling_receive_message.go -n queue_name -t timeout +// +// go run sqs_longpolling_receive_message.go -n queue_name -t timeout func main() { - // snippet-start:[sqs.go.longpolling_receive_message.vars] - namePtr := flag.String("n", "", "Queue name") - timeoutPtr := flag.Int64("t", 20, "(Optional) Timeout in seconds for long polling") + // snippet-start:[sqs.go.longpolling_receive_message.vars] + namePtr := flag.String("n", "", "Queue name") + timeoutPtr := flag.Int64("t", 20, "(Optional) Timeout in seconds for long polling") - flag.Parse() + flag.Parse() - if *namePtr == "" { - flag.PrintDefaults() - exitErrorf("Queue name required") - } - // snippet-end:[sqs.go.longpolling_receive_message.vars] + if *namePtr == "" { + flag.PrintDefaults() + exitErrorf("Queue name required") + } + // snippet-end:[sqs.go.longpolling_receive_message.vars] - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file. (~/.aws/credentials). - // snippet-start:[sqs.go.longpolling_receive_message.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file. (~/.aws/credentials). + // snippet-start:[sqs.go.longpolling_receive_message.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - svc := sqs.New(sess) - // snippet-end:[sqs.go.longpolling_receive_message.session] + svc := sqs.New(sess) + // snippet-end:[sqs.go.longpolling_receive_message.session] - // Need to convert the queue name into a URL. Make the GetQueueUrl - // API call to retrieve the URL. This is needed for receiving messages - // from the queue. - // snippet-start:[sqs.go.longpolling_receive_message.url] - resultURL, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ - QueueName: namePtr, - }) - if err != nil { - if aerr, ok := err.(awserr.Error); ok && aerr.Code() == sqs.ErrCodeQueueDoesNotExist { - exitErrorf("Unable to find queue %q.", *namePtr) - } - exitErrorf("Unable to queue %q, %v.", *namePtr, err) - } - // snippet-end:[sqs.go.longpolling_receive_message.url] + // Need to convert the queue name into a URL. Make the GetQueueUrl + // API call to retrieve the URL. This is needed for receiving messages + // from the queue. + // snippet-start:[sqs.go.longpolling_receive_message.url] + resultURL, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ + QueueName: namePtr, + }) + if err != nil { + if aerr, ok := err.(awserr.Error); ok && aerr.Code() == sqs.ErrCodeQueueDoesNotExist { + exitErrorf("Unable to find queue %q.", *namePtr) + } + exitErrorf("Unable to queue %q, %v.", *namePtr, err) + } + // snippet-end:[sqs.go.longpolling_receive_message.url] - // Receive a message from the SQS queue with long polling enabled. - // snippet-start:[sqs.go.longpolling_receive_message.receive] - result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{ - QueueUrl: resultURL.QueueUrl, - AttributeNames: aws.StringSlice([]string{ - "SentTimestamp", - }), - MaxNumberOfMessages: aws.Int64(1), - MessageAttributeNames: aws.StringSlice([]string{ - "All", - }), - WaitTimeSeconds: timeoutPtr, - }) - if err != nil { - exitErrorf("Unable to receive message from queue %q, %v.", *namePtr, err) - } + // Receive a message from the SQS queue with long polling enabled. + // snippet-start:[sqs.go.longpolling_receive_message.receive] + result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{ + QueueUrl: resultURL.QueueUrl, + AttributeNames: aws.StringSlice([]string{ + "SentTimestamp", + }), + MaxNumberOfMessages: aws.Int64(1), + MessageAttributeNames: aws.StringSlice([]string{ + "All", + }), + WaitTimeSeconds: timeoutPtr, + }) + if err != nil { + exitErrorf("Unable to receive message from queue %q, %v.", *namePtr, err) + } - fmt.Printf("Received %d messages.\n", len(result.Messages)) - if len(result.Messages) > 0 { - fmt.Println(result.Messages) - } - // snippet-end:[sqs.go.longpolling_receive_message.receive] + fmt.Printf("Received %d messages.\n", len(result.Messages)) + if len(result.Messages) > 0 { + fmt.Println(result.Messages) + } + // snippet-end:[sqs.go.longpolling_receive_message.receive] } // snippet-start:[sqs.go.longpolling_receive_message.exit] func exitErrorf(msg string, args ...interface{}) { - fmt.Fprintf(os.Stderr, msg+"\n", args...) - os.Exit(1) + fmt.Fprintf(os.Stderr, msg+"\n", args...) + os.Exit(1) } + // snippet-end:[sqs.go.longpolling_receive_message.exit] // snippet-end:[sqs.go.longpolling_receive_message.complete] diff --git a/go/example_code/sqs/sqs_receive_message.go b/go/example_code/sqs/sqs_receive_message.go index cdf3062889a..37e0b94acdd 100644 --- a/go/example_code/sqs/sqs_receive_message.go +++ b/go/example_code/sqs/sqs_receive_message.go @@ -1,72 +1,50 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[AWS] -// snippet-sourcedescription:[Receives an SQS message.] -// snippet-keyword:[Amazon Simple Queue Service] -// snippet-keyword:[Amazon SQS] -// snippet-keyword:[ReceiveMessage function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[sqs] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sqs.go.receive_message] package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // Usage: // go run sqs_receive_message.go func main() { - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := sqs.New(sess) - - // URL to our queue - qURL := "QueueURL" - - result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{ - AttributeNames: []*string{ - aws.String(sqs.MessageSystemAttributeNameSentTimestamp), - }, - MessageAttributeNames: []*string{ - aws.String(sqs.QueueAttributeNameAll), - }, - QueueUrl: &qURL, - MaxNumberOfMessages: aws.Int64(10), - VisibilityTimeout: aws.Int64(60), // 60 seconds - WaitTimeSeconds: aws.Int64(0), - }) - if err != nil { - fmt.Println("Error", err) - return - } - if len(result.Messages) == 0 { - fmt.Println("Received no messages") - return - } - - fmt.Printf("Success: %+v\n", result.Messages) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := sqs.New(sess) + + // URL to our queue + qURL := "QueueURL" + + result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{ + AttributeNames: []*string{ + aws.String(sqs.MessageSystemAttributeNameSentTimestamp), + }, + MessageAttributeNames: []*string{ + aws.String(sqs.QueueAttributeNameAll), + }, + QueueUrl: &qURL, + MaxNumberOfMessages: aws.Int64(10), + VisibilityTimeout: aws.Int64(60), // 60 seconds + WaitTimeSeconds: aws.Int64(0), + }) + if err != nil { + fmt.Println("Error", err) + return + } + if len(result.Messages) == 0 { + fmt.Println("Received no messages") + return + } + + fmt.Printf("Success: %+v\n", result.Messages) } + // snippet-end:[sqs.go.receive_message] diff --git a/go/example_code/sqs/sqs_sendmessage.go b/go/example_code/sqs/sqs_sendmessage.go index 74c7281dc59..6bef23afb88 100644 --- a/go/example_code/sqs/sqs_sendmessage.go +++ b/go/example_code/sqs/sqs_sendmessage.go @@ -1,75 +1,52 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Sends a message to an SQS queue.] -// snippet-keyword:[Amazon Simple Queue Service] -// snippet-keyword:[Amazon SQS] -// snippet-keyword:[SendMessage function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[sqs] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-03-16] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // Usage: // go run sqs_sendmessage.go func main() { - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := sqs.New(sess) - - // URL to our queue - qURL := "QueueURL" - - result, err := svc.SendMessage(&sqs.SendMessageInput{ - DelaySeconds: aws.Int64(10), - MessageAttributes: map[string]*sqs.MessageAttributeValue{ - "Title": &sqs.MessageAttributeValue{ - DataType: aws.String("String"), - StringValue: aws.String("The Whistler"), - }, - "Author": &sqs.MessageAttributeValue{ - DataType: aws.String("String"), - StringValue: aws.String("John Grisham"), - }, - "WeeksOn": &sqs.MessageAttributeValue{ - DataType: aws.String("Number"), - StringValue: aws.String("6"), - }, - }, - MessageBody: aws.String("Information about current NY Times fiction bestseller for week of 12/11/2016."), - QueueUrl: &qURL, - }) - - if err != nil { - fmt.Println("Error", err) - return - } - - fmt.Println("Success", *result.MessageId) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := sqs.New(sess) + + // URL to our queue + qURL := "QueueURL" + + result, err := svc.SendMessage(&sqs.SendMessageInput{ + DelaySeconds: aws.Int64(10), + MessageAttributes: map[string]*sqs.MessageAttributeValue{ + "Title": &sqs.MessageAttributeValue{ + DataType: aws.String("String"), + StringValue: aws.String("The Whistler"), + }, + "Author": &sqs.MessageAttributeValue{ + DataType: aws.String("String"), + StringValue: aws.String("John Grisham"), + }, + "WeeksOn": &sqs.MessageAttributeValue{ + DataType: aws.String("Number"), + StringValue: aws.String("6"), + }, + }, + MessageBody: aws.String("Information about current NY Times fiction bestseller for week of 12/11/2016."), + QueueUrl: &qURL, + }) + + if err != nil { + fmt.Println("Error", err) + return + } + + fmt.Println("Success", *result.MessageId) } diff --git a/go/example_code/sts/sts_assume_role.go b/go/example_code/sts/sts_assume_role.go index fc8b7d521d2..5f993da4b6d 100644 --- a/go/example_code/sts/sts_assume_role.go +++ b/go/example_code/sts/sts_assume_role.go @@ -1,65 +1,47 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[AWS] -// snippet-sourcedescription:[sts_assume_role.go creates a set of temporary security credentials.] -// snippet-keyword:[Amazon Security Token Service] -// snippet-keyword:[Amazon STS] -// snippet-keyword:[AssumeRole function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[sts] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[sts.go.assume_role] package main import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sts" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sts" ) // Usage: // go run sts_assume_role.go func main() { - // Initialize a session in us-west-2 that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-west-2"), - }) - - if err != nil { - fmt.Println("NewSession Error", err) - return - } - - // Create a STS client - svc := sts.New(sess) - - roleToAssumeArn := "arn:aws:iam::123456789012:role/roleName" - sessionName := "test_session" - result, err := svc.AssumeRole(&sts.AssumeRoleInput{ - RoleArn: &roleToAssumeArn, - RoleSessionName: &sessionName, - }) - - if err != nil { - fmt.Println("AssumeRole Error", err) - return - } - - fmt.Println(result.AssumedRoleUser) + // Initialize a session in us-west-2 that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-west-2"), + }) + + if err != nil { + fmt.Println("NewSession Error", err) + return + } + + // Create a STS client + svc := sts.New(sess) + + roleToAssumeArn := "arn:aws:iam::123456789012:role/roleName" + sessionName := "test_session" + result, err := svc.AssumeRole(&sts.AssumeRoleInput{ + RoleArn: &roleToAssumeArn, + RoleSessionName: &sessionName, + }) + + if err != nil { + fmt.Println("AssumeRole Error", err) + return + } + + fmt.Println(result.AssumedRoleUser) } + // snippet-end:[sts.go.assume_role] diff --git a/go/example_code/workdocs/wd_list_user_docs.go b/go/example_code/workdocs/wd_list_user_docs.go index 4f1a861a1c3..f280ff97e52 100644 --- a/go/example_code/workdocs/wd_list_user_docs.go +++ b/go/example_code/workdocs/wd_list_user_docs.go @@ -1,104 +1,82 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Lists the WorkDocs documents for a user.] -// snippet-keyword:[Amazon WorkDocs] -// snippet-keyword:[DescribeFolderContents function] -// snippet-keyword:[DescribeUsers function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[workdocs] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-1-6] -/* - Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[workdocs.go.list_user_docs.complete] package main // snippet-start:[workdocs.go.list_user_docs.imports] import ( - "os" + "os" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/workdocs" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/workdocs" - "flag" - "fmt" + "flag" + "fmt" ) // snippet-end:[workdocs.go.list_user_docs.imports] func main() { - // snippet-start:[workdocs.go.list_user_docs.vars] - userPtr := flag.String("u", "", "User for whom info is retrieved") - orgPtr := flag.String("o", "", "Your organization ID") - - flag.Parse() - - if *userPtr == "" || *orgPtr == "" { - flag.PrintDefaults() - os.Exit(1) - } - // snippet-end:[workdocs.go.list_user_docs.vars] - - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file. (~/.aws/credentials). - // snippet-start:[workdocs.go.list_user_docs.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := workdocs.New(sess) - // snippet-end:[workdocs.go.list_user_docs.session] - - // snippet-start:[workdocs.go.list_user_docs.root_folder] - input := new(workdocs.DescribeUsersInput) - input.OrganizationId = orgPtr - input.Query = userPtr - - result, err := svc.DescribeUsers(input) - if err != nil { - fmt.Println("Error getting user info", err) - return - } - - var folderID = "" - - if *result.TotalNumberOfUsers == 1 { - for _, user := range result.Users { - folderID = *user.RootFolderId - } - // snippet-end:[workdocs.go.list_user_docs.root_folder] - - // snippet-start:[workdocs.go.list_user_docs.describe] - result, err := svc.DescribeFolderContents(&workdocs.DescribeFolderContentsInput{FolderId: &folderID}) - - if err != nil { - fmt.Println("Error getting docs for user", err) - return - } - - fmt.Println(*userPtr + " docs:") - fmt.Println("") - - for _, doc := range result.Documents { - fmt.Println(*doc.LatestVersionMetadata.Name) - fmt.Println(" Size: ", *doc.LatestVersionMetadata.Size, "(bytes)") - fmt.Println(" Last modified:", *doc.LatestVersionMetadata.ModifiedTimestamp) - fmt.Println("") - } - // snippet-end:[workdocs.go.list_user_docs.describe] - } + // snippet-start:[workdocs.go.list_user_docs.vars] + userPtr := flag.String("u", "", "User for whom info is retrieved") + orgPtr := flag.String("o", "", "Your organization ID") + + flag.Parse() + + if *userPtr == "" || *orgPtr == "" { + flag.PrintDefaults() + os.Exit(1) + } + // snippet-end:[workdocs.go.list_user_docs.vars] + + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file. (~/.aws/credentials). + // snippet-start:[workdocs.go.list_user_docs.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := workdocs.New(sess) + // snippet-end:[workdocs.go.list_user_docs.session] + + // snippet-start:[workdocs.go.list_user_docs.root_folder] + input := new(workdocs.DescribeUsersInput) + input.OrganizationId = orgPtr + input.Query = userPtr + + result, err := svc.DescribeUsers(input) + if err != nil { + fmt.Println("Error getting user info", err) + return + } + + var folderID = "" + + if *result.TotalNumberOfUsers == 1 { + for _, user := range result.Users { + folderID = *user.RootFolderId + } + // snippet-end:[workdocs.go.list_user_docs.root_folder] + + // snippet-start:[workdocs.go.list_user_docs.describe] + result, err := svc.DescribeFolderContents(&workdocs.DescribeFolderContentsInput{FolderId: &folderID}) + + if err != nil { + fmt.Println("Error getting docs for user", err) + return + } + + fmt.Println(*userPtr + " docs:") + fmt.Println("") + + for _, doc := range result.Documents { + fmt.Println(*doc.LatestVersionMetadata.Name) + fmt.Println(" Size: ", *doc.LatestVersionMetadata.Size, "(bytes)") + fmt.Println(" Last modified:", *doc.LatestVersionMetadata.ModifiedTimestamp) + fmt.Println("") + } + // snippet-end:[workdocs.go.list_user_docs.describe] + } } + // snippet-end:[workdocs.go.list_user_docs.complete] diff --git a/go/example_code/workdocs/wd_list_users.go b/go/example_code/workdocs/wd_list_users.go index 087638da4b3..095b9cf52bf 100644 --- a/go/example_code/workdocs/wd_list_users.go +++ b/go/example_code/workdocs/wd_list_users.go @@ -1,40 +1,19 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourceauthor:[Doug-AWS] -// snippet-sourcedescription:[Lists the WorkDocs users.] -// snippet-keyword:[Amazon WorkDocs] -// snippet-keyword:[DescribeUsers function] -// snippet-keyword:[Go] -// snippet-sourcesyntax:[go] -// snippet-service:[workdocs] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-1-6] -/* - Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[workdocs.go.list_users.complete] package main // snippet-start:[workdocs.go.list_users.imports] import ( - "os" + "os" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/workdocs" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/workdocs" - "flag" - "fmt" + "flag" + "fmt" ) + // snippet-end:[workdocs.go.list_users.imports] /* @@ -45,68 +24,69 @@ import ( */ func main() { - // snippet-start:[workdocs.go.list_users.vars] - orgPtr := flag.String("o", "", "The ID of your organization") - userPtr := flag.String("u", "", "User for whom info is retrieved") - - flag.Parse() - - if *orgPtr == "" { - fmt.Println("You must supply the organization ID") - flag.PrintDefaults() - os.Exit(1) - } - // snippet-end:[workdocs.go.list_users.vars] - - // snippet-start:[workdocs.go.list_users.input] - input := new(workdocs.DescribeUsersInput) - input.OrganizationId = orgPtr - - // Show all users if we don't get a user name - if *userPtr == "" { - fmt.Println("Getting info about all users") - } else { - fmt.Println("Getting info about user " + *userPtr) - input.Query = userPtr - } - // snippet-end:[workdocs.go.list_users.input] - - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file. (~/.aws/credentials). - // snippet-start:[workdocs.go.list_users.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := workdocs.New(sess) - // snippet-end:[workdocs.go.list_users.session] - - fmt.Println("") - - // snippet-start:[workdocs.go.list_users.describe] - result, err := svc.DescribeUsers(input) - if err != nil { - fmt.Println("Error getting user info", err) - return - } - - if *userPtr == "" { - fmt.Println("Found", *result.TotalNumberOfUsers, "users") - fmt.Println("") - } - - for _, user := range result.Users { - fmt.Println("Username: " + *user.Username) - - if *userPtr != "" { - fmt.Println("Firstname: " + *user.GivenName) - fmt.Println("Lastname: " + *user.Surname) - fmt.Println("Email: " + *user.EmailAddress) - fmt.Println("Root folder " + *user.RootFolderId) - } - - fmt.Println("") - } - // snippet-end:[workdocs.go.list_users.describe] + // snippet-start:[workdocs.go.list_users.vars] + orgPtr := flag.String("o", "", "The ID of your organization") + userPtr := flag.String("u", "", "User for whom info is retrieved") + + flag.Parse() + + if *orgPtr == "" { + fmt.Println("You must supply the organization ID") + flag.PrintDefaults() + os.Exit(1) + } + // snippet-end:[workdocs.go.list_users.vars] + + // snippet-start:[workdocs.go.list_users.input] + input := new(workdocs.DescribeUsersInput) + input.OrganizationId = orgPtr + + // Show all users if we don't get a user name + if *userPtr == "" { + fmt.Println("Getting info about all users") + } else { + fmt.Println("Getting info about user " + *userPtr) + input.Query = userPtr + } + // snippet-end:[workdocs.go.list_users.input] + + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file. (~/.aws/credentials). + // snippet-start:[workdocs.go.list_users.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := workdocs.New(sess) + // snippet-end:[workdocs.go.list_users.session] + + fmt.Println("") + + // snippet-start:[workdocs.go.list_users.describe] + result, err := svc.DescribeUsers(input) + if err != nil { + fmt.Println("Error getting user info", err) + return + } + + if *userPtr == "" { + fmt.Println("Found", *result.TotalNumberOfUsers, "users") + fmt.Println("") + } + + for _, user := range result.Users { + fmt.Println("Username: " + *user.Username) + + if *userPtr != "" { + fmt.Println("Firstname: " + *user.GivenName) + fmt.Println("Lastname: " + *user.Surname) + fmt.Println("Email: " + *user.EmailAddress) + fmt.Println("Root folder " + *user.RootFolderId) + } + + fmt.Println("") + } + // snippet-end:[workdocs.go.list_users.describe] } + // snippet-end:[workdocs.go.list_users.complete] diff --git a/go/iam/AccessKeyLastUsed/AccessKeyLastUsed_test.go b/go/iam/AccessKeyLastUsed/AccessKeyLastUsed_test.go index f444df9081b..f455a4b442c 100644 --- a/go/iam/AccessKeyLastUsed/AccessKeyLastUsed_test.go +++ b/go/iam/AccessKeyLastUsed/AccessKeyLastUsed_test.go @@ -1,55 +1,56 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/iam/iamiface" ) // Define a mock struct to use in unit tests type mockIAMClient struct { - iamiface.IAMAPI + iamiface.IAMAPI } func (m *mockIAMClient) GetAccessKeyLastUsed(input *iam.GetAccessKeyLastUsedInput) (*iam.GetAccessKeyLastUsedOutput, error) { - // Check that required inputs exist - if input.AccessKeyId == nil || *input.AccessKeyId == "" { - return nil, errors.New("GetAccessKeyLastUsedInput.AccessKeyId is nil or an empty string") - } - - resp := iam.GetAccessKeyLastUsedOutput{ - AccessKeyLastUsed: &iam.AccessKeyLastUsed{ - LastUsedDate: aws.Time(time.Now()), - Region: aws.String("REGION"), - ServiceName: aws.String("SERVICE-NAME"), - }, - UserName: aws.String("MrMagoo"), - } - return &resp, nil + // Check that required inputs exist + if input.AccessKeyId == nil || *input.AccessKeyId == "" { + return nil, errors.New("GetAccessKeyLastUsedInput.AccessKeyId is nil or an empty string") + } + + resp := iam.GetAccessKeyLastUsedOutput{ + AccessKeyLastUsed: &iam.AccessKeyLastUsed{ + LastUsedDate: aws.Time(time.Now()), + Region: aws.String("REGION"), + ServiceName: aws.String("SERVICE-NAME"), + }, + UserName: aws.String("MrMagoo"), + } + return &resp, nil } func TestAccessKeyLastUsed(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - keyID := "test-access-key" + // mock resource + keyID := "test-access-key" - mockSvc := &mockIAMClient{} + mockSvc := &mockIAMClient{} - result, err := WhenWasKeyUsed(mockSvc, &keyID) - if err != nil { - t.Fatal(err) - } + result, err := WhenWasKeyUsed(mockSvc, &keyID) + if err != nil { + t.Fatal(err) + } - t.Log("Access key was last used " + (*result.AccessKeyLastUsed.LastUsedDate).Format("2006-01-02 15:04:05 Monday")) - t.Log("For service " + *result.AccessKeyLastUsed.ServiceName + " in region " + *result.AccessKeyLastUsed.Region) + t.Log("Access key was last used " + (*result.AccessKeyLastUsed.LastUsedDate).Format("2006-01-02 15:04:05 Monday")) + t.Log("For service " + *result.AccessKeyLastUsed.ServiceName + " in region " + *result.AccessKeyLastUsed.Region) } diff --git a/go/iam/AttachUserPolicy/AttachUserPolicy_test.go b/go/iam/AttachUserPolicy/AttachUserPolicy_test.go index e189f51a21a..7909e0484f6 100644 --- a/go/iam/AttachUserPolicy/AttachUserPolicy_test.go +++ b/go/iam/AttachUserPolicy/AttachUserPolicy_test.go @@ -1,45 +1,46 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/iam/iamiface" ) // Define a mock struct to use in unit tests type mockIAMClient struct { - iamiface.IAMAPI + iamiface.IAMAPI } func (m *mockIAMClient) AttachRolePolicy(input *iam.AttachRolePolicyInput) (*iam.AttachRolePolicyOutput, error) { - // Check that required inputs exist - if input.PolicyArn == nil || *input.PolicyArn == "" || input.RoleName == nil || *input.RoleName == "" { - return nil, errors.New("AttacheRolePolicyInput.PolicyArn or AttachRolePolicyInput.RoleName is nil or an empty string") - } + // Check that required inputs exist + if input.PolicyArn == nil || *input.PolicyArn == "" || input.RoleName == nil || *input.RoleName == "" { + return nil, errors.New("AttacheRolePolicyInput.PolicyArn or AttachRolePolicyInput.RoleName is nil or an empty string") + } - resp := iam.AttachRolePolicyOutput{} - return &resp, nil + resp := iam.AttachRolePolicyOutput{} + return &resp, nil } func TestAttachRolePolicy(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - roleName := "test-role" + // mock resource + roleName := "test-role" - mockSvc := &mockIAMClient{} + mockSvc := &mockIAMClient{} - err := AttachDynamoFullPolicy(mockSvc, &roleName) - if err != nil { - t.Fatal(err) - } + err := AttachDynamoFullPolicy(mockSvc, &roleName) + if err != nil { + t.Fatal(err) + } - t.Log("Attached DynamoDB full-access policy to role " + roleName) + t.Log("Attached DynamoDB full-access policy to role " + roleName) } diff --git a/go/iam/CreateAccessKey/CreateAccessKey_test.go b/go/iam/CreateAccessKey/CreateAccessKey_test.go index 9cc773b57bd..53b705523f6 100644 --- a/go/iam/CreateAccessKey/CreateAccessKey_test.go +++ b/go/iam/CreateAccessKey/CreateAccessKey_test.go @@ -1,52 +1,53 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/iam/iamiface" ) // Define a mock struct to use in unit tests type mockIAMClient struct { - iamiface.IAMAPI + iamiface.IAMAPI } func (m *mockIAMClient) CreateAccessKey(input *iam.CreateAccessKeyInput) (*iam.CreateAccessKeyOutput, error) { - // Check that required inputs exist - if input.UserName == nil || *input.UserName == "" { - return nil, errors.New("The CreateAccessKeyInput.Username is nil or ") - } - - resp := iam.CreateAccessKeyOutput{ - AccessKey: &iam.AccessKey{ - AccessKeyId: aws.String("abc123xyz"), - SecretAccessKey: aws.String("stu789"), - }, - } - - return &resp, nil + // Check that required inputs exist + if input.UserName == nil || *input.UserName == "" { + return nil, errors.New("The CreateAccessKeyInput.Username is nil or ") + } + + resp := iam.CreateAccessKeyOutput{ + AccessKey: &iam.AccessKey{ + AccessKeyId: aws.String("abc123xyz"), + SecretAccessKey: aws.String("stu789"), + }, + } + + return &resp, nil } func TestCreateAccessKey(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - userName := "test-user" + // mock resource + userName := "test-user" - mockSvc := &mockIAMClient{} + mockSvc := &mockIAMClient{} - result, err := MakeAccessKey(mockSvc, &userName) - if err != nil { - t.Fatal(err) - } + result, err := MakeAccessKey(mockSvc, &userName) + if err != nil { + t.Fatal(err) + } - t.Log("Created new access key with ID: " + *result.AccessKey.AccessKeyId + " and secret key: " + *result.AccessKey.SecretAccessKey) + t.Log("Created new access key with ID: " + *result.AccessKey.AccessKeyId + " and secret key: " + *result.AccessKey.SecretAccessKey) } diff --git a/go/iam/CreateAccountAlias/CreateAccountAlias_test.go b/go/iam/CreateAccountAlias/CreateAccountAlias_test.go index c3f2c4eecca..fb9dcf965f2 100644 --- a/go/iam/CreateAccountAlias/CreateAccountAlias_test.go +++ b/go/iam/CreateAccountAlias/CreateAccountAlias_test.go @@ -1,45 +1,46 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/iam/iamiface" ) // Define a mock struct to use in unit tests type mockIAMClient struct { - iamiface.IAMAPI + iamiface.IAMAPI } func (m *mockIAMClient) CreateAccountAlias(input *iam.CreateAccountAliasInput) (*iam.CreateAccountAliasOutput, error) { - // Check that required inputs exist - if input.AccountAlias == nil || *input.AccountAlias == "" { - return nil, errors.New("CreateAccountAliasInput.AccountAlias cannot be nil or an empty string") - } + // Check that required inputs exist + if input.AccountAlias == nil || *input.AccountAlias == "" { + return nil, errors.New("CreateAccountAliasInput.AccountAlias cannot be nil or an empty string") + } - resp := iam.CreateAccountAliasOutput{} - return &resp, nil + resp := iam.CreateAccountAliasOutput{} + return &resp, nil } func TestCreateAccountAlias(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - alias := "test-alias" + // mock resource + alias := "test-alias" - mockSvc := &mockIAMClient{} + mockSvc := &mockIAMClient{} - err := MakeAccountAlias(mockSvc, &alias) - if err != nil { - t.Fatal(err) - } + err := MakeAccountAlias(mockSvc, &alias) + if err != nil { + t.Fatal(err) + } - t.Log("Created account alias " + alias) + t.Log("Created account alias " + alias) } diff --git a/go/iam/CreatePolicy/CreatePolicy_test.go b/go/iam/CreatePolicy/CreatePolicy_test.go index 9a198bb6dc2..23103c0ac87 100644 --- a/go/iam/CreatePolicy/CreatePolicy_test.go +++ b/go/iam/CreatePolicy/CreatePolicy_test.go @@ -1,44 +1,45 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/iam/iamiface" ) // Define a mock struct to use in unit tests type mockIAMClient struct { - iamiface.IAMAPI + iamiface.IAMAPI } func (m *mockIAMClient) CreatePolicy(input *iam.CreatePolicyInput) (*iam.CreatePolicyOutput, error) { - // Check that required inputs exist - if input.PolicyDocument == nil || *input.PolicyDocument == "" || input.PolicyName == nil || *input.PolicyName == "" { - return nil, errors.New("CreatePolicyInput.PolicyDocument or CreatePolicyInput.PolicyName is nil or an empty string") - } + // Check that required inputs exist + if input.PolicyDocument == nil || *input.PolicyDocument == "" || input.PolicyName == nil || *input.PolicyName == "" { + return nil, errors.New("CreatePolicyInput.PolicyDocument or CreatePolicyInput.PolicyName is nil or an empty string") + } - resp := iam.CreatePolicyOutput{} - return &resp, nil + resp := iam.CreatePolicyOutput{} + return &resp, nil } func TestCreatePolicy(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - mockSvc := &mockIAMClient{} + mockSvc := &mockIAMClient{} - policyName := "test-policy" + policyName := "test-policy" - err := MakePolicy(mockSvc, &policyName) - if err != nil { - t.Fatal(err) - } + err := MakePolicy(mockSvc, &policyName) + if err != nil { + t.Fatal(err) + } - t.Log("Created policy " + policyName) + t.Log("Created policy " + policyName) } diff --git a/go/iam/CreateUser/CreateUser_test.go b/go/iam/CreateUser/CreateUser_test.go index 25a7bd2b31d..2b903986071 100644 --- a/go/iam/CreateUser/CreateUser_test.go +++ b/go/iam/CreateUser/CreateUser_test.go @@ -1,46 +1,47 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/iam/iamiface" ) // Define a mock struct to use in unit tests type mockIAMClient struct { - iamiface.IAMAPI + iamiface.IAMAPI } // Then for every *real* call you make in the example: func (m *mockIAMClient) CreateUser(input *iam.CreateUserInput) (*iam.CreateUserOutput, error) { - // Check that required inputs exist - if input.UserName == nil || *input.UserName == "" { - return nil, errors.New("The CreateUserInput.UserName was nil or an empty string") - } + // Check that required inputs exist + if input.UserName == nil || *input.UserName == "" { + return nil, errors.New("The CreateUserInput.UserName was nil or an empty string") + } - resp := iam.CreateUserOutput{} - return &resp, nil + resp := iam.CreateUserOutput{} + return &resp, nil } func TestCreateUser(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - userName := "test-user" + // mock resource + userName := "test-user" - mockSvc := &mockIAMClient{} + mockSvc := &mockIAMClient{} - err := MakeUser(mockSvc, &userName) - if err != nil { - t.Fatal(err) - } + err := MakeUser(mockSvc, &userName) + if err != nil { + t.Fatal(err) + } - t.Log("Created user " + userName) + t.Log("Created user " + userName) } diff --git a/go/iam/DeleteAccessKey/DeleteAccessKey_test.go b/go/iam/DeleteAccessKey/DeleteAccessKey_test.go index 002bce26629..cbd072c8a1e 100644 --- a/go/iam/DeleteAccessKey/DeleteAccessKey_test.go +++ b/go/iam/DeleteAccessKey/DeleteAccessKey_test.go @@ -1,46 +1,47 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/iam/iamiface" ) // Define a mock struct to use in unit tests type mockIAMClient struct { - iamiface.IAMAPI + iamiface.IAMAPI } func (m *mockIAMClient) DeleteAccessKey(input *iam.DeleteAccessKeyInput) (*iam.DeleteAccessKeyOutput, error) { - // Check that required inputs exist - if input.AccessKeyId == nil || *input.AccessKeyId == "" || input.UserName == nil || *input.UserName == "" { - return nil, errors.New("DeleteAccessKeyInput.AccessKeyId or DeleteAccessKeyInput.UserName is nil or an empty string") - } + // Check that required inputs exist + if input.AccessKeyId == nil || *input.AccessKeyId == "" || input.UserName == nil || *input.UserName == "" { + return nil, errors.New("DeleteAccessKeyInput.AccessKeyId or DeleteAccessKeyInput.UserName is nil or an empty string") + } - resp := iam.DeleteAccessKeyOutput{} - return &resp, nil + resp := iam.DeleteAccessKeyOutput{} + return &resp, nil } func TestDeleteAccessKey(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resources - keyID := "test-key" - userName := "test-user" + // mock resources + keyID := "test-key" + userName := "test-user" - mockSvc := &mockIAMClient{} + mockSvc := &mockIAMClient{} - err := RemoveAccessKey(mockSvc, &keyID, &userName) - if err != nil { - t.Fatal(err) - } + err := RemoveAccessKey(mockSvc, &keyID, &userName) + if err != nil { + t.Fatal(err) + } - t.Log("Deleted key with ID " + keyID + " from user " + userName) + t.Log("Deleted key with ID " + keyID + " from user " + userName) } diff --git a/go/iam/DeleteAccountAlias/DeleteAccountAlias_test.go b/go/iam/DeleteAccountAlias/DeleteAccountAlias_test.go index 62986d9e6a7..2915b75033a 100644 --- a/go/iam/DeleteAccountAlias/DeleteAccountAlias_test.go +++ b/go/iam/DeleteAccountAlias/DeleteAccountAlias_test.go @@ -1,45 +1,46 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/iam/iamiface" ) // Define a mock struct to use in unit tests type mockIAMClient struct { - iamiface.IAMAPI + iamiface.IAMAPI } func (m *mockIAMClient) DeleteAccountAlias(input *iam.DeleteAccountAliasInput) (*iam.DeleteAccountAliasOutput, error) { - // Check that required inputs exist - if input.AccountAlias == nil || *input.AccountAlias == "" { - return nil, errors.New("DeleteAccountAliasInput.AccountAlias cannot be nil or an empty string") - } + // Check that required inputs exist + if input.AccountAlias == nil || *input.AccountAlias == "" { + return nil, errors.New("DeleteAccountAliasInput.AccountAlias cannot be nil or an empty string") + } - resp := iam.DeleteAccountAliasOutput{} - return &resp, nil + resp := iam.DeleteAccountAliasOutput{} + return &resp, nil } func TestDeleteAccountAlias(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - alias := "test-alias" + // mock resource + alias := "test-alias" - mockSvc := &mockIAMClient{} + mockSvc := &mockIAMClient{} - err := RemoveAccountAlias(mockSvc, &alias) - if err != nil { - t.Fatal(err) - } + err := RemoveAccountAlias(mockSvc, &alias) + if err != nil { + t.Fatal(err) + } - t.Log("Deleted account alias " + alias) + t.Log("Deleted account alias " + alias) } diff --git a/go/iam/DeleteServerCert/DeleteServerCert_test.go b/go/iam/DeleteServerCert/DeleteServerCert_test.go index 54f4f372928..e568f187c78 100644 --- a/go/iam/DeleteServerCert/DeleteServerCert_test.go +++ b/go/iam/DeleteServerCert/DeleteServerCert_test.go @@ -1,46 +1,47 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/iam/iamiface" ) // Define a mock struct to use in unit tests type mockIAMClient struct { - iamiface.IAMAPI + iamiface.IAMAPI } func (m *mockIAMClient) DeleteServerCertificate(input *iam.DeleteServerCertificateInput) (*iam.DeleteServerCertificateOutput, error) { - // Check that required inputs exist - if input.ServerCertificateName == nil || *input.ServerCertificateName == "" { - return nil, errors.New("UpdateServerCertificateInput.ServerCertificateName is nil or an empty string") - } + // Check that required inputs exist + if input.ServerCertificateName == nil || *input.ServerCertificateName == "" { + return nil, errors.New("UpdateServerCertificateInput.ServerCertificateName is nil or an empty string") + } - resp := iam.DeleteServerCertificateOutput{} + resp := iam.DeleteServerCertificateOutput{} - return &resp, nil + return &resp, nil } func TestGetServerCert(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - certName := "test-cert" + // mock resource + certName := "test-cert" - mockSvc := &mockIAMClient{} + mockSvc := &mockIAMClient{} - err := DeleteServerCert(mockSvc, &certName) - if err != nil { - t.Fatal(err) - } + err := DeleteServerCert(mockSvc, &certName) + if err != nil { + t.Fatal(err) + } - t.Log("Deleted server certificate: " + certName) + t.Log("Deleted server certificate: " + certName) } diff --git a/go/iam/DeleteUser/DeleteUser_test.go b/go/iam/DeleteUser/DeleteUser_test.go index a615794b2e3..eebd2dc4a64 100644 --- a/go/iam/DeleteUser/DeleteUser_test.go +++ b/go/iam/DeleteUser/DeleteUser_test.go @@ -1,45 +1,46 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/iam/iamiface" ) // Define a mock struct to use in unit tests type mockIAMClient struct { - iamiface.IAMAPI + iamiface.IAMAPI } func (m *mockIAMClient) DeleteUser(input *iam.DeleteUserInput) (*iam.DeleteUserOutput, error) { - // Check that required inputs exist - if input.UserName == nil || *input.UserName == "" { - return nil, errors.New("The DeleteUserInput.UserName was nil or an empty string") - } + // Check that required inputs exist + if input.UserName == nil || *input.UserName == "" { + return nil, errors.New("The DeleteUserInput.UserName was nil or an empty string") + } - resp := iam.DeleteUserOutput{} - return &resp, nil + resp := iam.DeleteUserOutput{} + return &resp, nil } func TestCreateUser(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - userName := "test-user" + // mock resource + userName := "test-user" - mockSvc := &mockIAMClient{} + mockSvc := &mockIAMClient{} - err := RemoveUser(mockSvc, &userName) - if err != nil { - t.Fatal(err) - } + err := RemoveUser(mockSvc, &userName) + if err != nil { + t.Fatal(err) + } - t.Log("Deleted user " + userName) + t.Log("Deleted user " + userName) } diff --git a/go/iam/DetachUserPolicy/DetachUserPolicy_test.go b/go/iam/DetachUserPolicy/DetachUserPolicy_test.go index 0d4766e492e..6e6acd0eeb7 100644 --- a/go/iam/DetachUserPolicy/DetachUserPolicy_test.go +++ b/go/iam/DetachUserPolicy/DetachUserPolicy_test.go @@ -1,45 +1,46 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/iam/iamiface" ) // Define a mock struct to use in unit tests type mockIAMClient struct { - iamiface.IAMAPI + iamiface.IAMAPI } func (m *mockIAMClient) DetachRolePolicy(input *iam.DetachRolePolicyInput) (*iam.DetachRolePolicyOutput, error) { - // Check that required inputs exist - if input.PolicyArn == nil || *input.PolicyArn == "" || input.RoleName == nil || *input.RoleName == "" { - return nil, errors.New("DetacheRolePolicyInput.PolicyArn or DetachRolePolicyInput.RoleName is nil or an empty string") - } + // Check that required inputs exist + if input.PolicyArn == nil || *input.PolicyArn == "" || input.RoleName == nil || *input.RoleName == "" { + return nil, errors.New("DetacheRolePolicyInput.PolicyArn or DetachRolePolicyInput.RoleName is nil or an empty string") + } - resp := iam.DetachRolePolicyOutput{} - return &resp, nil + resp := iam.DetachRolePolicyOutput{} + return &resp, nil } func TestDetachRolePolicy(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - roleName := "test-role" + // mock resource + roleName := "test-role" - mockSvc := &mockIAMClient{} + mockSvc := &mockIAMClient{} - err := DetachDynamoFullPolicy(mockSvc, &roleName) - if err != nil { - t.Fatal(err) - } + err := DetachDynamoFullPolicy(mockSvc, &roleName) + if err != nil { + t.Fatal(err) + } - t.Log("Detached DynamoDB full-access policy to role " + roleName) + t.Log("Detached DynamoDB full-access policy to role " + roleName) } diff --git a/go/iam/GetPolicy/GetPolicy_test.go b/go/iam/GetPolicy/GetPolicy_test.go index 34747d945fa..a4bedd36e8c 100644 --- a/go/iam/GetPolicy/GetPolicy_test.go +++ b/go/iam/GetPolicy/GetPolicy_test.go @@ -1,61 +1,62 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/iam/iamiface" ) // Define a mock struct to use in unit tests type mockIAMClient struct { - iamiface.IAMAPI + iamiface.IAMAPI } var expectedDescription = "Provides Put, Get access to Amazon S3 and full access to Amazon CloudWatch Logs." // Then for every *real* call you make in the example: func (m *mockIAMClient) GetPolicy(input *iam.GetPolicyInput) (*iam.GetPolicyOutput, error) { - // Check that required inputs exist - if input.PolicyArn == nil || *input.PolicyArn == "" { - return nil, errors.New("GetPolicyInput.PolicyArn is nil or an empty string") - } - - resp := iam.GetPolicyOutput{ - Policy: &iam.Policy{ - Description: &expectedDescription, - }, - } - return &resp, nil + // Check that required inputs exist + if input.PolicyArn == nil || *input.PolicyArn == "" { + return nil, errors.New("GetPolicyInput.PolicyArn is nil or an empty string") + } + + resp := iam.GetPolicyOutput{ + Policy: &iam.Policy{ + Description: &expectedDescription, + }, + } + return &resp, nil } func TestGetPolicy(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - policyArn := "arn:aws:iam::aws:policy/AWSLambdaExecute" + policyArn := "arn:aws:iam::aws:policy/AWSLambdaExecute" - t.Log("Getting policy with ARN: " + policyArn) + t.Log("Getting policy with ARN: " + policyArn) - mockSvc := &mockIAMClient{} + mockSvc := &mockIAMClient{} - description, err := GetPolicyDescription(mockSvc, &policyArn) - if err != nil { - t.Fatal(err) - } + description, err := GetPolicyDescription(mockSvc, &policyArn) + if err != nil { + t.Fatal(err) + } - if description != expectedDescription { - t.Log("Description:") - t.Log(description) - t.Log("Does not match expected description:") - t.Fatal(expectedDescription) - } + if description != expectedDescription { + t.Log("Description:") + t.Log(description) + t.Log("Does not match expected description:") + t.Fatal(expectedDescription) + } - t.Log("Description") - t.Log(description) + t.Log("Description") + t.Log(description) } diff --git a/go/iam/GetPublicKeys/GetPublicKeys_test.go b/go/iam/GetPublicKeys/GetPublicKeys_test.go index d760ea0d2ca..75c40a791ff 100644 --- a/go/iam/GetPublicKeys/GetPublicKeys_test.go +++ b/go/iam/GetPublicKeys/GetPublicKeys_test.go @@ -1,45 +1,46 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/iam/iamiface" ) // Define a mock struct to use in unit tests type mockIAMClient struct { - iamiface.IAMAPI + iamiface.IAMAPI } func (m *mockIAMClient) ListSSHPublicKeys(input *iam.ListSSHPublicKeysInput) (*iam.ListSSHPublicKeysOutput, error) { - // Check that required inputs exist - if input.UserName == nil || *input.UserName == "" { - return nil, errors.New("ListSSHPublicKeysInput.UserName is nil or an empty string") - } + // Check that required inputs exist + if input.UserName == nil || *input.UserName == "" { + return nil, errors.New("ListSSHPublicKeysInput.UserName is nil or an empty string") + } - resp := iam.ListSSHPublicKeysOutput{} - return &resp, nil + resp := iam.ListSSHPublicKeysOutput{} + return &resp, nil } func TestGetPublicKeys(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - userName := "test-user" + // mock resource + userName := "test-user" - mockSvc := &mockIAMClient{} + mockSvc := &mockIAMClient{} - _, err := GetPublicKeyBodies(mockSvc, &userName) - if err != nil { - t.Fatal(err) - } + _, err := GetPublicKeyBodies(mockSvc, &userName) + if err != nil { + t.Fatal(err) + } - t.Log("Got SSH keys for user " + userName) + t.Log("Got SSH keys for user " + userName) } diff --git a/go/iam/GetServerCert/GetServerCert_test.go b/go/iam/GetServerCert/GetServerCert_test.go index 909003a471c..2bed0f50e30 100644 --- a/go/iam/GetServerCert/GetServerCert_test.go +++ b/go/iam/GetServerCert/GetServerCert_test.go @@ -1,66 +1,67 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/iam/iamiface" ) // Define a mock struct to use in unit tests type mockIAMClient struct { - iamiface.IAMAPI + iamiface.IAMAPI } func (m *mockIAMClient) GetServerCertificate(input *iam.GetServerCertificateInput) (*iam.GetServerCertificateOutput, error) { - // Check that required inputs exist - if input.ServerCertificateName == nil || *input.ServerCertificateName == "" { - return nil, errors.New("GetServerCertificateInput.ServerCertificateName is nil or an empty string") - } + // Check that required inputs exist + if input.ServerCertificateName == nil || *input.ServerCertificateName == "" { + return nil, errors.New("GetServerCertificateInput.ServerCertificateName is nil or an empty string") + } - resp := iam.GetServerCertificateOutput{ - ServerCertificate: &iam.ServerCertificate{ - ServerCertificateMetadata: &iam.ServerCertificateMetadata{ - Arn: aws.String("test-cert.ARN"), - Expiration: aws.Time(time.Now()), - Path: aws.String("a/b/c"), - ServerCertificateId: aws.String("test-cert-ID"), - ServerCertificateName: aws.String("my-server-cert"), - UploadDate: aws.Time(time.Now()), - }, - }, - } + resp := iam.GetServerCertificateOutput{ + ServerCertificate: &iam.ServerCertificate{ + ServerCertificateMetadata: &iam.ServerCertificateMetadata{ + Arn: aws.String("test-cert.ARN"), + Expiration: aws.Time(time.Now()), + Path: aws.String("a/b/c"), + ServerCertificateId: aws.String("test-cert-ID"), + ServerCertificateName: aws.String("my-server-cert"), + UploadDate: aws.Time(time.Now()), + }, + }, + } - return &resp, nil + return &resp, nil } func TestGetServerCert(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - certName := "test-cert" + // mock resource + certName := "test-cert" - mockSvc := &mockIAMClient{} + mockSvc := &mockIAMClient{} - result, err := FindServerCert(mockSvc, &certName) - if err != nil { - t.Fatal(err) - } + result, err := FindServerCert(mockSvc, &certName) + if err != nil { + t.Fatal(err) + } - t.Log("Retrieved metadata for certificate: " + certName + ":") - metadata := result.ServerCertificate.ServerCertificateMetadata + t.Log("Retrieved metadata for certificate: " + certName + ":") + metadata := result.ServerCertificate.ServerCertificateMetadata - t.Log("ARN: " + *metadata.Arn) - t.Log("Expiration: " + (*metadata.Expiration).Format("2006-01-02 15:04:05 Monday")) - t.Log("Path: " + *metadata.Path) - t.Log("ServerCertificateId " + *metadata.ServerCertificateId) - t.Log("ServerCertificateName " + *metadata.ServerCertificateName) - t.Log("UploadDate: " + (*metadata.UploadDate).Format("2006-01-02 15:04:05 Monday")) + t.Log("ARN: " + *metadata.Arn) + t.Log("Expiration: " + (*metadata.Expiration).Format("2006-01-02 15:04:05 Monday")) + t.Log("Path: " + *metadata.Path) + t.Log("ServerCertificateId " + *metadata.ServerCertificateId) + t.Log("ServerCertificateName " + *metadata.ServerCertificateName) + t.Log("UploadDate: " + (*metadata.UploadDate).Format("2006-01-02 15:04:05 Monday")) } diff --git a/go/iam/ListAccessKeys/ListAccessKeys_test.go b/go/iam/ListAccessKeys/ListAccessKeys_test.go index ccc8c602dbd..2849e80d6f3 100644 --- a/go/iam/ListAccessKeys/ListAccessKeys_test.go +++ b/go/iam/ListAccessKeys/ListAccessKeys_test.go @@ -1,56 +1,57 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/iam/iamiface" ) // Define a mock struct to use in unit tests type mockIAMClient struct { - iamiface.IAMAPI + iamiface.IAMAPI } func (m *mockIAMClient) ListAccessKeys(input *iam.ListAccessKeysInput) (*iam.ListAccessKeysOutput, error) { - // Check that required inputs exist - if input.UserName == nil || *input.UserName == "" { - return nil, errors.New("The ListAccessKeysInput.UserName was nil or an empty string") - } - - resp := iam.ListAccessKeysOutput{ - AccessKeyMetadata: []*iam.AccessKeyMetadata{ - &iam.AccessKeyMetadata{ - AccessKeyId: aws.String("abc123xyx"), - Status: aws.String("Active"), - }, - }, - } - - return &resp, nil + // Check that required inputs exist + if input.UserName == nil || *input.UserName == "" { + return nil, errors.New("The ListAccessKeysInput.UserName was nil or an empty string") + } + + resp := iam.ListAccessKeysOutput{ + AccessKeyMetadata: []*iam.AccessKeyMetadata{ + &iam.AccessKeyMetadata{ + AccessKeyId: aws.String("abc123xyx"), + Status: aws.String("Active"), + }, + }, + } + + return &resp, nil } func TestListAccessKeys(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resources - maxItems := int64(10) - userName := "test-user" + // mock resources + maxItems := int64(10) + userName := "test-user" - mockSvc := &mockIAMClient{} + mockSvc := &mockIAMClient{} - _, err := GetAccessKeys(mockSvc, &maxItems, &userName) - if err != nil { - t.Fatal(err) - } + _, err := GetAccessKeys(mockSvc, &maxItems, &userName) + if err != nil { + t.Fatal(err) + } - t.Log("Got access keys for " + userName) + t.Log("Got access keys for " + userName) } diff --git a/go/iam/ListAccountAliases/ListAccountAliases_test.go b/go/iam/ListAccountAliases/ListAccountAliases_test.go index 1086bba9240..74c67f627d3 100644 --- a/go/iam/ListAccountAliases/ListAccountAliases_test.go +++ b/go/iam/ListAccountAliases/ListAccountAliases_test.go @@ -1,40 +1,41 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "testing" - "time" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/iam/iamiface" ) // Define a mock struct to use in unit tests type mockIAMClient struct { - iamiface.IAMAPI + iamiface.IAMAPI } // Then for every *real* call you make in the example: func (m *mockIAMClient) ListAccountAliases(input *iam.ListAccountAliasesInput) (*iam.ListAccountAliasesOutput, error) { - // No required inputs - resp := iam.ListAccountAliasesOutput{} - return &resp, nil + // No required inputs + resp := iam.ListAccountAliasesOutput{} + return &resp, nil } func TestListAccountAliases(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - maxItems := int64(10) + maxItems := int64(10) - mockSvc := &mockIAMClient{} + mockSvc := &mockIAMClient{} - _, err := GetAccountAliases(mockSvc, &maxItems) - if err != nil { - t.Fatal(err) - } + _, err := GetAccountAliases(mockSvc, &maxItems) + if err != nil { + t.Fatal(err) + } - t.Log("Retrieved the account aliases") + t.Log("Retrieved the account aliases") } diff --git a/go/iam/ListAdmins/ListAdmins_test.go b/go/iam/ListAdmins/ListAdmins_test.go index bd36b23e3a5..2c26c3a422c 100644 --- a/go/iam/ListAdmins/ListAdmins_test.go +++ b/go/iam/ListAdmins/ListAdmins_test.go @@ -1,28 +1,29 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "strconv" - "testing" - "time" + "strconv" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/aws/session" ) func TestListUsers(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - users, admins, err := GetNumUsersAndAdmins(sess) - if err != nil { - t.Fatal(err) - } + users, admins, err := GetNumUsersAndAdmins(sess) + if err != nil { + t.Fatal(err) + } - t.Log("Got " + strconv.Itoa(admins) + " admin(s) out of " + strconv.Itoa(users) + " user(s)") + t.Log("Got " + strconv.Itoa(admins) + " admin(s) out of " + strconv.Itoa(users) + " user(s)") } diff --git a/go/iam/ListServerCerts/ListServerCerts_test.go b/go/iam/ListServerCerts/ListServerCerts_test.go index 03059eb6e64..f59cdf899a5 100644 --- a/go/iam/ListServerCerts/ListServerCerts_test.go +++ b/go/iam/ListServerCerts/ListServerCerts_test.go @@ -1,38 +1,39 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "testing" - "time" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/iam/iamiface" ) // Define a mock struct to use in unit tests type mockIAMClient struct { - iamiface.IAMAPI + iamiface.IAMAPI } func (m *mockIAMClient) ListServerCertificates(input *iam.ListServerCertificatesInput) (*iam.ListServerCertificatesOutput, error) { - // Check that required inputs exist + // Check that required inputs exist - resp := iam.ListServerCertificatesOutput{} - return &resp, nil + resp := iam.ListServerCertificatesOutput{} + return &resp, nil } func TestListServerCerts(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - mockSvc := &mockIAMClient{} + mockSvc := &mockIAMClient{} - _, err := GetServerCerts(mockSvc) - if err != nil { - t.Fatal(err) - } + _, err := GetServerCerts(mockSvc) + if err != nil { + t.Fatal(err) + } - t.Log("Retrieved the server certificates") + t.Log("Retrieved the server certificates") } diff --git a/go/iam/ListUsers/ListUsers_test.go b/go/iam/ListUsers/ListUsers_test.go index c8b0981035e..f58cbc79d93 100644 --- a/go/iam/ListUsers/ListUsers_test.go +++ b/go/iam/ListUsers/ListUsers_test.go @@ -1,29 +1,30 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "testing" - "time" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/aws/session" ) func TestListUsers(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - maxUsers := int64(10) + maxUsers := int64(10) - _, err := GetUsers(sess, &maxUsers) - if err != nil { - t.Fatal(err) - } + _, err := GetUsers(sess, &maxUsers) + if err != nil { + t.Fatal(err) + } - t.Log("Retrieved list of users") + t.Log("Retrieved list of users") } diff --git a/go/iam/UpdateAccessKey/UpdateAccessKey_test.go b/go/iam/UpdateAccessKey/UpdateAccessKey_test.go index 184e57ca4ba..1c9f83f1896 100644 --- a/go/iam/UpdateAccessKey/UpdateAccessKey_test.go +++ b/go/iam/UpdateAccessKey/UpdateAccessKey_test.go @@ -1,47 +1,48 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/iam/iamiface" ) // Define a mock struct to use in unit tests type mockIAMClient struct { - iamiface.IAMAPI + iamiface.IAMAPI } func (m *mockIAMClient) UpdateAccessKey(input *iam.UpdateAccessKeyInput) (*iam.UpdateAccessKeyOutput, error) { - // Check that required inputs exist - if input.AccessKeyId == nil || *input.AccessKeyId == "" || input.UserName == nil || *input.UserName == "" { - return nil, errors.New("UpdateAccessKeyInput.AccessKeyId or UpdateAccessKeyInput.Username is nil or an empty string") - } + // Check that required inputs exist + if input.AccessKeyId == nil || *input.AccessKeyId == "" || input.UserName == nil || *input.UserName == "" { + return nil, errors.New("UpdateAccessKeyInput.AccessKeyId or UpdateAccessKeyInput.Username is nil or an empty string") + } - resp := iam.UpdateAccessKeyOutput{} + resp := iam.UpdateAccessKeyOutput{} - return &resp, nil + return &resp, nil } func TestCreateAccessKey(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resources - keyID := "test-ID" - userName := "test-user" + // mock resources + keyID := "test-ID" + userName := "test-user" - mockSvc := &mockIAMClient{} + mockSvc := &mockIAMClient{} - err := ActivateAccessKey(mockSvc, &keyID, &userName) - if err != nil { - t.Fatal(err) - } + err := ActivateAccessKey(mockSvc, &keyID, &userName) + if err != nil { + t.Fatal(err) + } - t.Log("Activated key") + t.Log("Activated key") } diff --git a/go/iam/UpdateServerCert/UpdateServerCert_test.go b/go/iam/UpdateServerCert/UpdateServerCert_test.go index 18c910787b8..4b1324adbb3 100644 --- a/go/iam/UpdateServerCert/UpdateServerCert_test.go +++ b/go/iam/UpdateServerCert/UpdateServerCert_test.go @@ -1,47 +1,48 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/iam/iamiface" ) // Define a mock struct to use in unit tests type mockIAMClient struct { - iamiface.IAMAPI + iamiface.IAMAPI } func (m *mockIAMClient) UpdateServerCertificate(input *iam.UpdateServerCertificateInput) (*iam.UpdateServerCertificateOutput, error) { - // Check that required inputs exist - if input.ServerCertificateName == nil || *input.ServerCertificateName == "" || input.NewServerCertificateName == nil || *input.NewServerCertificateName == "" { - return nil, errors.New("UpdateServerCertificateInput.ServerCertificateName or UpdateServerCertificateInput.NewServerCertificateName is nil or an empty string") - } + // Check that required inputs exist + if input.ServerCertificateName == nil || *input.ServerCertificateName == "" || input.NewServerCertificateName == nil || *input.NewServerCertificateName == "" { + return nil, errors.New("UpdateServerCertificateInput.ServerCertificateName or UpdateServerCertificateInput.NewServerCertificateName is nil or an empty string") + } - resp := iam.UpdateServerCertificateOutput{} + resp := iam.UpdateServerCertificateOutput{} - return &resp, nil + return &resp, nil } func TestGetServerCert(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resources - certName := "test-cert" - newName := "new-test-cert" + // mock resources + certName := "test-cert" + newName := "new-test-cert" - mockSvc := &mockIAMClient{} + mockSvc := &mockIAMClient{} - err := RenameServerCert(mockSvc, &certName, &newName) - if err != nil { - t.Fatal(err) - } + err := RenameServerCert(mockSvc, &certName, &newName) + if err != nil { + t.Fatal(err) + } - t.Log("Renamed server certificate from: " + certName + " to: " + newName) + t.Log("Renamed server certificate from: " + certName + " to: " + newName) } diff --git a/go/iam/UpdateUser/UpdateUser_test.go b/go/iam/UpdateUser/UpdateUser_test.go index d8e3199e5d2..3f28fd79e3e 100644 --- a/go/iam/UpdateUser/UpdateUser_test.go +++ b/go/iam/UpdateUser/UpdateUser_test.go @@ -1,46 +1,47 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/iam/iamiface" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/iam/iamiface" ) // Define a mock struct to use in unit tests type mockIAMClient struct { - iamiface.IAMAPI + iamiface.IAMAPI } func (m *mockIAMClient) UpdateUser(input *iam.UpdateUserInput) (*iam.UpdateUserOutput, error) { - // Check that required inputs exist - if input.UserName == nil || *input.UserName == "" || input.NewUserName == nil || *input.NewUserName == "" { - return nil, errors.New("The UpdateUserInput.UserName or UpdateUserInput.NewUserName was nil or an empty string") - } + // Check that required inputs exist + if input.UserName == nil || *input.UserName == "" || input.NewUserName == nil || *input.NewUserName == "" { + return nil, errors.New("The UpdateUserInput.UserName or UpdateUserInput.NewUserName was nil or an empty string") + } - resp := iam.UpdateUserOutput{} - return &resp, nil + resp := iam.UpdateUserOutput{} + return &resp, nil } func TestCreateUser(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resources - userName := "test-user" - newName := "new-test-user" + // mock resources + userName := "test-user" + newName := "new-test-user" - mockSvc := &mockIAMClient{} + mockSvc := &mockIAMClient{} - err := RenameUser(mockSvc, &userName, &newName) - if err != nil { - t.Fatal(err) - } + err := RenameUser(mockSvc, &userName, &newName) + if err != nil { + t.Fatal(err) + } - t.Log("Renamed user " + userName + " to " + newName) + t.Log("Renamed user " + userName + " to " + newName) } diff --git a/go/lambda/UploadLambdaFunction/UploadLambdaFunction.go b/go/lambda/UploadLambdaFunction/UploadLambdaFunction.go index 913b2c93ad3..202ff0e8789 100644 --- a/go/lambda/UploadLambdaFunction/UploadLambdaFunction.go +++ b/go/lambda/UploadLambdaFunction/UploadLambdaFunction.go @@ -1,116 +1,110 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lambda.go.create_function.complete] package main // snippet-start:[lambda.go.create_function.imports] import ( - "flag" - "fmt" - "io/ioutil" + "flag" + "fmt" + "io/ioutil" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/lambda" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/lambda" ) + // snippet-end:[lambda.go.create_function.imports] // UploadFunction uploads a Lambda function to a bucket. // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients. -// zipFile is the name of the ZIP file, without the .zip, to upload. -// bucket is the name of the Amazon S3 bucket. -// function is the name of the Lambda function. -// handler is the name of the method within the code that Lambda calls to execute the function. -// role is the ARN of the function's execution role. -// runtime is the name of the runtime for the function code. -// For a function written in Go, this is "go1.x". +// +// sess is the current session, which provides configuration for the SDK's service clients. +// zipFile is the name of the ZIP file, without the .zip, to upload. +// bucket is the name of the Amazon S3 bucket. +// function is the name of the Lambda function. +// handler is the name of the method within the code that Lambda calls to execute the function. +// role is the ARN of the function's execution role. +// runtime is the name of the runtime for the function code. +// For a function written in Go, this is "go1.x". +// // Output: -// If success, the SOMETHING of the RESOURCE and nil -// Otherwise, an empty string and an error from the call to FUNCTION +// +// If success, the SOMETHING of the RESOURCE and nil +// Otherwise, an empty string and an error from the call to FUNCTION func UploadFunction(sess *session.Session, zipFile *string, bucket *string, function *string, handler *string, role *string, runtime *string) (*lambda.FunctionConfiguration, error) { - // Create service client - // snippet-start:[lambda.go.create_function.client] - svc := lambda.New(sess) - // snippet-end:[lambda.go.create_function.client] - - // snippet-start:[lambda.go.create_function.read_zip] - contents, err := ioutil.ReadFile(*zipFile + ".zip") - // snippet-end:[lambda.go.create_function.read_zip] - if err != nil { - fmt.Println("Got error trying to read " + *zipFile + ".zip") - return nil, err - } - - // snippet-start:[lambda.go.create_function.structs] - createCode := &lambda.FunctionCode{ - // S3Bucket: bucket, - // S3Key: zipFile, - // S3ObjectVersion: aws.String("1"), - ZipFile: contents, - } - - createArgs := &lambda.CreateFunctionInput{ - Code: createCode, - FunctionName: function, - Handler: handler, - Role: role, - Runtime: runtime, - } - // snippet-end:[lambda.go.create_function.structs] - - // snippet-start:[lambda.go.create_function.create] - result, err := svc.CreateFunction(createArgs) - // snippet-end:[lambda.go.create_function.create] - if err != nil { - fmt.Println("Cannot create function") - return nil, err - } - - return result, nil + // Create service client + // snippet-start:[lambda.go.create_function.client] + svc := lambda.New(sess) + // snippet-end:[lambda.go.create_function.client] + + // snippet-start:[lambda.go.create_function.read_zip] + contents, err := ioutil.ReadFile(*zipFile + ".zip") + // snippet-end:[lambda.go.create_function.read_zip] + if err != nil { + fmt.Println("Got error trying to read " + *zipFile + ".zip") + return nil, err + } + + // snippet-start:[lambda.go.create_function.structs] + createCode := &lambda.FunctionCode{ + // S3Bucket: bucket, + // S3Key: zipFile, + // S3ObjectVersion: aws.String("1"), + ZipFile: contents, + } + + createArgs := &lambda.CreateFunctionInput{ + Code: createCode, + FunctionName: function, + Handler: handler, + Role: role, + Runtime: runtime, + } + // snippet-end:[lambda.go.create_function.structs] + + // snippet-start:[lambda.go.create_function.create] + result, err := svc.CreateFunction(createArgs) + // snippet-end:[lambda.go.create_function.create] + if err != nil { + fmt.Println("Cannot create function") + return nil, err + } + + return result, nil } func main() { - // snippet-start:[lambda.go.create_function.vars] - zipFile := flag.String("z", "", "The name of the ZIP file, without the .zip extension.") - bucket := flag.String("b", "", "the name of bucket to which the ZIP file is uploaded.") - function := flag.String("f", "", "The name of the Lambda function.") - handler := flag.String("h", "main", "The name of the package.class handling the call.") - roleARN := flag.String("a", "", "The ARN of the role that calls the function.") - runtime := flag.String("r", "go1.x", "The runtime for the function.") - - flag.Parse() - - if *zipFile == "" || *bucket == "" || *function == "" || *handler == "" || *roleARN == "" || *runtime == "" { - fmt.Println("You must supply a zip file name, bucket name, function name, handler (package) name, role ARN, and runtime value.") - return - } - // snippet-end:[lambda.go.create_function.vars] - - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - // snippet-start:[lambda.go.create_function.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[lambda.go.create_function.session] - - result, err := UploadFunction(sess, zipFile, bucket, function, handler, roleARN, runtime) - if err != nil { - fmt.Println(err) - return - } - - fmt.Println("Lambda function ARN: " + *result.FunctionArn) + // snippet-start:[lambda.go.create_function.vars] + zipFile := flag.String("z", "", "The name of the ZIP file, without the .zip extension.") + bucket := flag.String("b", "", "the name of bucket to which the ZIP file is uploaded.") + function := flag.String("f", "", "The name of the Lambda function.") + handler := flag.String("h", "main", "The name of the package.class handling the call.") + roleARN := flag.String("a", "", "The ARN of the role that calls the function.") + runtime := flag.String("r", "go1.x", "The runtime for the function.") + + flag.Parse() + + if *zipFile == "" || *bucket == "" || *function == "" || *handler == "" || *roleARN == "" || *runtime == "" { + fmt.Println("You must supply a zip file name, bucket name, function name, handler (package) name, role ARN, and runtime value.") + return + } + // snippet-end:[lambda.go.create_function.vars] + + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + // snippet-start:[lambda.go.create_function.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[lambda.go.create_function.session] + + result, err := UploadFunction(sess, zipFile, bucket, function, handler, roleARN, runtime) + if err != nil { + fmt.Println(err) + return + } + + fmt.Println("Lambda function ARN: " + *result.FunctionArn) } + // snippet-end:[lambda.go.create_function.complete] diff --git a/go/lambda/UploadLambdaFunction/UploadLambdaFunction_test.go b/go/lambda/UploadLambdaFunction/UploadLambdaFunction_test.go index 27de5cf69b1..0593d243a3d 100644 --- a/go/lambda/UploadLambdaFunction/UploadLambdaFunction_test.go +++ b/go/lambda/UploadLambdaFunction/UploadLambdaFunction_test.go @@ -1,43 +1,32 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "errors" - "io/ioutil" - "testing" - "time" - - "github.com/google/uuid" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/iam" - "github.com/aws/aws-sdk-go/service/lambda" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" + "encoding/json" + "errors" + "io/ioutil" + "testing" + "time" + + "github.com/google/uuid" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/lambda" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" ) type Config struct { - Bucket string `json:"Bucket"` - Function string `json:"Function"` - Handler string `json:"Handler"` - RoleARN string `json:"RoleARN"` - Runtime string `json:"Runtime"` - ZipFile string `json:"ZipFile"` - Cleanup bool `json:"Cleanup"` + Bucket string `json:"Bucket"` + Function string `json:"Function"` + Handler string `json:"Handler"` + RoleARN string `json:"RoleARN"` + Runtime string `json:"Runtime"` + ZipFile string `json:"ZipFile"` + Cleanup bool `json:"Cleanup"` } var configFileName = "config.json" @@ -45,33 +34,33 @@ var configFileName = "config.json" var globalConfig Config func PopulateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } - - text := string(content) - - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } - - t.Log("Default config.json values:") - t.Log("Bucket: " + globalConfig.Bucket) - t.Log("Function: " + globalConfig.Function) - t.Log("Handler: " + globalConfig.Handler) - t.Log("RoleARN: " + globalConfig.RoleARN) - t.Log("Runtime: " + globalConfig.Runtime) - t.Log("ZipFile: " + globalConfig.ZipFile) - - return nil + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } + + text := string(content) + + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } + + t.Log("Default config.json values:") + t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Function: " + globalConfig.Function) + t.Log("Handler: " + globalConfig.Handler) + t.Log("RoleARN: " + globalConfig.RoleARN) + t.Log("Runtime: " + globalConfig.Runtime) + t.Log("ZipFile: " + globalConfig.ZipFile) + + return nil } func createRole(sess *session.Session, roleName *string) (*iam.CreateRoleOutput, error) { - svc := iam.New(sess) + svc := iam.New(sess) - trustRelationship := []byte(`{ + trustRelationship := []byte(`{ "Version": "2012-10-17", "Statement": [ { @@ -84,229 +73,229 @@ func createRole(sess *session.Session, roleName *string) (*iam.CreateRoleOutput, ] }`) - trustPolicy := string(trustRelationship[:]) - - result, err := svc.CreateRole(&iam.CreateRoleInput{ - AssumeRolePolicyDocument: aws.String(trustPolicy), - RoleName: roleName, - }) - - if err != nil { - return nil, err - } - - _, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{ - PolicyArn: aws.String("arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"), - RoleName: roleName, - }) - if err != nil { - return nil, err - } - - _, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{ - PolicyArn: aws.String("arn:aws:iam::aws:policy/AWSXRayDaemonWriteAccess"), - RoleName: roleName, - }) - if err != nil { - return nil, err - } - - return result, nil + trustPolicy := string(trustRelationship[:]) + + result, err := svc.CreateRole(&iam.CreateRoleInput{ + AssumeRolePolicyDocument: aws.String(trustPolicy), + RoleName: roleName, + }) + + if err != nil { + return nil, err + } + + _, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{ + PolicyArn: aws.String("arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"), + RoleName: roleName, + }) + if err != nil { + return nil, err + } + + _, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{ + PolicyArn: aws.String("arn:aws:iam::aws:policy/AWSXRayDaemonWriteAccess"), + RoleName: roleName, + }) + if err != nil { + return nil, err + } + + return result, nil } func createBucket(sess *session.Session, bucket *string) error { - // Create S3 service client - svc := s3.New(sess) - - // Create the S3 Bucket - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - // Wait until bucket is created before finishing - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + // Create S3 service client + svc := s3.New(sess) + + // Create the S3 Bucket + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + // Wait until bucket is created before finishing + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func deleteFunction(sess *session.Session, function *string) error { - svc := lambda.New(sess) + svc := lambda.New(sess) - _, err := svc.DeleteFunction(&lambda.DeleteFunctionInput{ - FunctionName: function, - }) - if err != nil { - return err - } + _, err := svc.DeleteFunction(&lambda.DeleteFunctionInput{ + FunctionName: function, + }) + if err != nil { + return err + } - return nil + return nil } func deleteRole(sess *session.Session, role *string) error { - svc := iam.New(sess) + svc := iam.New(sess) - _, err := svc.DeleteRole(&iam.DeleteRoleInput{ - RoleName: role, - }) - if err != nil { - return err - } + _, err := svc.DeleteRole(&iam.DeleteRoleInput{ + RoleName: role, + }) + if err != nil { + return err + } - return nil + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - // Create S3 service client - svc := s3.New(sess) - - // Delete all objects in the bucket - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucket, - }) - - if err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter); err != nil { - return err - } - - // Delete the S3 Bucket - _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - // Wait until bucket is gone before finishing - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + // Create S3 service client + svc := s3.New(sess) + + // Delete all objects in the bucket + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucket, + }) + + if err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter); err != nil { + return err + } + + // Delete the S3 Bucket + _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + // Wait until bucket is gone before finishing + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestLambdaUpload(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := PopulateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - // Initialize a session that the SDK will use to load - // credentials from the shared credentials file ~/.aws/credentials. - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - id := uuid.New() - - if globalConfig.Runtime == "" { - globalConfig.Runtime = "go1.x" - } - - roleCreated := false - roleName := "" - - if globalConfig.RoleARN == "" { - roleName = "my-lambda-role-" + id.String() - result, err := createRole(sess, &roleName) - if err != nil { - t.Fatal(err) - } - - globalConfig.RoleARN = *result.Role.Arn - roleCreated = true - t.Log("Created role ") - } - - if globalConfig.Handler == "" { - globalConfig.Handler = "main" - } - - bucketCreated := false - - if globalConfig.Bucket == "" { - globalConfig.Bucket = "my-lambda-bucket-" + id.String() - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Created bucket " + globalConfig.Bucket) - bucketCreated = true - } - - functionCreated := false - - if globalConfig.Function == "" { - globalConfig.Function = "my-lambda-function-" + id.String() - functionCreated = true - } - - if globalConfig.ZipFile == "" { - globalConfig.ZipFile = "main" - } - - if globalConfig.Bucket == "" || globalConfig.Function == "" || globalConfig.Handler == "" || globalConfig.RoleARN == "" || globalConfig.Runtime == "" || globalConfig.ZipFile == "" { - t.Log("Bucket: " + globalConfig.Bucket) - t.Log("Function: " + globalConfig.Function) - t.Log("Handler: " + globalConfig.Handler) - t.Log("RoleARN: " + globalConfig.RoleARN) - t.Log("Runtime: " + globalConfig.Runtime) - t.Log("ZipFile: " + globalConfig.ZipFile) - - msg := "You must supply a zip file name, bucket name, function name, handler (package) name, role ARN, and runtime value." - t.Fatal(errors.New(msg)) - } - - result, err := UploadFunction(sess, &globalConfig.ZipFile, &globalConfig.Bucket, &globalConfig.Function, &globalConfig.Handler, &globalConfig.RoleARN, &globalConfig.Runtime) - if err != nil { - t.Fatal(err) - } - - t.Log("Lambda function ARN: " + *result.FunctionArn) - - if globalConfig.Cleanup { - if functionCreated { - err := deleteFunction(sess, &globalConfig.Function) - if err != nil { - t.Log("You'll have to delete function " + globalConfig.Function + " yourself") - t.Fatal(err) - } - - t.Log("Deleted function " + globalConfig.Function) - } - - if roleCreated { - err := deleteRole(sess, &roleName) - if err != nil { - t.Log("You'll have to delete role " + roleName + " yourself") - } - - t.Log("Deleted role " + roleName) - } - - if bucketCreated { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete the bucket " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted bucket " + globalConfig.Bucket) - } - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := PopulateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + // Initialize a session that the SDK will use to load + // credentials from the shared credentials file ~/.aws/credentials. + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + id := uuid.New() + + if globalConfig.Runtime == "" { + globalConfig.Runtime = "go1.x" + } + + roleCreated := false + roleName := "" + + if globalConfig.RoleARN == "" { + roleName = "my-lambda-role-" + id.String() + result, err := createRole(sess, &roleName) + if err != nil { + t.Fatal(err) + } + + globalConfig.RoleARN = *result.Role.Arn + roleCreated = true + t.Log("Created role ") + } + + if globalConfig.Handler == "" { + globalConfig.Handler = "main" + } + + bucketCreated := false + + if globalConfig.Bucket == "" { + globalConfig.Bucket = "my-lambda-bucket-" + id.String() + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Created bucket " + globalConfig.Bucket) + bucketCreated = true + } + + functionCreated := false + + if globalConfig.Function == "" { + globalConfig.Function = "my-lambda-function-" + id.String() + functionCreated = true + } + + if globalConfig.ZipFile == "" { + globalConfig.ZipFile = "main" + } + + if globalConfig.Bucket == "" || globalConfig.Function == "" || globalConfig.Handler == "" || globalConfig.RoleARN == "" || globalConfig.Runtime == "" || globalConfig.ZipFile == "" { + t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Function: " + globalConfig.Function) + t.Log("Handler: " + globalConfig.Handler) + t.Log("RoleARN: " + globalConfig.RoleARN) + t.Log("Runtime: " + globalConfig.Runtime) + t.Log("ZipFile: " + globalConfig.ZipFile) + + msg := "You must supply a zip file name, bucket name, function name, handler (package) name, role ARN, and runtime value." + t.Fatal(errors.New(msg)) + } + + result, err := UploadFunction(sess, &globalConfig.ZipFile, &globalConfig.Bucket, &globalConfig.Function, &globalConfig.Handler, &globalConfig.RoleARN, &globalConfig.Runtime) + if err != nil { + t.Fatal(err) + } + + t.Log("Lambda function ARN: " + *result.FunctionArn) + + if globalConfig.Cleanup { + if functionCreated { + err := deleteFunction(sess, &globalConfig.Function) + if err != nil { + t.Log("You'll have to delete function " + globalConfig.Function + " yourself") + t.Fatal(err) + } + + t.Log("Deleted function " + globalConfig.Function) + } + + if roleCreated { + err := deleteRole(sess, &roleName) + if err != nil { + t.Log("You'll have to delete role " + roleName + " yourself") + } + + t.Log("Deleted role " + roleName) + } + + if bucketCreated { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete the bucket " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted bucket " + globalConfig.Bucket) + } + } } diff --git a/go/rds/CopySnapshotToS3/CopySnapshotToS3_test.go b/go/rds/CopySnapshotToS3/CopySnapshotToS3_test.go index f6a8314f94c..98c860ea538 100644 --- a/go/rds/CopySnapshotToS3/CopySnapshotToS3_test.go +++ b/go/rds/CopySnapshotToS3/CopySnapshotToS3_test.go @@ -1,60 +1,61 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "testing" - "time" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/rds" - "github.com/aws/aws-sdk-go/service/rds/rdsiface" + "github.com/aws/aws-sdk-go/service/rds" + "github.com/aws/aws-sdk-go/service/rds/rdsiface" ) // Define a mock struct to use in unit tests type mockRDSClient struct { - rdsiface.RDSAPI + rdsiface.RDSAPI } var rdsSnapshot = "test-rds-snapshot" var dBSnapshotArn = rdsSnapshot + "-arn" func (m *mockRDSClient) DescribeDBSnapshots(input *rds.DescribeDBSnapshotsInput) (*rds.DescribeDBSnapshotsOutput, error) { - resp := rds.DescribeDBSnapshotsOutput{ - DBSnapshots: []*rds.DBSnapshot{ - &rds.DBSnapshot{ - DBSnapshotArn: &dBSnapshotArn, - }, - }, - } - - return &resp, nil + resp := rds.DescribeDBSnapshotsOutput{ + DBSnapshots: []*rds.DBSnapshot{ + &rds.DBSnapshot{ + DBSnapshotArn: &dBSnapshotArn, + }, + }, + } + + return &resp, nil } func (m *mockRDSClient) StartExportTask(input *rds.StartExportTaskInput) (*rds.StartExportTaskOutput, error) { - resp := rds.StartExportTaskOutput{} + resp := rds.StartExportTaskOutput{} - return &resp, nil + return &resp, nil } func TestCopySnapshot(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resources - roleArn := "test-role-arn" - kmsKey := "test-kms-key" - bucketName := "test-bucket" - rdsSnapshotName := "test-rds-snapshot" - exportRDSSnapshotName := "test-export-name" + // mock resources + roleArn := "test-role-arn" + kmsKey := "test-kms-key" + bucketName := "test-bucket" + rdsSnapshotName := "test-rds-snapshot" + exportRDSSnapshotName := "test-export-name" - mockSvc := &mockRDSClient{} + mockSvc := &mockRDSClient{} - _, err := StoreInstance(mockSvc, &rdsSnapshotName, &exportRDSSnapshotName, &roleArn, &kmsKey, &bucketName) - if err != nil { - t.Fatal(err) - } + _, err := StoreInstance(mockSvc, &rdsSnapshotName, &exportRDSSnapshotName, &roleArn, &kmsKey, &bucketName) + if err != nil { + t.Fatal(err) + } - t.Log("Stored instance snapshot " + rdsSnapshotName + " to bucket " + bucketName) + t.Log("Stored instance snapshot " + rdsSnapshotName + " to bucket " + bucketName) } diff --git a/go/rds/CreateClusterSnapshot/CreateClusterSnapshot_test.go b/go/rds/CreateClusterSnapshot/CreateClusterSnapshot_test.go index 1c566dcb2e5..39fd12b0347 100644 --- a/go/rds/CreateClusterSnapshot/CreateClusterSnapshot_test.go +++ b/go/rds/CreateClusterSnapshot/CreateClusterSnapshot_test.go @@ -1,46 +1,47 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/rds" - "github.com/aws/aws-sdk-go/service/rds/rdsiface" + "github.com/aws/aws-sdk-go/service/rds" + "github.com/aws/aws-sdk-go/service/rds/rdsiface" ) // Define a mock struct to use in unit tests type mockRDSClient struct { - rdsiface.RDSAPI + rdsiface.RDSAPI } func (m *mockRDSClient) CreateDBClusterSnapshot(input *rds.CreateDBClusterSnapshotInput) (*rds.CreateDBClusterSnapshotOutput, error) { - // Check that required inputs exist - if input.DBClusterIdentifier == nil || *input.DBClusterIdentifier == "" { - return nil, errors.New("The DBInstanceIdentifier argument is null or empty") - } + // Check that required inputs exist + if input.DBClusterIdentifier == nil || *input.DBClusterIdentifier == "" { + return nil, errors.New("The DBInstanceIdentifier argument is null or empty") + } - resp := rds.CreateDBClusterSnapshotOutput{} + resp := rds.CreateDBClusterSnapshotOutput{} - return &resp, nil + return &resp, nil } func TestCreateClusterSnapshot(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - clusterID := "test-cluster-1234" + // mock resource + clusterID := "test-cluster-1234" - mockSvc := &mockRDSClient{} + mockSvc := &mockRDSClient{} - err := MakeClusterSnapshot(mockSvc, &clusterID) - if err != nil { - t.Fatal(err) - } + err := MakeClusterSnapshot(mockSvc, &clusterID) + if err != nil { + t.Fatal(err) + } - t.Log("Created cluster snapshot") + t.Log("Created cluster snapshot") } diff --git a/go/rds/CreateInstanceSnapshot/CreateInstanceSnapshot_test.go b/go/rds/CreateInstanceSnapshot/CreateInstanceSnapshot_test.go index fa448719db3..c4bf09ef28d 100644 --- a/go/rds/CreateInstanceSnapshot/CreateInstanceSnapshot_test.go +++ b/go/rds/CreateInstanceSnapshot/CreateInstanceSnapshot_test.go @@ -1,50 +1,51 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "errors" - "testing" - "time" + "errors" + "testing" + "time" - "github.com/aws/aws-sdk-go/service/rds" - "github.com/aws/aws-sdk-go/service/rds/rdsiface" + "github.com/aws/aws-sdk-go/service/rds" + "github.com/aws/aws-sdk-go/service/rds/rdsiface" ) // Define a mock struct to use in unit tests type mockRDSClient struct { - rdsiface.RDSAPI + rdsiface.RDSAPI } func (m *mockRDSClient) CreateDBSnapshot(input *rds.CreateDBSnapshotInput) (*rds.CreateDBSnapshotOutput, error) { - // Check that required inputs exist - if input.DBInstanceIdentifier == nil || *input.DBInstanceIdentifier == "" { - return nil, errors.New("The DBInstanceIdentifier argument is null or empty") - } + // Check that required inputs exist + if input.DBInstanceIdentifier == nil || *input.DBInstanceIdentifier == "" { + return nil, errors.New("The DBInstanceIdentifier argument is null or empty") + } - if input.DBSnapshotIdentifier == nil || *input.DBSnapshotIdentifier == "" { - return nil, errors.New("The DBSnapshotIdentifier argument is null or empty") - } + if input.DBSnapshotIdentifier == nil || *input.DBSnapshotIdentifier == "" { + return nil, errors.New("The DBSnapshotIdentifier argument is null or empty") + } - resp := rds.CreateDBSnapshotOutput{} + resp := rds.CreateDBSnapshotOutput{} - return &resp, nil + return &resp, nil } func TestCreateInstanceSnapshot(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - // mock resource - instance := "test-instance" + // mock resource + instance := "test-instance" - mockSvc := &mockRDSClient{} + mockSvc := &mockRDSClient{} - err := MakeInstanceSnapshot(mockSvc, &instance) - if err != nil { - t.Fatal(err) - } + err := MakeInstanceSnapshot(mockSvc, &instance) + if err != nil { + t.Fatal(err) + } - t.Log("Created instance snapshot") + t.Log("Created instance snapshot") } diff --git a/go/rds/ListClusterSnapshots/ListClusterSnapshots_test.go b/go/rds/ListClusterSnapshots/ListClusterSnapshots_test.go index 28e6553ddb5..296515bfe8a 100644 --- a/go/rds/ListClusterSnapshots/ListClusterSnapshots_test.go +++ b/go/rds/ListClusterSnapshots/ListClusterSnapshots_test.go @@ -1,27 +1,28 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "testing" - "time" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/aws/session" ) func TestListClusterSnapshots(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - _, err := GetClusterSnapshots(sess) - if err != nil { - t.Fatal(err) - } + _, err := GetClusterSnapshots(sess) + if err != nil { + t.Fatal(err) + } - t.Log("Retrieved cluster snapshots") + t.Log("Retrieved cluster snapshots") } diff --git a/go/rds/ListInstanceSnapshots/ListInstanceSnapshots_test.go b/go/rds/ListInstanceSnapshots/ListInstanceSnapshots_test.go index a2a8f94eccd..0f14997d865 100644 --- a/go/rds/ListInstanceSnapshots/ListInstanceSnapshots_test.go +++ b/go/rds/ListInstanceSnapshots/ListInstanceSnapshots_test.go @@ -1,4 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main diff --git a/go/rds/ListInstances/ListInstances_test.go b/go/rds/ListInstances/ListInstances_test.go index af45e3dafa5..a654784b03b 100644 --- a/go/rds/ListInstances/ListInstances_test.go +++ b/go/rds/ListInstances/ListInstances_test.go @@ -1,4 +1,5 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main diff --git a/go/rds/ListParameterGroups/ListParameterGroups_test.go b/go/rds/ListParameterGroups/ListParameterGroups_test.go index a3216554fca..610bf75c36a 100644 --- a/go/rds/ListParameterGroups/ListParameterGroups_test.go +++ b/go/rds/ListParameterGroups/ListParameterGroups_test.go @@ -1,27 +1,28 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "testing" - "time" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/aws/session" ) func TestListParameterGroups(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - _, err := GetParameterGroups(sess) - if err != nil { - t.Fatal(err) - } + _, err := GetParameterGroups(sess) + if err != nil { + t.Fatal(err) + } - t.Log("Retrieved security groups") + t.Log("Retrieved security groups") } diff --git a/go/rds/ListSecurityGroups/ListSecurityGroups_test.go b/go/rds/ListSecurityGroups/ListSecurityGroups_test.go index 2b88e0e5c98..f27bcfa6462 100644 --- a/go/rds/ListSecurityGroups/ListSecurityGroups_test.go +++ b/go/rds/ListSecurityGroups/ListSecurityGroups_test.go @@ -1,27 +1,28 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "testing" - "time" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/aws/session" ) func TestListSecurityGroups(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - _, err := GetSecurityGroups(sess) - if err != nil { - t.Fatal(err) - } + _, err := GetSecurityGroups(sess) + if err != nil { + t.Fatal(err) + } - t.Log("Retrieved the security groups") + t.Log("Retrieved the security groups") } diff --git a/go/rds/ListSubnetGroups/ListSubnetGroups_test.go b/go/rds/ListSubnetGroups/ListSubnetGroups_test.go index c434c2f1ffd..1d4fdb2c81d 100644 --- a/go/rds/ListSubnetGroups/ListSubnetGroups_test.go +++ b/go/rds/ListSubnetGroups/ListSubnetGroups_test.go @@ -1,27 +1,28 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "testing" - "time" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/aws/session" ) func TestListSubnetGroups(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - _, err := GetSubnetGroups(sess) - if err != nil { - t.Fatal(err) - } + _, err := GetSubnetGroups(sess) + if err != nil { + t.Fatal(err) + } - t.Log("Retrieved the subnet groups") + t.Log("Retrieved the subnet groups") } diff --git a/go/s3/CRUD/S3CrudOps.go b/go/s3/CRUD/S3CrudOps.go index d21a5f1c6d0..f052a26474d 100644 --- a/go/s3/CRUD/S3CrudOps.go +++ b/go/s3/CRUD/S3CrudOps.go @@ -1,196 +1,199 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.crud_ops] package main // snippet-start:[s3.go.crud_ops.imports] import ( - "errors" - "flag" - "fmt" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3iface" + "errors" + "flag" + "fmt" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3iface" ) + // snippet-end:[s3.go.crud_ops.imports] // Functions to perform CRUD (create, read, update, delete) operations in Amazon S3 // MakeBucket creates an S3 bucket func MakeBucket(svc s3iface.S3API, bucket *string) error { - // snippet-start:[s3.go.crud_ops.call] - // Create the S3 bucket - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - // snippet-end:[s3.go.crud_ops.call] - if err != nil { - return err - } - - return nil + // snippet-start:[s3.go.crud_ops.call] + // Create the S3 bucket + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + // snippet-end:[s3.go.crud_ops.call] + if err != nil { + return err + } + + return nil } func waitForCreate(svc s3iface.S3API, bucket *string) error { - // snippet-start:[s3.go.crud_ops.wait_create] - err := svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - // snippet-end:[s3.go.crud_ops.wait_create] - if err != nil { - return err - } - - return nil + // snippet-start:[s3.go.crud_ops.wait_create] + err := svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + // snippet-end:[s3.go.crud_ops.wait_create] + if err != nil { + return err + } + + return nil } func GetBucket(svc s3iface.S3API, bucket *string) error { - // snippet-start:[s3.go.crud_ops.head_bucket] - _, err := svc.HeadBucket(&s3.HeadBucketInput{ - Bucket: bucket, - }) - // snippet-end:[s3.go.crud_ops.head_bucket] - if err != nil { - return err - } - - return nil + // snippet-start:[s3.go.crud_ops.head_bucket] + _, err := svc.HeadBucket(&s3.HeadBucketInput{ + Bucket: bucket, + }) + // snippet-end:[s3.go.crud_ops.head_bucket] + if err != nil { + return err + } + + return nil } // HasACL returns nil if the S3 bucket has a read-only ACL func HasACL(svc s3iface.S3API, bucket *string) error { - // snippet-start:[s3.go.crud_ops.get_acl] - acl, err := svc.GetBucketAcl(&s3.GetBucketAclInput{ - Bucket: bucket, - }) - // snippet-end:[s3.go.crud_ops.get_acl] - if err != nil { - return err - } - - // Determine whether the group AllUsers has read permission - // snippet-start:[s3.go.crud_ops.check_grants] - for _, g := range acl.Grants { - if *g.Grantee.Type == "Group" && *g.Grantee.URI == "http://acs.amazonaws.com/groups/global/AllUsers" && *g.Permission == "READ" { - // snippet-end:[s3.go.crud_ops.check_grants] - return nil - } - } - - return errors.New("All users do not have read access") + // snippet-start:[s3.go.crud_ops.get_acl] + acl, err := svc.GetBucketAcl(&s3.GetBucketAclInput{ + Bucket: bucket, + }) + // snippet-end:[s3.go.crud_ops.get_acl] + if err != nil { + return err + } + + // Determine whether the group AllUsers has read permission + // snippet-start:[s3.go.crud_ops.check_grants] + for _, g := range acl.Grants { + if *g.Grantee.Type == "Group" && *g.Grantee.URI == "http://acs.amazonaws.com/groups/global/AllUsers" && *g.Permission == "READ" { + // snippet-end:[s3.go.crud_ops.check_grants] + return nil + } + } + + return errors.New("All users do not have read access") } // UpdateBucket changes the S3 bucket to give all users read permission func UpdateBucket(svc s3iface.S3API, bucket *string) error { - // snippet-start:[s3.go.crud_ops.put_acl] - _, err := svc.PutBucketAcl(&s3.PutBucketAclInput{ - ACL: aws.String("public-read"), - Bucket: bucket, - }) - // snippet-end:[s3.go.crud_ops.put_acl] - if err != nil { - return err - } - - // Do all users have read permission? - err = HasACL(svc, bucket) - if err != nil { - return err - } - - return nil + // snippet-start:[s3.go.crud_ops.put_acl] + _, err := svc.PutBucketAcl(&s3.PutBucketAclInput{ + ACL: aws.String("public-read"), + Bucket: bucket, + }) + // snippet-end:[s3.go.crud_ops.put_acl] + if err != nil { + return err + } + + // Do all users have read permission? + err = HasACL(svc, bucket) + if err != nil { + return err + } + + return nil } // RemoveBucket deletes an S3 bucket func RemoveBucket(svc s3iface.S3API, bucket *string) error { - // snippet-start:[s3.go.crud_ops.delete_bucket] - _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - // snippet-end:[s3.go.crud_ops.delete_bucket] - if err != nil { - return err - } - - return nil + // snippet-start:[s3.go.crud_ops.delete_bucket] + _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + // snippet-end:[s3.go.crud_ops.delete_bucket] + if err != nil { + return err + } + + return nil } func waitForDelete(svc s3iface.S3API, bucket *string) error { - // snippet-start:[s3.go.crud_ops.wait_delete] - err := svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - // snippet-end:[s3.go.crud_ops.wait_delete] - if err != nil { - return err - } - - return nil + // snippet-start:[s3.go.crud_ops.wait_delete] + err := svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + // snippet-end:[s3.go.crud_ops.wait_delete] + if err != nil { + return err + } + + return nil } func main() { - // snippet-start:[s3.go.crud_ops.args] - bucket := flag.String("b", "", "The name of the S3 bucket") - flag.Parse() - - if *bucket == "" { - fmt.Println("You must supply an S3 bucket name (-b BUCKET)") - return - } - // snippet-end:[s3.go.crud_ops.args] - - // snippet-start:[s3.go.crud_ops.session_service] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := s3.New(sess) - // snippet-end:[s3.go.crud_ops.session_service] - - err := MakeBucket(svc, bucket) - if err != nil { - fmt.Println("Got error creating S3 bucket:") - fmt.Println(err) - return - } - - err = waitForCreate(svc, bucket) - if err != nil { - fmt.Println("Got error creating S3 bucket:") - fmt.Println(err) - return - } - - err = GetBucket(svc, bucket) - if err != nil { - fmt.Println("Got error reading S3 bucket:") - fmt.Println(err) - return - } - - err = UpdateBucket(svc, bucket) - if err != nil { - fmt.Println("Got error updating S3 bucket:") - fmt.Println(err) - return - } - - err = RemoveBucket(svc, bucket) - if err != nil { - fmt.Println("Got error deleting S3 bucket:") - fmt.Println(err) - return - } - - err = waitForDelete(svc, bucket) - if err != nil { - fmt.Println("Got error deleting S3 bucket:") - fmt.Println(err) - return - } - - fmt.Println("Successfully ran CRUD operations on S3 bucket " + *bucket) + // snippet-start:[s3.go.crud_ops.args] + bucket := flag.String("b", "", "The name of the S3 bucket") + flag.Parse() + + if *bucket == "" { + fmt.Println("You must supply an S3 bucket name (-b BUCKET)") + return + } + // snippet-end:[s3.go.crud_ops.args] + + // snippet-start:[s3.go.crud_ops.session_service] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := s3.New(sess) + // snippet-end:[s3.go.crud_ops.session_service] + + err := MakeBucket(svc, bucket) + if err != nil { + fmt.Println("Got error creating S3 bucket:") + fmt.Println(err) + return + } + + err = waitForCreate(svc, bucket) + if err != nil { + fmt.Println("Got error creating S3 bucket:") + fmt.Println(err) + return + } + + err = GetBucket(svc, bucket) + if err != nil { + fmt.Println("Got error reading S3 bucket:") + fmt.Println(err) + return + } + + err = UpdateBucket(svc, bucket) + if err != nil { + fmt.Println("Got error updating S3 bucket:") + fmt.Println(err) + return + } + + err = RemoveBucket(svc, bucket) + if err != nil { + fmt.Println("Got error deleting S3 bucket:") + fmt.Println(err) + return + } + + err = waitForDelete(svc, bucket) + if err != nil { + fmt.Println("Got error deleting S3 bucket:") + fmt.Println(err) + return + } + + fmt.Println("Successfully ran CRUD operations on S3 bucket " + *bucket) } + // snippet-end:[s3.go.crud_ops] diff --git a/go/s3/CRUD/S3CrudOps_test.go b/go/s3/CRUD/S3CrudOps_test.go index 2b02663f051..29b12e4ac70 100644 --- a/go/s3/CRUD/S3CrudOps_test.go +++ b/go/s3/CRUD/S3CrudOps_test.go @@ -1,114 +1,103 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "errors" - "io/ioutil" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3iface" - "github.com/google/uuid" + "encoding/json" + "errors" + "io/ioutil" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3iface" + "github.com/google/uuid" ) // Define a mock struct to use in unit tests type mockS3Client struct { - s3iface.S3API + s3iface.S3API } func (m *mockS3Client) CreateBucket(input *s3.CreateBucketInput) (*s3.CreateBucketOutput, error) { - if input.Bucket == nil || *input.Bucket == "" { - return nil, errors.New("The bucket name is nil or empty") - } + if input.Bucket == nil || *input.Bucket == "" { + return nil, errors.New("The bucket name is nil or empty") + } - resp := s3.CreateBucketOutput{} + resp := s3.CreateBucketOutput{} - return &resp, nil + return &resp, nil } func (m *mockS3Client) HeadBucket(input *s3.HeadBucketInput) (*s3.HeadBucketOutput, error) { - if input.Bucket == nil || *input.Bucket == "" { - return nil, errors.New("The bucket name is nil or empty") - } + if input.Bucket == nil || *input.Bucket == "" { + return nil, errors.New("The bucket name is nil or empty") + } - resp := s3.HeadBucketOutput{} + resp := s3.HeadBucketOutput{} - return &resp, nil + return &resp, nil } func (m *mockS3Client) GetBucketAcl(input *s3.GetBucketAclInput) (*s3.GetBucketAclOutput, error) { - if input.Bucket == nil || *input.Bucket == "" { - return nil, errors.New("The bucket name is nil or empty") - } - - g1 := &s3.Grant{ - Grantee: &s3.Grantee{ - DisplayName: aws.String("me"), - ID: aws.String("123456789"), - Type: aws.String("CanonicalUser"), - }, - Permission: aws.String("FULL_CONTROL"), - } - - g2 := &s3.Grant{ - Grantee: &s3.Grantee{ - Type: aws.String("Group"), - URI: aws.String("http://acs.amazonaws.com/groups/global/AllUsers"), - }, - Permission: aws.String("READ"), - } - - grants := []*s3.Grant{g1, g2} - - resp := s3.GetBucketAclOutput{ - Grants: grants, - Owner: &s3.Owner{ - DisplayName: aws.String("me"), - ID: aws.String("123456789"), - }, - } - - return &resp, nil + if input.Bucket == nil || *input.Bucket == "" { + return nil, errors.New("The bucket name is nil or empty") + } + + g1 := &s3.Grant{ + Grantee: &s3.Grantee{ + DisplayName: aws.String("me"), + ID: aws.String("123456789"), + Type: aws.String("CanonicalUser"), + }, + Permission: aws.String("FULL_CONTROL"), + } + + g2 := &s3.Grant{ + Grantee: &s3.Grantee{ + Type: aws.String("Group"), + URI: aws.String("http://acs.amazonaws.com/groups/global/AllUsers"), + }, + Permission: aws.String("READ"), + } + + grants := []*s3.Grant{g1, g2} + + resp := s3.GetBucketAclOutput{ + Grants: grants, + Owner: &s3.Owner{ + DisplayName: aws.String("me"), + ID: aws.String("123456789"), + }, + } + + return &resp, nil } func (m *mockS3Client) PutBucketAcl(input *s3.PutBucketAclInput) (*s3.PutBucketAclOutput, error) { - if input.Bucket == nil || *input.Bucket == "" { - return nil, errors.New("The bucket name is nil or empty") - } + if input.Bucket == nil || *input.Bucket == "" { + return nil, errors.New("The bucket name is nil or empty") + } - resp := s3.PutBucketAclOutput{} + resp := s3.PutBucketAclOutput{} - return &resp, nil + return &resp, nil } func (m *mockS3Client) DeleteBucket(input *s3.DeleteBucketInput) (*s3.DeleteBucketOutput, error) { - if input.Bucket == nil || *input.Bucket == "" { - return nil, errors.New("The bucket name is nil or empty") - } + if input.Bucket == nil || *input.Bucket == "" { + return nil, errors.New("The bucket name is nil or empty") + } - resp := s3.DeleteBucketOutput{} + resp := s3.DeleteBucketOutput{} - return &resp, nil + return &resp, nil } type Config struct { - Bucket string `json:"Bucket"` + Bucket string `json:"Bucket"` } var configFileName = "config.json" @@ -116,88 +105,88 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Bucket: " + globalConfig.Bucket) - return nil + return nil } func TestS3CrudOps(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - if globalConfig.Bucket == "" { - // mock resources - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - - mockSvc := &mockS3Client{} - - err = MakeBucket(mockSvc, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - err = GetBucket(mockSvc, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - err = UpdateBucket(mockSvc, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - err = RemoveBucket(mockSvc, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Successfully ran CRUD operations on bucket " + globalConfig.Bucket) - } else { - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - svc := s3.New(sess) - - err = MakeBucket(svc, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - err = GetBucket(svc, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - err = UpdateBucket(svc, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - err = RemoveBucket(svc, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Successfully ran CRUD operations on bucket " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + if globalConfig.Bucket == "" { + // mock resources + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + + mockSvc := &mockS3Client{} + + err = MakeBucket(mockSvc, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + err = GetBucket(mockSvc, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + err = UpdateBucket(mockSvc, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + err = RemoveBucket(mockSvc, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Successfully ran CRUD operations on bucket " + globalConfig.Bucket) + } else { + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + svc := s3.New(sess) + + err = MakeBucket(svc, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + err = GetBucket(svc, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + err = UpdateBucket(svc, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + err = RemoveBucket(svc, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Successfully ran CRUD operations on bucket " + globalConfig.Bucket) + } } diff --git a/go/s3/CopyObject/CopyObject.go b/go/s3/CopyObject/CopyObject.go index 0cdd0a6084c..69ab2d9a1fc 100644 --- a/go/s3/CopyObject/CopyObject.go +++ b/go/s3/CopyObject/CopyObject.go @@ -1,97 +1,91 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.copy_object] package main // snippet-start:[s3.go.copy_object.imports] import ( - "flag" - "fmt" - "net/url" + "flag" + "fmt" + "net/url" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.copy_object.imports] // CopyItem copies an item from one bucket to another // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// sourceBucket is the name of the source bucket -// otherBucket is the name of the bucket to which the item is copied -// item is the name of the bucket object to copy +// +// sess is the current session, which provides configuration for the SDK's service clients +// sourceBucket is the name of the source bucket +// otherBucket is the name of the bucket to which the item is copied +// item is the name of the bucket object to copy +// // Output: -// If success, nil -// Otherwise, an error from the call to CopyObject or WaitUntilObjectExists +// +// If success, nil +// Otherwise, an error from the call to CopyObject or WaitUntilObjectExists func CopyItem(sess *session.Session, sourceBucket *string, targetBucket *string, item *string) error { - // snippet-start:[s3.go.copy_object.call] - svc := s3.New(sess) - source := *sourceBucket + "/" + *item + // snippet-start:[s3.go.copy_object.call] + svc := s3.New(sess) + source := *sourceBucket + "/" + *item - // Copy the item - _, err := svc.CopyObject(&s3.CopyObjectInput{ - Bucket: targetBucket, - CopySource: aws.String(url.QueryEscape(source)), - Key: item, - }) - // snippet-end:[s3.go.copy_object.call] - if err != nil { - return err - } + // Copy the item + _, err := svc.CopyObject(&s3.CopyObjectInput{ + Bucket: targetBucket, + CopySource: aws.String(url.QueryEscape(source)), + Key: item, + }) + // snippet-end:[s3.go.copy_object.call] + if err != nil { + return err + } - // snippet-start:[s3.go.copy_object.wait] - err = svc.WaitUntilObjectExists(&s3.HeadObjectInput{ - Bucket: targetBucket, - Key: item, - }) - // snippet-end:[s3.go.copy_object.wait] - if err != nil { - return err - } + // snippet-start:[s3.go.copy_object.wait] + err = svc.WaitUntilObjectExists(&s3.HeadObjectInput{ + Bucket: targetBucket, + Key: item, + }) + // snippet-end:[s3.go.copy_object.wait] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[s3.go.copy_object.args] - sourceBucket := flag.String("f", "", "The bucket containing the object to copy") - targetBucket := flag.String("t", "", "The bucket to which the object is copied") - item := flag.String("i", "", "The object to copy") - flag.Parse() + // snippet-start:[s3.go.copy_object.args] + sourceBucket := flag.String("f", "", "The bucket containing the object to copy") + targetBucket := flag.String("t", "", "The bucket to which the object is copied") + item := flag.String("i", "", "The object to copy") + flag.Parse() - if *sourceBucket == "" || *targetBucket == "" || *item == "" { - fmt.Println("You must supply the bucket to copy from (-f BUCKET), to (-t BUCKET), and item to copy (-i ITEM") - return - } - // snippet-end:[s3.go.copy_object.args] + if *sourceBucket == "" || *targetBucket == "" || *item == "" { + fmt.Println("You must supply the bucket to copy from (-f BUCKET), to (-t BUCKET), and item to copy (-i ITEM") + return + } + // snippet-end:[s3.go.copy_object.args] - // snippet-start:[s3.go.copy_object.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.copy_object.session] + // snippet-start:[s3.go.copy_object.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.copy_object.session] - err := CopyItem(sess, sourceBucket, targetBucket, item) - if err != nil { - fmt.Println("Got an error copying item:") - fmt.Println(err) - return - } + err := CopyItem(sess, sourceBucket, targetBucket, item) + if err != nil { + fmt.Println("Got an error copying item:") + fmt.Println(err) + return + } - // snippet-start:[s3.go.copy_object.print] - fmt.Println("Copied " + *item + " from " + *sourceBucket + " to " + *targetBucket) - // snippet-end:[s3.go.copy_object.print] + // snippet-start:[s3.go.copy_object.print] + fmt.Println("Copied " + *item + " from " + *sourceBucket + " to " + *targetBucket) + // snippet-end:[s3.go.copy_object.print] } + // snippet-end:[s3.go.copy_object] diff --git a/go/s3/CopyObject/CopyObject_test.go b/go/s3/CopyObject/CopyObject_test.go index 2e80ffae636..517a96e0a99 100644 --- a/go/s3/CopyObject/CopyObject_test.go +++ b/go/s3/CopyObject/CopyObject_test.go @@ -1,38 +1,27 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - - "github.com/google/uuid" + "encoding/json" + "fmt" + "io/ioutil" + "os" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + + "github.com/google/uuid" ) type Config struct { - SourceBucket string `json:"SourceBucket"` - TargetBucket string `json:"TargetBucket"` - Item string `json:"Item"` + SourceBucket string `json:"SourceBucket"` + TargetBucket string `json:"TargetBucket"` + Item string `json:"Item"` } var configFileName = "config.json" @@ -40,172 +29,172 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("SourceBucket: " + globalConfig.SourceBucket) - t.Log("TargetBucket: " + globalConfig.TargetBucket) - t.Log("Item: " + globalConfig.Item) + t.Log("SourceBucket: " + globalConfig.SourceBucket) + t.Log("TargetBucket: " + globalConfig.TargetBucket) + t.Log("Item: " + globalConfig.Item) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func putFile(sess *session.Session, bucket *string, filename *string) error { - file, err := os.Open(*filename) - if err != nil { - fmt.Println("Unable to open file " + *filename) - return err - } - - defer file.Close() - - uploader := s3manager.NewUploader(sess) - - _, err = uploader.Upload(&s3manager.UploadInput{ - Bucket: bucket, - Key: filename, - Body: file, - }) - if err != nil { - return err - } - - return nil + file, err := os.Open(*filename) + if err != nil { + fmt.Println("Unable to open file " + *filename) + return err + } + + defer file.Close() + + uploader := s3manager.NewUploader(sess) + + _, err = uploader.Upload(&s3manager.UploadInput{ + Bucket: bucket, + Key: filename, + Body: file, + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucket, - }) - - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - if err != nil { - return err - } - - _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucket, + }) + + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + if err != nil { + return err + } + + _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestCopyObject(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - createdBuckets := false - - if globalConfig.SourceBucket == "" || globalConfig.TargetBucket == "" { - id := uuid.New() - globalConfig.SourceBucket = "source-bucket-" + id.String() - globalConfig.TargetBucket = "target-bucket-" + id.String() - - err := createBucket(sess, &globalConfig.SourceBucket) - if err != nil { - t.Log("Could not create bucket " + globalConfig.SourceBucket) - t.Fatal(err) - } - - t.Log("Created bucket " + globalConfig.SourceBucket) - - err = createBucket(sess, &globalConfig.TargetBucket) - if err != nil { - t.Log("Could not create bucket " + globalConfig.TargetBucket) - t.Fatal(err) - } - - t.Log("Created bucket " + globalConfig.TargetBucket) - - if globalConfig.Item == "" { - globalConfig.Item = "test.txt" - } - - err = putFile(sess, &globalConfig.SourceBucket, &globalConfig.Item) - if err != nil { - t.Log("Could not upload " + globalConfig.Item + " to " + globalConfig.SourceBucket) - t.Fatal(err) - } - - t.Log("Uploaded " + globalConfig.Item + " to " + globalConfig.SourceBucket) - - createdBuckets = true - } - - err = CopyItem(sess, &globalConfig.SourceBucket, &globalConfig.TargetBucket, &globalConfig.Item) - if err != nil { - t.Log("Could not copy " + globalConfig.Item + " to " + globalConfig.TargetBucket) - t.Fatal(err) - } - - t.Log("Copied " + globalConfig.Item + " to " + globalConfig.TargetBucket) - - if createdBuckets { - err := deleteBucket(sess, &globalConfig.SourceBucket) - if err != nil { - t.Log("You must delete buckets " + globalConfig.SourceBucket + " and " + globalConfig.TargetBucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted bucket " + globalConfig.SourceBucket) - - err = deleteBucket(sess, &globalConfig.TargetBucket) - if err != nil { - t.Log("You must delete bucket " + globalConfig.TargetBucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted bucket " + globalConfig.TargetBucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + createdBuckets := false + + if globalConfig.SourceBucket == "" || globalConfig.TargetBucket == "" { + id := uuid.New() + globalConfig.SourceBucket = "source-bucket-" + id.String() + globalConfig.TargetBucket = "target-bucket-" + id.String() + + err := createBucket(sess, &globalConfig.SourceBucket) + if err != nil { + t.Log("Could not create bucket " + globalConfig.SourceBucket) + t.Fatal(err) + } + + t.Log("Created bucket " + globalConfig.SourceBucket) + + err = createBucket(sess, &globalConfig.TargetBucket) + if err != nil { + t.Log("Could not create bucket " + globalConfig.TargetBucket) + t.Fatal(err) + } + + t.Log("Created bucket " + globalConfig.TargetBucket) + + if globalConfig.Item == "" { + globalConfig.Item = "test.txt" + } + + err = putFile(sess, &globalConfig.SourceBucket, &globalConfig.Item) + if err != nil { + t.Log("Could not upload " + globalConfig.Item + " to " + globalConfig.SourceBucket) + t.Fatal(err) + } + + t.Log("Uploaded " + globalConfig.Item + " to " + globalConfig.SourceBucket) + + createdBuckets = true + } + + err = CopyItem(sess, &globalConfig.SourceBucket, &globalConfig.TargetBucket, &globalConfig.Item) + if err != nil { + t.Log("Could not copy " + globalConfig.Item + " to " + globalConfig.TargetBucket) + t.Fatal(err) + } + + t.Log("Copied " + globalConfig.Item + " to " + globalConfig.TargetBucket) + + if createdBuckets { + err := deleteBucket(sess, &globalConfig.SourceBucket) + if err != nil { + t.Log("You must delete buckets " + globalConfig.SourceBucket + " and " + globalConfig.TargetBucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted bucket " + globalConfig.SourceBucket) + + err = deleteBucket(sess, &globalConfig.TargetBucket) + if err != nil { + t.Log("You must delete bucket " + globalConfig.TargetBucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted bucket " + globalConfig.TargetBucket) + } } diff --git a/go/s3/CreateBucket/CreateBucket.go b/go/s3/CreateBucket/CreateBucket.go index bde89b5ca3b..097ca5544dc 100644 --- a/go/s3/CreateBucket/CreateBucket.go +++ b/go/s3/CreateBucket/CreateBucket.go @@ -1,80 +1,74 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.create_bucket] package main // snippet-start:[s3.go.create_bucket.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.create_bucket.imports] // MakeBucket creates a bucket. // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// // Output: -// If success, nil -// Otherwise, an error from the call to CreateBucket +// +// If success, nil +// Otherwise, an error from the call to CreateBucket func MakeBucket(sess *session.Session, bucket *string) error { - // snippet-start:[s3.go.create_bucket.call] - svc := s3.New(sess) + // snippet-start:[s3.go.create_bucket.call] + svc := s3.New(sess) - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - // snippet-end:[s3.go.create_bucket.call] - if err != nil { - return err - } + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + // snippet-end:[s3.go.create_bucket.call] + if err != nil { + return err + } - // snippet-start:[s3.go.create_bucket.wait] - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - // snippet-end:[s3.go.create_bucket.wait] - if err != nil { - return err - } + // snippet-start:[s3.go.create_bucket.wait] + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + // snippet-end:[s3.go.create_bucket.wait] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[s3.go.create_bucket.args] - bucket := flag.String("b", "", "The name of the bucket") - flag.Parse() + // snippet-start:[s3.go.create_bucket.args] + bucket := flag.String("b", "", "The name of the bucket") + flag.Parse() - if *bucket == "" { - fmt.Println("You must supply a bucket name (-b BUCKET)") - return - } - // snippet-end:[s3.go.create_bucket.args] + if *bucket == "" { + fmt.Println("You must supply a bucket name (-b BUCKET)") + return + } + // snippet-end:[s3.go.create_bucket.args] - // snippet-start:[s3.go.create_bucket.imports.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.create_bucket.imports.session] + // snippet-start:[s3.go.create_bucket.imports.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.create_bucket.imports.session] - err := MakeBucket(sess, bucket) - if err != nil { - fmt.Println("Could not create bucket " + *bucket) - } + err := MakeBucket(sess, bucket) + if err != nil { + fmt.Println("Could not create bucket " + *bucket) + } } + // snippet-end:[s3.go.create_bucket] diff --git a/go/s3/CreateBucket/CreateBucket_test.go b/go/s3/CreateBucket/CreateBucket_test.go index 8b0ce5da1e6..95ee19de8ee 100644 --- a/go/s3/CreateBucket/CreateBucket_test.go +++ b/go/s3/CreateBucket/CreateBucket_test.go @@ -1,31 +1,20 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/google/uuid" + "encoding/json" + "io/ioutil" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` + Bucket string `json:"Bucket"` } var configFileName = "config.json" @@ -33,120 +22,120 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Bucket: " + globalConfig.Bucket) - return nil + return nil } func getBuckets(sess *session.Session) (*s3.ListBucketsOutput, error) { - svc := s3.New(sess) + svc := s3.New(sess) - result, err := svc.ListBuckets(&s3.ListBucketsInput{}) - if err != nil { - return nil, err - } + result, err := svc.ListBuckets(&s3.ListBucketsInput{}) + if err != nil { + return nil, err + } - return result, nil + return result, nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestCreateBucket(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file (~/.aws/credentials) - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - result, err := getBuckets(sess) - if err != nil { - t.Fatal(err) - } - - numBuckets := len(result.Buckets) - - bucketCreated := false - - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - bucketCreated = true - } - - err = MakeBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - result, err = getBuckets(sess) - if err != nil { - t.Fatal(err) - } - - lenEqual := len(result.Buckets) == numBuckets+1 - - if !lenEqual { - t.Fatal("Adding a bucket didn't work") - } - - foundBucket := false - - for _, b := range result.Buckets { - if *b.Name == globalConfig.Bucket { - foundBucket = true - break - } - } - - if foundBucket { - t.Log("Found bucket in list") - } else { - t.Log("Did not find bucket in list") - } - - if bucketCreated { - err = deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - } - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file (~/.aws/credentials) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + result, err := getBuckets(sess) + if err != nil { + t.Fatal(err) + } + + numBuckets := len(result.Buckets) + + bucketCreated := false + + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + bucketCreated = true + } + + err = MakeBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + result, err = getBuckets(sess) + if err != nil { + t.Fatal(err) + } + + lenEqual := len(result.Buckets) == numBuckets+1 + + if !lenEqual { + t.Fatal("Adding a bucket didn't work") + } + + foundBucket := false + + for _, b := range result.Buckets { + if *b.Name == globalConfig.Bucket { + foundBucket = true + break + } + } + + if foundBucket { + t.Log("Found bucket in list") + } else { + t.Log("Did not find bucket in list") + } + + if bucketCreated { + err = deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + } + } } diff --git a/go/s3/CreateBucketAndObject/CreateBucketAndObject.go b/go/s3/CreateBucketAndObject/CreateBucketAndObject.go index bda907e8cb8..5d3d7a4ffaa 100644 --- a/go/s3/CreateBucketAndObject/CreateBucketAndObject.go +++ b/go/s3/CreateBucketAndObject/CreateBucketAndObject.go @@ -1,97 +1,91 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.create_bucket_and_object] package main // snippet-start:[s3.go.create_bucket_and_object.imports] import ( - "flag" - "fmt" - "strings" + "flag" + "fmt" + "strings" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.create_bucket_and_object.imports] // CreateBucketAndObject creates an Amazon S3 bucket and a dummy object in that bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket -// key is the name of the object +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// key is the name of the object +// // Output: -// If success, nil -// Otherwise, an error from the call to CreateBucket, WaitUntilBucketExists, or PutObject +// +// If success, nil +// Otherwise, an error from the call to CreateBucket, WaitUntilBucketExists, or PutObject func CreateBucketAndObject(sess *session.Session, bucket *string, key *string) error { - // snippet-start:[s3.go.create_bucket_and_object.call] - svc := s3.New(sess) + // snippet-start:[s3.go.create_bucket_and_object.call] + svc := s3.New(sess) - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - // snippet-end:[s3.go.create_bucket_and_object.call] - if err != nil { - fmt.Println("Got error trying to create bucket:") - return err - } + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + // snippet-end:[s3.go.create_bucket_and_object.call] + if err != nil { + fmt.Println("Got error trying to create bucket:") + return err + } - // snippet-start:[s3.go.create_bucket_and_object.wait] - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{Bucket: bucket}) - // snippet-end:[s3.go.create_bucket_and_object.wait] - if err != nil { - fmt.Println("Got error waiting for bucket:") - return err - } + // snippet-start:[s3.go.create_bucket_and_object.wait] + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{Bucket: bucket}) + // snippet-end:[s3.go.create_bucket_and_object.wait] + if err != nil { + fmt.Println("Got error waiting for bucket:") + return err + } - // snippet-start:[s3.go.create_bucket_and_object.put_object] - _, err = svc.PutObject(&s3.PutObjectInput{ - Body: strings.NewReader("Hello World!"), - Bucket: bucket, - Key: key, - }) - // snippet-end:[s3.go.create_bucket_and_object.put_object] - if err != nil { - fmt.Println("Got error putting object in bucket:") - return err - } + // snippet-start:[s3.go.create_bucket_and_object.put_object] + _, err = svc.PutObject(&s3.PutObjectInput{ + Body: strings.NewReader("Hello World!"), + Bucket: bucket, + Key: key, + }) + // snippet-end:[s3.go.create_bucket_and_object.put_object] + if err != nil { + fmt.Println("Got error putting object in bucket:") + return err + } - return nil + return nil } func main() { - // snippet-start:[s3.go.create_bucket_and_object.put_args] - bucket := flag.String("b", "", "The name of the bucket") - key := flag.String("k", "TestFile.txt", "The name of the object (key)") - flag.Parse() + // snippet-start:[s3.go.create_bucket_and_object.put_args] + bucket := flag.String("b", "", "The name of the bucket") + key := flag.String("k", "TestFile.txt", "The name of the object (key)") + flag.Parse() - if *bucket == "" { - fmt.Println("You must supply the name of the bucket (-b BUCKET)") - } - // snippet-end:[s3.go.create_bucket_and_object.put_args] + if *bucket == "" { + fmt.Println("You must supply the name of the bucket (-b BUCKET)") + } + // snippet-end:[s3.go.create_bucket_and_object.put_args] - // snippet-start:[s3.go.create_bucket_and_object.put_session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.create_bucket_and_object.put_session] + // snippet-start:[s3.go.create_bucket_and_object.put_session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.create_bucket_and_object.put_session] - err := CreateBucketAndObject(sess, bucket, key) - if err != nil { - fmt.Println("err") - return - } + err := CreateBucketAndObject(sess, bucket, key) + if err != nil { + fmt.Println("err") + return + } - fmt.Println("Successfully created bucket " + *bucket + " and uploaded data with key " + *key) + fmt.Println("Successfully created bucket " + *bucket + " and uploaded data with key " + *key) } -// snippet-end:[s3.go.create_bucket_and_object] \ No newline at end of file + +// snippet-end:[s3.go.create_bucket_and_object] diff --git a/go/s3/CreateBucketAndObject/CreateBucketAndObject_test.go b/go/s3/CreateBucketAndObject/CreateBucketAndObject_test.go index 5fee8faf671..63ccc6b04e3 100644 --- a/go/s3/CreateBucketAndObject/CreateBucketAndObject_test.go +++ b/go/s3/CreateBucketAndObject/CreateBucketAndObject_test.go @@ -1,34 +1,23 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - "github.com/google/uuid" + "encoding/json" + "io/ioutil" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` - Key string `json:"Key"` + Bucket string `json:"Bucket"` + Key string `json:"Key"` } var configFileName = "config.json" @@ -36,138 +25,138 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) - t.Log("Key: " + globalConfig.Key) + t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Key: " + globalConfig.Key) - return nil + return nil } func getBuckets(sess *session.Session) (*s3.ListBucketsOutput, error) { - svc := s3.New(sess) + svc := s3.New(sess) - result, err := svc.ListBuckets(&s3.ListBucketsInput{}) - if err != nil { - return nil, err - } + result, err := svc.ListBuckets(&s3.ListBucketsInput{}) + if err != nil { + return nil, err + } - return result, nil + return result, nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucket, - }) - - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - if err != nil { - return err - } - - _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucket, + }) + + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + if err != nil { + return err + } + + _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestCreateBucket(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file (~/.aws/credentials) - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - result, err := getBuckets(sess) - if err != nil { - t.Fatal(err) - } - - numBuckets := len(result.Buckets) - - bucketCreated := false - - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - bucketCreated = true - } - - if globalConfig.Key == "" { - globalConfig.Key = "TestFile.txt" - } - - err = CreateBucketAndObject(sess, &globalConfig.Bucket, &globalConfig.Key) - if err != nil { - t.Fatal(err) - } - - t.Log("Created bucket " + globalConfig.Bucket + " with object " + globalConfig.Key) - - result, err = getBuckets(sess) - if err != nil { - t.Fatal(err) - } - - lenEqual := len(result.Buckets) == numBuckets+1 - - if !lenEqual { - t.Fatal("Adding a bucket didn't work") - } - - foundBucket := false - - for _, b := range result.Buckets { - if *b.Name == globalConfig.Bucket { - foundBucket = true - break - } - } - - if foundBucket { - t.Log("Found bucket in list") - } else { - t.Log("Did not find bucket in list") - } - - if bucketCreated { - err = deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - } - - t.Log("Deleted bucket " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file (~/.aws/credentials) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + result, err := getBuckets(sess) + if err != nil { + t.Fatal(err) + } + + numBuckets := len(result.Buckets) + + bucketCreated := false + + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + bucketCreated = true + } + + if globalConfig.Key == "" { + globalConfig.Key = "TestFile.txt" + } + + err = CreateBucketAndObject(sess, &globalConfig.Bucket, &globalConfig.Key) + if err != nil { + t.Fatal(err) + } + + t.Log("Created bucket " + globalConfig.Bucket + " with object " + globalConfig.Key) + + result, err = getBuckets(sess) + if err != nil { + t.Fatal(err) + } + + lenEqual := len(result.Buckets) == numBuckets+1 + + if !lenEqual { + t.Fatal("Adding a bucket didn't work") + } + + foundBucket := false + + for _, b := range result.Buckets { + if *b.Name == globalConfig.Bucket { + foundBucket = true + break + } + } + + if foundBucket { + t.Log("Found bucket in list") + } else { + t.Log("Did not find bucket in list") + } + + if bucketCreated { + err = deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + } + + t.Log("Deleted bucket " + globalConfig.Bucket) + } } diff --git a/go/s3/CustomClient/CustomHttpClient.go b/go/s3/CustomClient/CustomHttpClient.go index 7ade3395481..5c90a290faa 100644 --- a/go/s3/CustomClient/CustomHttpClient.go +++ b/go/s3/CustomClient/CustomHttpClient.go @@ -1,35 +1,24 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.customHttpClient] package main // snippet-start:[s3.go.customHttpClient.import] import ( - "bytes" - "context" - "flag" - "fmt" - "io" - "net" - "net/http" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - - "golang.org/x/net/http2" + "bytes" + "context" + "flag" + "fmt" + "io" + "net" + "net/http" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + + "golang.org/x/net/http2" ) // snippet-end:[s3.go.customHttpClient.import] @@ -37,201 +26,209 @@ import ( // HTTPClientSettings defines the HTTP setting for clients // snippet-start:[s3.go.customHttpClient_struct] type HTTPClientSettings struct { - Connect time.Duration - ConnKeepAlive time.Duration - ExpectContinue time.Duration - IdleConn time.Duration - MaxAllIdleConns int - MaxHostIdleConns int - ResponseHeader time.Duration - TLSHandshake time.Duration + Connect time.Duration + ConnKeepAlive time.Duration + ExpectContinue time.Duration + IdleConn time.Duration + MaxAllIdleConns int + MaxHostIdleConns int + ResponseHeader time.Duration + TLSHandshake time.Duration } // snippet-end:[s3.go.customHttpClient_struct] // NewHTTPClientWithSettings creates an HTTP client with some custom settings // Inputs: -// httpSettings contains some custom HTTP settings for the client +// +// httpSettings contains some custom HTTP settings for the client +// // Output: -// If success, an HTTP client -// Otherwise, ??? +// +// If success, an HTTP client +// Otherwise, ??? +// // snippet-start:[s3.go.customHttpClient_client] func NewHTTPClientWithSettings(httpSettings HTTPClientSettings) (*http.Client, error) { - var client http.Client - tr := &http.Transport{ - ResponseHeaderTimeout: httpSettings.ResponseHeader, - Proxy: http.ProxyFromEnvironment, - DialContext: (&net.Dialer{ - KeepAlive: httpSettings.ConnKeepAlive, - DualStack: true, - Timeout: httpSettings.Connect, - }).DialContext, - MaxIdleConns: httpSettings.MaxAllIdleConns, - IdleConnTimeout: httpSettings.IdleConn, - TLSHandshakeTimeout: httpSettings.TLSHandshake, - MaxIdleConnsPerHost: httpSettings.MaxHostIdleConns, - ExpectContinueTimeout: httpSettings.ExpectContinue, - } - - // So client makes HTTP/2 requests - err := http2.ConfigureTransport(tr) - if err != nil { - return &client, err - } - - return &http.Client{ - Transport: tr, - }, nil + var client http.Client + tr := &http.Transport{ + ResponseHeaderTimeout: httpSettings.ResponseHeader, + Proxy: http.ProxyFromEnvironment, + DialContext: (&net.Dialer{ + KeepAlive: httpSettings.ConnKeepAlive, + DualStack: true, + Timeout: httpSettings.Connect, + }).DialContext, + MaxIdleConns: httpSettings.MaxAllIdleConns, + IdleConnTimeout: httpSettings.IdleConn, + TLSHandshakeTimeout: httpSettings.TLSHandshake, + MaxIdleConnsPerHost: httpSettings.MaxHostIdleConns, + ExpectContinueTimeout: httpSettings.ExpectContinue, + } + + // So client makes HTTP/2 requests + err := http2.ConfigureTransport(tr) + if err != nil { + return &client, err + } + + return &http.Client{ + Transport: tr, + }, nil } // snippet-end:[s3.go.customHttpClient_client] // GetObjectWithTimeout retrieves an S3 bucket object, but only within 20 seconds // Inputs: -// bucket is the name of the S3 bucket -// object is the name of the S3 bucket object +// +// bucket is the name of the S3 bucket +// object is the name of the S3 bucket object +// // Output: -// If success, the content of the object and nil -// Otherwise, an empty object and an error from the call to GetObjectWithContext +// +// If success, the content of the object and nil +// Otherwise, an empty object and an error from the call to GetObjectWithContext func GetObjectWithTimeout(sess *session.Session, bucket *string, object *string) (io.ReadCloser, error) { - var body io.ReadCloser - svc := s3.New(sess) - - // snippet-start:[s3.go.customHttpClient.get_object] - ctx, cancelFn := context.WithTimeout(context.TODO(), 20*time.Second) - defer cancelFn() - - resp, err := svc.GetObjectWithContext(ctx, &s3.GetObjectInput{ - Bucket: bucket, - Key: object, - }) - if err != nil { - return body, err - } - - return resp.Body, nil - // snippet-end:[s3.go.customHttpClient.get_object] + var body io.ReadCloser + svc := s3.New(sess) + + // snippet-start:[s3.go.customHttpClient.get_object] + ctx, cancelFn := context.WithTimeout(context.TODO(), 20*time.Second) + defer cancelFn() + + resp, err := svc.GetObjectWithContext(ctx, &s3.GetObjectInput{ + Bucket: bucket, + Key: object, + }) + if err != nil { + return body, err + } + + return resp.Body, nil + // snippet-end:[s3.go.customHttpClient.get_object] } // Create a custom HTTP client and uses it to get an S3 bucket item // or get it using a custom timeout of 20 seconds. // // Usage: -// go run customHttpClient -b BUCKET-NAME -o OBJECT-NAME [-s] [-t] +// +// go run customHttpClient -b BUCKET-NAME -o OBJECT-NAME [-s] [-t] func main() { - // snippet-start:[s3.go.customHttpClient.args] - bucket := flag.String("b", "", "The name of the bucket") - object := flag.String("o", "", "The name of the bucket object") - show := flag.Bool("s", false, "Whether to show the object as a string") - timeout := flag.Bool("t", false, "Whether to get the object within a 20 second timeout or use the default custom HTTP client") - flag.Parse() - - if *bucket == "" || *object == "" { - fmt.Println("You must supply the name of the bucket and object") - fmt.Println("Usage: go run customHttpClient -b BUCKET -o OBJECT [-s] [-t]") - return - } - // snippet-end:[s3.go.customHttpClient.args] - - fmt.Println("Getting object " + *object + " from bucket " + *bucket) - - var body io.ReadCloser - var err error - - if *timeout { - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file (~/.aws/credentials) - // snippet-start:[s3.go.customHttpClient.sess] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.customHttpClient.sess] - - // Get object using 20 second timeout - body, err = GetObjectWithTimeout(sess, bucket, object) - if err != nil { - fmt.Println("Could not get " + *object + " from " + *bucket) - return - } - - fmt.Println("Got " + *object + " from " + *bucket) - } else { - // Creating a SDK session using the custom HTTP client - // and use that session to create S3 client. - // snippet-start:[s3.go.customHttpClient_session] - httpClient, err := NewHTTPClientWithSettings(HTTPClientSettings{ - Connect: 5 * time.Second, - ExpectContinue: 1 * time.Second, - IdleConn: 90 * time.Second, - ConnKeepAlive: 30 * time.Second, - MaxAllIdleConns: 100, - MaxHostIdleConns: 10, - ResponseHeader: 5 * time.Second, - TLSHandshake: 5 * time.Second, - }) - if err != nil { - fmt.Println("Got an error creating custom HTTP client:") - fmt.Println(err) - return - } - - sess := session.Must(session.NewSession(&aws.Config{ - HTTPClient: httpClient, - })) - - svc := s3.New(sess) - // snippet-end:[s3.go.customHttpClient_session] - - /* If you are only using one client, - * you could use the custom HTTP client when you create the client object: - * - sess := session.Must(session.NewSession()) - - client := s3.New(sess, &aws.Config{ - HTTPClient: NewHTTPClientWithSettings(HTTPClientSettings{ - Connect: 5 * time.Second, - ExpectContinue: 1 * time.Second, - IdleConn: 90 * time.Second, - KeepAlive: 30 * time.Second, - MaxAllIdleConns: 100, - MaxHostIdleConns: 10, - ResponseHeader: 5 * time.Second, - TLSHandshake: 5 * time.Second, - }), - }) - * - */ - - obj, err := svc.GetObject(&s3.GetObjectInput{ - Bucket: bucket, - Key: object, - }) - if err != nil { - fmt.Println("Got error calling GetObject:") - fmt.Println(err.Error()) - return - } - - body = obj.Body - } - - if *show { - // Convert body from IO.ReadCloser to string: - buf := new(bytes.Buffer) - - _, err := buf.ReadFrom(body) - if err != nil { - fmt.Println("Got an error reading body of object:") - fmt.Println(err) - return - } - - newBytes := buf.String() - s := string(newBytes) - - fmt.Println("Bucket object as string:") - fmt.Println(s) - } + // snippet-start:[s3.go.customHttpClient.args] + bucket := flag.String("b", "", "The name of the bucket") + object := flag.String("o", "", "The name of the bucket object") + show := flag.Bool("s", false, "Whether to show the object as a string") + timeout := flag.Bool("t", false, "Whether to get the object within a 20 second timeout or use the default custom HTTP client") + flag.Parse() + + if *bucket == "" || *object == "" { + fmt.Println("You must supply the name of the bucket and object") + fmt.Println("Usage: go run customHttpClient -b BUCKET -o OBJECT [-s] [-t]") + return + } + // snippet-end:[s3.go.customHttpClient.args] + + fmt.Println("Getting object " + *object + " from bucket " + *bucket) + + var body io.ReadCloser + var err error + + if *timeout { + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file (~/.aws/credentials) + // snippet-start:[s3.go.customHttpClient.sess] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.customHttpClient.sess] + + // Get object using 20 second timeout + body, err = GetObjectWithTimeout(sess, bucket, object) + if err != nil { + fmt.Println("Could not get " + *object + " from " + *bucket) + return + } + + fmt.Println("Got " + *object + " from " + *bucket) + } else { + // Creating a SDK session using the custom HTTP client + // and use that session to create S3 client. + // snippet-start:[s3.go.customHttpClient_session] + httpClient, err := NewHTTPClientWithSettings(HTTPClientSettings{ + Connect: 5 * time.Second, + ExpectContinue: 1 * time.Second, + IdleConn: 90 * time.Second, + ConnKeepAlive: 30 * time.Second, + MaxAllIdleConns: 100, + MaxHostIdleConns: 10, + ResponseHeader: 5 * time.Second, + TLSHandshake: 5 * time.Second, + }) + if err != nil { + fmt.Println("Got an error creating custom HTTP client:") + fmt.Println(err) + return + } + + sess := session.Must(session.NewSession(&aws.Config{ + HTTPClient: httpClient, + })) + + svc := s3.New(sess) + // snippet-end:[s3.go.customHttpClient_session] + + /* If you are only using one client, + * you could use the custom HTTP client when you create the client object: + * + sess := session.Must(session.NewSession()) + + client := s3.New(sess, &aws.Config{ + HTTPClient: NewHTTPClientWithSettings(HTTPClientSettings{ + Connect: 5 * time.Second, + ExpectContinue: 1 * time.Second, + IdleConn: 90 * time.Second, + KeepAlive: 30 * time.Second, + MaxAllIdleConns: 100, + MaxHostIdleConns: 10, + ResponseHeader: 5 * time.Second, + TLSHandshake: 5 * time.Second, + }), + }) + * + */ + + obj, err := svc.GetObject(&s3.GetObjectInput{ + Bucket: bucket, + Key: object, + }) + if err != nil { + fmt.Println("Got error calling GetObject:") + fmt.Println(err.Error()) + return + } + + body = obj.Body + } + + if *show { + // Convert body from IO.ReadCloser to string: + buf := new(bytes.Buffer) + + _, err := buf.ReadFrom(body) + if err != nil { + fmt.Println("Got an error reading body of object:") + fmt.Println(err) + return + } + + newBytes := buf.String() + s := string(newBytes) + + fmt.Println("Bucket object as string:") + fmt.Println(s) + } } // snippet-end:[s3.go.customHttpClient] diff --git a/go/s3/CustomClient/CustomHttpClient_test.go b/go/s3/CustomClient/CustomHttpClient_test.go index 8931946a5c4..b4c86688384 100644 --- a/go/s3/CustomClient/CustomHttpClient_test.go +++ b/go/s3/CustomClient/CustomHttpClient_test.go @@ -1,40 +1,29 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "bytes" - "encoding/json" - "io" - "io/ioutil" - "strings" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/google/uuid" + "bytes" + "encoding/json" + "io" + "io/ioutil" + "strings" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/google/uuid" ) type config struct { - Bucket string `json:"Bucket"` - Object string `json:"Object"` - UseTimeout bool `json:"UseTimeout"` - ShowObject bool `json:"ShowObject"` - BucketCreated bool - ObjectCreated bool + Bucket string `json:"Bucket"` + Object string `json:"Object"` + UseTimeout bool `json:"UseTimeout"` + ShowObject bool `json:"ShowObject"` + BucketCreated bool + ObjectCreated bool } var configFileName = "config.json" @@ -42,247 +31,247 @@ var configFileName = "config.json" var globalConfig config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket name: " + globalConfig.Bucket) - t.Log("Object name: " + globalConfig.Object) + t.Log("Bucket name: " + globalConfig.Bucket) + t.Log("Object name: " + globalConfig.Object) - if globalConfig.UseTimeout { - t.Log("Use timeout?: enabled") - } else { - t.Log("Use timeout?: disabled") - } + if globalConfig.UseTimeout { + t.Log("Use timeout?: enabled") + } else { + t.Log("Use timeout?: disabled") + } - if globalConfig.ShowObject { - t.Log("Show object?: enabled") - } else { - t.Log("Show object?: disabled") - } + if globalConfig.ShowObject { + t.Log("Show object?: enabled") + } else { + t.Log("Show object?: disabled") + } - globalConfig.BucketCreated = false + globalConfig.BucketCreated = false - return nil + return nil } func createBucket(sess *session.Session, id uuid.UUID) error { - globalConfig.Bucket = "custom-bucket-" + id.String() + globalConfig.Bucket = "custom-bucket-" + id.String() - svc := s3.New(sess) + svc := s3.New(sess) - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: aws.String(globalConfig.Bucket), - }) - if err != nil { - return err - } + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: aws.String(globalConfig.Bucket), + }) + if err != nil { + return err + } - globalConfig.BucketCreated = true + globalConfig.BucketCreated = true - return nil + return nil } func createObject(sess *session.Session, bucket *string, id uuid.UUID) error { - globalConfig.Object = "custom-object-" + id.String() + globalConfig.Object = "custom-object-" + id.String() - svc := s3.New(sess) + svc := s3.New(sess) - _, err := svc.PutObject(&s3.PutObjectInput{ - Body: strings.NewReader("Hello World!"), - Bucket: bucket, - Key: &globalConfig.Object, - }) - if err != nil { - return err - } + _, err := svc.PutObject(&s3.PutObjectInput{ + Body: strings.NewReader("Hello World!"), + Bucket: bucket, + Key: &globalConfig.Object, + }) + if err != nil { + return err + } - globalConfig.ObjectCreated = true + globalConfig.ObjectCreated = true - return nil + return nil } func showObject(t *testing.T, show bool, body io.ReadCloser) { - if show { - // Convert body from IO.ReadCloser to string: - buf := new(bytes.Buffer) + if show { + // Convert body from IO.ReadCloser to string: + buf := new(bytes.Buffer) - _, err := buf.ReadFrom(body) - if err != nil { - t.Fatal(err) - } + _, err := buf.ReadFrom(body) + if err != nil { + t.Fatal(err) + } - newBytes := buf.String() - s := string(newBytes) + newBytes := buf.String() + s := string(newBytes) - t.Log("Bucket item as string:") - t.Log(s) - } + t.Log("Bucket item as string:") + t.Log(s) + } } func deleteObject(sess *session.Session, bucket *string, object *string) error { - svc := s3.New(sess) - - _, err := svc.DeleteObject(&s3.DeleteObjectInput{ - Bucket: bucket, - Key: object, - }) - if err != nil { - return err - } - - return svc.WaitUntilObjectNotExists(&s3.HeadObjectInput{ - Bucket: bucket, - Key: object, - }) + svc := s3.New(sess) + + _, err := svc.DeleteObject(&s3.DeleteObjectInput{ + Bucket: bucket, + Key: object, + }) + if err != nil { + return err + } + + return svc.WaitUntilObjectNotExists(&s3.HeadObjectInput{ + Bucket: bucket, + Key: object, + }) } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) + svc := s3.New(sess) + + _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) } func TestCustomHTTPClient(t *testing.T) { - // When the test started - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal("Could not get configuration values") - } - - var body io.ReadCloser - id := uuid.New() - - if globalConfig.UseTimeout { - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file (~/.aws/credentials) - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - if globalConfig.Bucket == "" { - err := createBucket(sess, id) - if err != nil { - t.Fatal(err) - } - - t.Log("Created bucket " + globalConfig.Bucket) - } - - if globalConfig.Object == "" { - err := createObject(sess, &globalConfig.Bucket, id) - if err != nil { - t.Fatal(err) - } - - t.Log("Created object " + globalConfig.Object) - } - - // Get object using 20 second timeout - body, err = GetObjectWithTimeout(sess, &globalConfig.Bucket, &globalConfig.Object) - if err != nil { - t.Fatal(err) - } - - t.Log("Got " + globalConfig.Object + " from " + globalConfig.Bucket) - } else { - // Creating a SDK session using the custom HTTP client - // and use that session to create S3 client. - httpClient, err := NewHTTPClientWithSettings(HTTPClientSettings{ - Connect: 5 * time.Second, - ExpectContinue: 1 * time.Second, - IdleConn: 90 * time.Second, - ConnKeepAlive: 30 * time.Second, - MaxAllIdleConns: 100, - MaxHostIdleConns: 10, - ResponseHeader: 5 * time.Second, - TLSHandshake: 5 * time.Second, - }) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSession(&aws.Config{ - HTTPClient: httpClient, - })) - - if globalConfig.Bucket == "" { - err := createBucket(sess, id) - if err != nil { - t.Fatal(err) - } - - t.Log("Created bucket " + globalConfig.Bucket) - } - - if globalConfig.Object == "" { - err := createObject(sess, &globalConfig.Bucket, id) - if err != nil { - t.Fatal(err) - } - - t.Log("Created object " + globalConfig.Object) - } - - svc := s3.New(sess) - - obj, err := svc.GetObject(&s3.GetObjectInput{ - Bucket: &globalConfig.Bucket, - Key: &globalConfig.Object, - }) - if err != nil { - t.Fatal(err) - } - - body = obj.Body - } - - showObject(t, globalConfig.ShowObject, body) - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - if globalConfig.ObjectCreated { - // deleteObject(sess *session.Session, bucket *string, object *string) - err := deleteObject(sess, &globalConfig.Bucket, &globalConfig.Object) - if err != nil { - t.Log("You'll have to delete object " + globalConfig.Object + " yourself") - t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted object " + globalConfig.Object + " from bucket " + globalConfig.Bucket) - } - - if globalConfig.BucketCreated { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted bucket " + globalConfig.Bucket) - } + // When the test started + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal("Could not get configuration values") + } + + var body io.ReadCloser + id := uuid.New() + + if globalConfig.UseTimeout { + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file (~/.aws/credentials) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + if globalConfig.Bucket == "" { + err := createBucket(sess, id) + if err != nil { + t.Fatal(err) + } + + t.Log("Created bucket " + globalConfig.Bucket) + } + + if globalConfig.Object == "" { + err := createObject(sess, &globalConfig.Bucket, id) + if err != nil { + t.Fatal(err) + } + + t.Log("Created object " + globalConfig.Object) + } + + // Get object using 20 second timeout + body, err = GetObjectWithTimeout(sess, &globalConfig.Bucket, &globalConfig.Object) + if err != nil { + t.Fatal(err) + } + + t.Log("Got " + globalConfig.Object + " from " + globalConfig.Bucket) + } else { + // Creating a SDK session using the custom HTTP client + // and use that session to create S3 client. + httpClient, err := NewHTTPClientWithSettings(HTTPClientSettings{ + Connect: 5 * time.Second, + ExpectContinue: 1 * time.Second, + IdleConn: 90 * time.Second, + ConnKeepAlive: 30 * time.Second, + MaxAllIdleConns: 100, + MaxHostIdleConns: 10, + ResponseHeader: 5 * time.Second, + TLSHandshake: 5 * time.Second, + }) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSession(&aws.Config{ + HTTPClient: httpClient, + })) + + if globalConfig.Bucket == "" { + err := createBucket(sess, id) + if err != nil { + t.Fatal(err) + } + + t.Log("Created bucket " + globalConfig.Bucket) + } + + if globalConfig.Object == "" { + err := createObject(sess, &globalConfig.Bucket, id) + if err != nil { + t.Fatal(err) + } + + t.Log("Created object " + globalConfig.Object) + } + + svc := s3.New(sess) + + obj, err := svc.GetObject(&s3.GetObjectInput{ + Bucket: &globalConfig.Bucket, + Key: &globalConfig.Object, + }) + if err != nil { + t.Fatal(err) + } + + body = obj.Body + } + + showObject(t, globalConfig.ShowObject, body) + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + if globalConfig.ObjectCreated { + // deleteObject(sess *session.Session, bucket *string, object *string) + err := deleteObject(sess, &globalConfig.Bucket, &globalConfig.Object) + if err != nil { + t.Log("You'll have to delete object " + globalConfig.Object + " yourself") + t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted object " + globalConfig.Object + " from bucket " + globalConfig.Bucket) + } + + if globalConfig.BucketCreated { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted bucket " + globalConfig.Bucket) + } } diff --git a/go/s3/DeleteBucket/DeleteBucket.go b/go/s3/DeleteBucket/DeleteBucket.go index da65ebadfaa..a9e4cdef81a 100644 --- a/go/s3/DeleteBucket/DeleteBucket.go +++ b/go/s3/DeleteBucket/DeleteBucket.go @@ -1,80 +1,74 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.delete_bucket] package main // snippet-start:[s3.go.delete_bucket.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.delete_bucket.imports] // RemoveBucket deletes a bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// // Output: -// If success, nil -// Otherwise, an error from the call to CreateBucket +// +// If success, nil +// Otherwise, an error from the call to CreateBucket func RemoveBucket(sess *session.Session, bucket *string) error { - // snippet-start:[s3.go.delete_bucket.call] - svc := s3.New(sess) + // snippet-start:[s3.go.delete_bucket.call] + svc := s3.New(sess) - _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - // snippet-end:[s3.go.delete_bucket.call] - if err != nil { - return err - } + _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + // snippet-end:[s3.go.delete_bucket.call] + if err != nil { + return err + } - // snippet-start:[s3.go.delete_bucket.wait] - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - // snippet-end:[s3.go.delete_bucket.wait] - if err != nil { - return err - } + // snippet-start:[s3.go.delete_bucket.wait] + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + // snippet-end:[s3.go.delete_bucket.wait] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[s3.go.delete_bucket.args] - bucket := flag.String("b", "", "The name of the bucket") - flag.Parse() + // snippet-start:[s3.go.delete_bucket.args] + bucket := flag.String("b", "", "The name of the bucket") + flag.Parse() - if *bucket == "" { - fmt.Println("You must supply a bucket name (-b BUCKET)") - return - } - // snippet-end:[s3.go.delete_bucket.args] + if *bucket == "" { + fmt.Println("You must supply a bucket name (-b BUCKET)") + return + } + // snippet-end:[s3.go.delete_bucket.args] - // snippet-start:[s3.go.delete_bucket.imports.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.delete_bucket.imports.session] + // snippet-start:[s3.go.delete_bucket.imports.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.delete_bucket.imports.session] - err := RemoveBucket(sess, bucket) - if err != nil { - fmt.Println("Could not delete bucket " + *bucket) - } + err := RemoveBucket(sess, bucket) + if err != nil { + fmt.Println("Could not delete bucket " + *bucket) + } } + // snippet-end:[s3.go.delete_bucket] diff --git a/go/s3/DeleteBucket/DeleteBucket_test.go b/go/s3/DeleteBucket/DeleteBucket_test.go index d5ae4fb9c53..7f3add031e7 100644 --- a/go/s3/DeleteBucket/DeleteBucket_test.go +++ b/go/s3/DeleteBucket/DeleteBucket_test.go @@ -1,31 +1,20 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/google/uuid" + "encoding/json" + "io/ioutil" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` + Bucket string `json:"Bucket"` } var configFileName = "config.json" @@ -33,111 +22,111 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Bucket: " + globalConfig.Bucket) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func getBuckets(sess *session.Session) (*s3.ListBucketsOutput, error) { - svc := s3.New(sess) + svc := s3.New(sess) - result, err := svc.ListBuckets(&s3.ListBucketsInput{}) - if err != nil { - return nil, err - } + result, err := svc.ListBuckets(&s3.ListBucketsInput{}) + if err != nil { + return nil, err + } - return result, nil + return result, nil } func TestCreateBucket(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file (~/.aws/credentials) - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // If we don't have a name in config.json - // create a bucket with a random name - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - - err = createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Created bucket " + globalConfig.Bucket) - } - - // Get original list of buckets before removing one - result, err := getBuckets(sess) - if err != nil { - t.Fatal(err) - } - - numBuckets := len(result.Buckets) - - err = RemoveBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Deleted bucket " + globalConfig.Bucket) - - result, err = getBuckets(sess) - if err != nil { - t.Fatal(err) - } - - if len(result.Buckets) != numBuckets-1 { - t.Log("Not sure " + globalConfig.Bucket + " got deleted") - } - - for _, b := range result.Buckets { - if *b.Name == globalConfig.Bucket { - t.Fatal("DID NOT DELETE" + globalConfig.Bucket) - } - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file (~/.aws/credentials) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // If we don't have a name in config.json + // create a bucket with a random name + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + + err = createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Created bucket " + globalConfig.Bucket) + } + + // Get original list of buckets before removing one + result, err := getBuckets(sess) + if err != nil { + t.Fatal(err) + } + + numBuckets := len(result.Buckets) + + err = RemoveBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Deleted bucket " + globalConfig.Bucket) + + result, err = getBuckets(sess) + if err != nil { + t.Fatal(err) + } + + if len(result.Buckets) != numBuckets-1 { + t.Log("Not sure " + globalConfig.Bucket + " got deleted") + } + + for _, b := range result.Buckets { + if *b.Name == globalConfig.Bucket { + t.Fatal("DID NOT DELETE" + globalConfig.Bucket) + } + } } diff --git a/go/s3/DeleteBucketPolicy/DeleteBucketPolicy.go b/go/s3/DeleteBucketPolicy/DeleteBucketPolicy.go index 2e30929287a..a5367da3bd1 100644 --- a/go/s3/DeleteBucketPolicy/DeleteBucketPolicy.go +++ b/go/s3/DeleteBucketPolicy/DeleteBucketPolicy.go @@ -1,77 +1,71 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.delete_bucket_policy] package main // snippet-start:[s3.go.delete_bucket_policy.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.delete_bucket_policy.imports] // RemoveBucketPolicy removes the policy for a bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// // Output: -// If success, nil -// Otherwise, an error from the call to DeleteBucketPolicy +// +// If success, nil +// Otherwise, an error from the call to DeleteBucketPolicy func RemoveBucketPolicy(sess *session.Session, bucket *string) error { - // snippet-start:[s3.go.delete_bucket_policy.call] - svc := s3.New(sess) + // snippet-start:[s3.go.delete_bucket_policy.call] + svc := s3.New(sess) - _, err := svc.DeleteBucketPolicy(&s3.DeleteBucketPolicyInput{ - Bucket: bucket, - }) - // snippet-end:[s3.go.delete_bucket_policy.call] - if err != nil { - return err - } + _, err := svc.DeleteBucketPolicy(&s3.DeleteBucketPolicyInput{ + Bucket: bucket, + }) + // snippet-end:[s3.go.delete_bucket_policy.call] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[s3.go.delete_bucket_policy.args] - bucket := flag.String("b", "", "The name of the bucket") - flag.Parse() + // snippet-start:[s3.go.delete_bucket_policy.args] + bucket := flag.String("b", "", "The name of the bucket") + flag.Parse() - if *bucket == "" { - fmt.Println("You must supply a bucket name (-b BUCKET)") - return - } - // snippet-end:[s3.go.delete_bucket_policy.args] + if *bucket == "" { + fmt.Println("You must supply a bucket name (-b BUCKET)") + return + } + // snippet-end:[s3.go.delete_bucket_policy.args] - // snippet-start:[s3.go.delete_bucket_policy.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.delete_bucket_policy.session] + // snippet-start:[s3.go.delete_bucket_policy.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.delete_bucket_policy.session] - err := RemoveBucketPolicy(sess, bucket) - if err != nil { - fmt.Println("Got an error removing the bucket policy:") - fmt.Println(err) - return - } + err := RemoveBucketPolicy(sess, bucket) + if err != nil { + fmt.Println("Got an error removing the bucket policy:") + fmt.Println(err) + return + } - // snippet-start:[s3.go.delete_bucket_policy.print] - fmt.Println("Removed the bucket policy") - // snippet-end:[s3.go.delete_bucket_policy.print] + // snippet-start:[s3.go.delete_bucket_policy.print] + fmt.Println("Removed the bucket policy") + // snippet-end:[s3.go.delete_bucket_policy.print] } + // snippet-end:[s3.go.delete_bucket_policy] diff --git a/go/s3/DeleteBucketPolicy/DeleteBucketPolicy_test.go b/go/s3/DeleteBucketPolicy/DeleteBucketPolicy_test.go index 5b016561bf1..90a9c6d4cbb 100644 --- a/go/s3/DeleteBucketPolicy/DeleteBucketPolicy_test.go +++ b/go/s3/DeleteBucketPolicy/DeleteBucketPolicy_test.go @@ -1,34 +1,23 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "fmt" - "io/ioutil" - "testing" - "time" + "encoding/json" + "fmt" + "io/ioutil" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" - "github.com/google/uuid" + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` + Bucket string `json:"Bucket"` } var configFileName = "config.json" @@ -36,150 +25,150 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Bucket: " + globalConfig.Bucket) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func addBucketPolity(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - readOnlyAnonUserPolicy := map[string]interface{}{ - "Version": "2012-10-17", - "Statement": []map[string]interface{}{ - { - "Sid": "AddPerm", - "Effect": "Allow", - "Principal": "*", - "Action": []string{ - "s3:GetObject", - }, - "Resource": []string{ - "arn:aws:s3:::" + *bucket + "/*", - }, - }, - }, - } - - policy, err := json.Marshal(readOnlyAnonUserPolicy) - if err != nil { - return err - } - - _, err = svc.PutBucketPolicy(&s3.PutBucketPolicyInput{ - Bucket: bucket, - Policy: aws.String(string(policy)), - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + readOnlyAnonUserPolicy := map[string]interface{}{ + "Version": "2012-10-17", + "Statement": []map[string]interface{}{ + { + "Sid": "AddPerm", + "Effect": "Allow", + "Principal": "*", + "Action": []string{ + "s3:GetObject", + }, + "Resource": []string{ + "arn:aws:s3:::" + *bucket + "/*", + }, + }, + }, + } + + policy, err := json.Marshal(readOnlyAnonUserPolicy) + if err != nil { + return err + } + + _, err = svc.PutBucketPolicy(&s3.PutBucketPolicyInput{ + Bucket: bucket, + Policy: aws.String(string(policy)), + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestGetBucketPolicy(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - bucketCreated := false - - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - fmt.Println("Created bucket " + globalConfig.Bucket) - bucketCreated = true - - err = addBucketPolity(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - } - - err = RemoveBucketPolicy(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Removed bucket policy") - - if bucketCreated { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted bucket " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + bucketCreated := false + + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + fmt.Println("Created bucket " + globalConfig.Bucket) + bucketCreated = true + + err = addBucketPolity(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + } + + err = RemoveBucketPolicy(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Removed bucket policy") + + if bucketCreated { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted bucket " + globalConfig.Bucket) + } } diff --git a/go/s3/DeleteBucketWebsite/DeleteBucketWebsite.go b/go/s3/DeleteBucketWebsite/DeleteBucketWebsite.go index 717ec45c961..3138509eb2a 100644 --- a/go/s3/DeleteBucketWebsite/DeleteBucketWebsite.go +++ b/go/s3/DeleteBucketWebsite/DeleteBucketWebsite.go @@ -1,77 +1,69 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.delete_bucket_website] package main // snippet-start:[s3.go.delete_bucket_website.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) // snippet-end:[s3.go.delete_bucket_website.imports] // RemoveBucketWebsite removes the website configuration for a bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// // Output: -// If success, nil -// Otherwise, an error from the call to DeleteBucketWebsite +// +// If success, nil +// Otherwise, an error from the call to DeleteBucketWebsite func RemoveBucketWebsite(sess *session.Session, bucket *string) error { - // snippet-start:[s3.go.delete_bucket_website.call] - svc := s3.New(sess) + // snippet-start:[s3.go.delete_bucket_website.call] + svc := s3.New(sess) - _, err := svc.DeleteBucketWebsite(&s3.DeleteBucketWebsiteInput{ - Bucket: bucket, - }) - // snippet-end:[s3.go.delete_bucket_website.call] - if err != nil { - return err - } + _, err := svc.DeleteBucketWebsite(&s3.DeleteBucketWebsiteInput{ + Bucket: bucket, + }) + // snippet-end:[s3.go.delete_bucket_website.call] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[s3.go.delete_bucket_website.args] - bucket := flag.String("b", "", "The name of the bucket") - flag.Parse() + // snippet-start:[s3.go.delete_bucket_website.args] + bucket := flag.String("b", "", "The name of the bucket") + flag.Parse() - if *bucket == "" { - fmt.Println("You must supply the name of a bucket (-b BUCKET)") - return - } - // snippet-end:[s3.go.delete_bucket_website.args] + if *bucket == "" { + fmt.Println("You must supply the name of a bucket (-b BUCKET)") + return + } + // snippet-end:[s3.go.delete_bucket_website.args] - // snippet-start:[s3.go.delete_bucket_website.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.delete_bucket_website.session] + // snippet-start:[s3.go.delete_bucket_website.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.delete_bucket_website.session] - err := RemoveBucketWebsite(sess, bucket) - if err != nil { - fmt.Println("Got an error removing the website configuration:") - fmt.Println(err) - return - } + err := RemoveBucketWebsite(sess, bucket) + if err != nil { + fmt.Println("Got an error removing the website configuration:") + fmt.Println(err) + return + } - fmt.Printf("Successfully deleted website configuration for " + *bucket) + fmt.Printf("Successfully deleted website configuration for " + *bucket) } // snippet-end:[s3.go.delete_bucket_website] diff --git a/go/s3/DeleteBucketWebsite/DeleteBucketWebsite_test.go b/go/s3/DeleteBucketWebsite/DeleteBucketWebsite_test.go index 64ecc21d234..3ee5908514f 100644 --- a/go/s3/DeleteBucketWebsite/DeleteBucketWebsite_test.go +++ b/go/s3/DeleteBucketWebsite/DeleteBucketWebsite_test.go @@ -1,35 +1,24 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "strings" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - - "github.com/google/uuid" + "encoding/json" + "io/ioutil" + "strings" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` + Bucket string `json:"Bucket"` } var configFileName = "config.json" @@ -37,196 +26,196 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Bucket: " + globalConfig.Bucket) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func createObject(sess *session.Session, bucket *string, key *string, content *string) error { - svc := s3.New(sess) - - _, err := svc.PutObject(&s3.PutObjectInput{ - Body: strings.NewReader(*content), - Bucket: bucket, - Key: key, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.PutObject(&s3.PutObjectInput{ + Body: strings.NewReader(*content), + Bucket: bucket, + Key: key, + }) + if err != nil { + return err + } + + return nil } func setWebPage(sess *session.Session, bucket, indexPage, errorPage *string) error { - svc := s3.New(sess) - - params := s3.PutBucketWebsiteInput{ - Bucket: bucket, - WebsiteConfiguration: &s3.WebsiteConfiguration{ - IndexDocument: &s3.IndexDocument{ - Suffix: indexPage, - }, - }, - } - - if len(*errorPage) > 0 { - params.WebsiteConfiguration.ErrorDocument = &s3.ErrorDocument{ - Key: errorPage, - } - } - - _, err := svc.PutBucketWebsite(¶ms) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + params := s3.PutBucketWebsiteInput{ + Bucket: bucket, + WebsiteConfiguration: &s3.WebsiteConfiguration{ + IndexDocument: &s3.IndexDocument{ + Suffix: indexPage, + }, + }, + } + + if len(*errorPage) > 0 { + params.WebsiteConfiguration.ErrorDocument = &s3.ErrorDocument{ + Key: errorPage, + } + } + + _, err := svc.PutBucketWebsite(¶ms) + if err != nil { + return err + } + + return nil } func createBucketWebsite(sess *session.Session, bucket *string) error { - err := createBucket(sess, bucket) - if err != nil { - return err - } - - indexPage := "Index.html" - content := "

This is the index

" - err = createObject(sess, bucket, &indexPage, &content) - if err != nil { - return err - } - - errorPage := "Error.html" - content = "

ERROR!

" - err = createObject(sess, bucket, &errorPage, &content) - if err != nil { - return err - } - - err = setWebPage(sess, bucket, &indexPage, &errorPage) - if err != nil { - return err - } - - return nil + err := createBucket(sess, bucket) + if err != nil { + return err + } + + indexPage := "Index.html" + content := "

This is the index

" + err = createObject(sess, bucket, &indexPage, &content) + if err != nil { + return err + } + + errorPage := "Error.html" + content = "

ERROR!

" + err = createObject(sess, bucket, &errorPage, &content) + if err != nil { + return err + } + + err = setWebPage(sess, bucket, &indexPage, &errorPage) + if err != nil { + return err + } + + return nil } func clearBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucket, - }) + svc := s3.New(sess) + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucket, + }) - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - if err != nil { - return err - } + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + if err != nil { + return err + } - return nil + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestDeleteBucketWebsite(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - bucketCreated := false - - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - - err := createBucketWebsite(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Created bucket " + globalConfig.Bucket + " with static web site") - bucketCreated = true - } - - err = RemoveBucketWebsite(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Removed website configuration from bucket " + globalConfig.Bucket) - - if bucketCreated { - err := clearBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - err = deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted bucket " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + bucketCreated := false + + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + + err := createBucketWebsite(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Created bucket " + globalConfig.Bucket + " with static web site") + bucketCreated = true + } + + err = RemoveBucketWebsite(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Removed website configuration from bucket " + globalConfig.Bucket) + + if bucketCreated { + err := clearBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + err = deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted bucket " + globalConfig.Bucket) + } } diff --git a/go/s3/DeleteObject/DeleteObject.go b/go/s3/DeleteObject/DeleteObject.go index 7d0db7149ee..f0d2cb33803 100644 --- a/go/s3/DeleteObject/DeleteObject.go +++ b/go/s3/DeleteObject/DeleteObject.go @@ -1,91 +1,84 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.delete_object] package main // snippet-start:[s3.go.delete_object.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.delete_object.imports] // DeleteItem deletes an item from a bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket -// item is the name of the bucket object to delete +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// item is the name of the bucket object to delete +// // Output: -// If success, nil -// Otherwise, an error from the call to DeleteObject or WaitUntilObjectNotExists +// +// If success, nil +// Otherwise, an error from the call to DeleteObject or WaitUntilObjectNotExists func DeleteItem(sess *session.Session, bucket *string, item *string) error { - // snippet-start:[s3.go.delete_object.call] - svc := s3.New(sess) + // snippet-start:[s3.go.delete_object.call] + svc := s3.New(sess) - _, err := svc.DeleteObject(&s3.DeleteObjectInput{ - Bucket: bucket, - Key: item, - }) - // snippet-end:[s3.go.delete_object.call] - if err != nil { - return err - } + _, err := svc.DeleteObject(&s3.DeleteObjectInput{ + Bucket: bucket, + Key: item, + }) + // snippet-end:[s3.go.delete_object.call] + if err != nil { + return err + } - // snippet-start:[s3.go.delete_object.wait] - err = svc.WaitUntilObjectNotExists(&s3.HeadObjectInput{ - Bucket: bucket, - Key: item, - }) - // snippet-end:[s3.go.delete_object.wait] - if err != nil { - return err - } + // snippet-start:[s3.go.delete_object.wait] + err = svc.WaitUntilObjectNotExists(&s3.HeadObjectInput{ + Bucket: bucket, + Key: item, + }) + // snippet-end:[s3.go.delete_object.wait] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[s3.go.delete_object.args] - bucket := flag.String("b", "", "The bucket from which the object is deleted") - item := flag.String("i", "", "The object to delete") - flag.Parse() + // snippet-start:[s3.go.delete_object.args] + bucket := flag.String("b", "", "The bucket from which the object is deleted") + item := flag.String("i", "", "The object to delete") + flag.Parse() - if *bucket == "" || *item == "" { - fmt.Println("You must supply the bucket (-b BUCKET), and item to delete (-i ITEM") - return - } - // snippet-end:[s3.go.delete_object.args] + if *bucket == "" || *item == "" { + fmt.Println("You must supply the bucket (-b BUCKET), and item to delete (-i ITEM") + return + } + // snippet-end:[s3.go.delete_object.args] - // snippet-start:[s3.go.delete_object.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.delete_object.session] + // snippet-start:[s3.go.delete_object.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.delete_object.session] - err := DeleteItem(sess, bucket, item) - if err != nil { - fmt.Println("Got an error deleting item:") - fmt.Println(err) - return - } + err := DeleteItem(sess, bucket, item) + if err != nil { + fmt.Println("Got an error deleting item:") + fmt.Println(err) + return + } - // snippet-start:[s3.go.delete_object.print] - fmt.Println("Deleted " + *item + " from " + *bucket) - // snippet-end:[s3.go.delete_object.print] + // snippet-start:[s3.go.delete_object.print] + fmt.Println("Deleted " + *item + " from " + *bucket) + // snippet-end:[s3.go.delete_object.print] } // snippet-end:[s3.go.delete_object] diff --git a/go/s3/DeleteObject/DeleteObject_test.go b/go/s3/DeleteObject/DeleteObject_test.go index 5910ebb6e32..0149f3f12fb 100644 --- a/go/s3/DeleteObject/DeleteObject_test.go +++ b/go/s3/DeleteObject/DeleteObject_test.go @@ -1,37 +1,26 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - - "github.com/google/uuid" + "encoding/json" + "fmt" + "io/ioutil" + "os" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` - Item string `json:"Item"` + Bucket string `json:"Bucket"` + Item string `json:"Item"` } var configFileName = "config.json" @@ -39,154 +28,154 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) - t.Log("Item: " + globalConfig.Item) + t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Item: " + globalConfig.Item) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func putFile(sess *session.Session, bucket *string, filename *string) error { - file, err := os.Open(*filename) - if err != nil { - fmt.Println("Unable to open file " + *filename) - return err - } - - defer file.Close() - - uploader := s3manager.NewUploader(sess) - - _, err = uploader.Upload(&s3manager.UploadInput{ - Bucket: bucket, - Key: filename, - Body: file, - }) - if err != nil { - return err - } - - return nil + file, err := os.Open(*filename) + if err != nil { + fmt.Println("Unable to open file " + *filename) + return err + } + + defer file.Close() + + uploader := s3manager.NewUploader(sess) + + _, err = uploader.Upload(&s3manager.UploadInput{ + Bucket: bucket, + Key: filename, + Body: file, + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucket, - }) - - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - if err != nil { - return err - } - - _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucket, + }) + + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + if err != nil { + return err + } + + _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestDeleteObject(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - createdBucket := false + createdBucket := false - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("Could not create bucket " + globalConfig.Bucket) - t.Fatal(err) - } + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("Could not create bucket " + globalConfig.Bucket) + t.Fatal(err) + } - t.Log("Created bucket " + globalConfig.Bucket) + t.Log("Created bucket " + globalConfig.Bucket) - if globalConfig.Item == "" { - globalConfig.Item = "test.txt" - } + if globalConfig.Item == "" { + globalConfig.Item = "test.txt" + } - err = putFile(sess, &globalConfig.Bucket, &globalConfig.Item) - if err != nil { - t.Log("Could not upload " + globalConfig.Item + " to " + globalConfig.Bucket) - t.Fatal(err) - } + err = putFile(sess, &globalConfig.Bucket, &globalConfig.Item) + if err != nil { + t.Log("Could not upload " + globalConfig.Item + " to " + globalConfig.Bucket) + t.Fatal(err) + } - t.Log("Uploaded " + globalConfig.Item + " to " + globalConfig.Bucket) + t.Log("Uploaded " + globalConfig.Item + " to " + globalConfig.Bucket) - createdBucket = true - } + createdBucket = true + } - err = DeleteItem(sess, &globalConfig.Bucket, &globalConfig.Item) - if err != nil { - t.Log("Could not delete " + globalConfig.Item + " from " + globalConfig.Bucket) - t.Fatal(err) - } + err = DeleteItem(sess, &globalConfig.Bucket, &globalConfig.Item) + if err != nil { + t.Log("Could not delete " + globalConfig.Item + " from " + globalConfig.Bucket) + t.Fatal(err) + } - t.Log("Deleted " + globalConfig.Item + " from " + globalConfig.Bucket) + t.Log("Deleted " + globalConfig.Item + " from " + globalConfig.Bucket) - if createdBucket { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You must delete bucket " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } + if createdBucket { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You must delete bucket " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } - t.Log("Deleted bucket " + globalConfig.Bucket) - } + t.Log("Deleted bucket " + globalConfig.Bucket) + } } diff --git a/go/s3/DeleteObjects/DeleteObjects.go b/go/s3/DeleteObjects/DeleteObjects.go index ed806840d0c..042bd57b84a 100644 --- a/go/s3/DeleteObjects/DeleteObjects.go +++ b/go/s3/DeleteObjects/DeleteObjects.go @@ -1,81 +1,75 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.delete_objects] package main // snippet-start:[s3.go.delete_objects.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" ) + // snippet-end:[s3.go.delete_objects.imports] // DeleteItems deletes all of the objects in the bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// // Output: -// If success, nil -// Otherwise, an error from the call to NewBatchDeleteWithClient +// +// If success, nil +// Otherwise, an error from the call to NewBatchDeleteWithClient func DeleteItems(sess *session.Session, bucket *string) error { - // snippet-start:[s3.go.delete_objects.call] - svc := s3.New(sess) + // snippet-start:[s3.go.delete_objects.call] + svc := s3.New(sess) - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucket, - }) + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucket, + }) - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - // snippet-end:[s3.go.delete_objects.call] - if err != nil { - return err - } + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + // snippet-end:[s3.go.delete_objects.call] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[s3.go.delete_objects.args] - bucket := flag.String("b", "", "The bucket to empty") - flag.Parse() + // snippet-start:[s3.go.delete_objects.args] + bucket := flag.String("b", "", "The bucket to empty") + flag.Parse() - if *bucket == "" { - fmt.Println("You must supply a bucket to empty (-b BUCKET)") - return - } - // snippet-end:[s3.go.delete_objects.args] + if *bucket == "" { + fmt.Println("You must supply a bucket to empty (-b BUCKET)") + return + } + // snippet-end:[s3.go.delete_objects.args] - // snippet-start:[s3.go.delete_objects.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.delete_objects.session] + // snippet-start:[s3.go.delete_objects.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.delete_objects.session] - err := DeleteItems(sess, bucket) - if err != nil { - fmt.Println("Got an error deleting items:") - fmt.Println(err) - return - } + err := DeleteItems(sess, bucket) + if err != nil { + fmt.Println("Got an error deleting items:") + fmt.Println(err) + return + } - // snippet-start:[s3.go.delete_objects.print] - fmt.Println("Deleted object(s) from " + *bucket) - // snippet-end:[s3.go.delete_objects.print] + // snippet-start:[s3.go.delete_objects.print] + fmt.Println("Deleted object(s) from " + *bucket) + // snippet-end:[s3.go.delete_objects.print] } + // snippet-end:[s3.go.delete_objects] diff --git a/go/s3/DeleteObjects/DeleteObjects_test.go b/go/s3/DeleteObjects/DeleteObjects_test.go index fa6192aed92..4de649b8bdf 100644 --- a/go/s3/DeleteObjects/DeleteObjects_test.go +++ b/go/s3/DeleteObjects/DeleteObjects_test.go @@ -1,37 +1,26 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "strconv" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - - "github.com/google/uuid" + "encoding/json" + "fmt" + "io/ioutil" + "os" + "strconv" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` + Bucket string `json:"Bucket"` } var configFileName = "config.json" @@ -39,179 +28,179 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Bucket: " + globalConfig.Bucket) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func addFile(sess *session.Session, bucket *string, filename string) error { - file, err := os.Open(filename) - if err != nil { - fmt.Println("Unable to open file " + filename) - return err - } - - defer file.Close() - - uploader := s3manager.NewUploader(sess) - - _, err = uploader.Upload(&s3manager.UploadInput{ - Bucket: bucket, - Key: aws.String(filename), - Body: file, - }) - if err != nil { - return err - } - - return nil + file, err := os.Open(filename) + if err != nil { + fmt.Println("Unable to open file " + filename) + return err + } + + defer file.Close() + + uploader := s3manager.NewUploader(sess) + + _, err = uploader.Upload(&s3manager.UploadInput{ + Bucket: bucket, + Key: aws.String(filename), + Body: file, + }) + if err != nil { + return err + } + + return nil } func getObjects(sess *session.Session, bucket *string) (*s3.ListObjectsV2Output, error) { - svc := s3.New(sess) + svc := s3.New(sess) - // Get the list of items - resp, err := svc.ListObjectsV2(&s3.ListObjectsV2Input{Bucket: bucket}) - if err != nil { - return nil, err - } + // Get the list of items + resp, err := svc.ListObjectsV2(&s3.ListObjectsV2Input{Bucket: bucket}) + if err != nil { + return nil, err + } - return resp, nil + return resp, nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestDeleteObject(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - bucketCreated := false - - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("Got error creating bucket:") - t.Fatal(err) - } - - bucketCreated = true - t.Log("Created bucket " + globalConfig.Bucket) - - resp, err := getObjects(sess, &globalConfig.Bucket) - if err != nil { - t.Log("Got error retrieving list of objects:") - t.Fatal(err) - } - - t.Log("Found " + strconv.Itoa(len(resp.Contents)) + " items in " + globalConfig.Bucket + " (should be 0)") - - err = addFile(sess, &globalConfig.Bucket, "test1.txt") - if err != nil { - t.Log("Got error adding test1.txt") - t.Fatal(err) - } - - err = addFile(sess, &globalConfig.Bucket, "test2.txt") - if err != nil { - t.Log("Got error adding test2.txt") - t.Fatal(err) - } - - resp, err = getObjects(sess, &globalConfig.Bucket) - if err != nil { - t.Log("Got error retrieving list of objects:") - t.Fatal(err) - } - - t.Log("Found " + strconv.Itoa(len(resp.Contents)) + " items in " + globalConfig.Bucket + " (should be 2)") - } - - err = DeleteItems(sess, &globalConfig.Bucket) - if err != nil { - t.Log("Could not empty " + globalConfig.Bucket) - t.Fatal(err) - } - - t.Log("Emptied " + globalConfig.Bucket) - - resp, err := getObjects(sess, &globalConfig.Bucket) - if err != nil { - t.Log("Got error retrieving list of objects:") - t.Fatal(err) - } - - t.Log("Found " + strconv.Itoa(len(resp.Contents)) + " items in " + globalConfig.Bucket + " (should be 0)") - - if bucketCreated { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted bucket " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + bucketCreated := false + + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("Got error creating bucket:") + t.Fatal(err) + } + + bucketCreated = true + t.Log("Created bucket " + globalConfig.Bucket) + + resp, err := getObjects(sess, &globalConfig.Bucket) + if err != nil { + t.Log("Got error retrieving list of objects:") + t.Fatal(err) + } + + t.Log("Found " + strconv.Itoa(len(resp.Contents)) + " items in " + globalConfig.Bucket + " (should be 0)") + + err = addFile(sess, &globalConfig.Bucket, "test1.txt") + if err != nil { + t.Log("Got error adding test1.txt") + t.Fatal(err) + } + + err = addFile(sess, &globalConfig.Bucket, "test2.txt") + if err != nil { + t.Log("Got error adding test2.txt") + t.Fatal(err) + } + + resp, err = getObjects(sess, &globalConfig.Bucket) + if err != nil { + t.Log("Got error retrieving list of objects:") + t.Fatal(err) + } + + t.Log("Found " + strconv.Itoa(len(resp.Contents)) + " items in " + globalConfig.Bucket + " (should be 2)") + } + + err = DeleteItems(sess, &globalConfig.Bucket) + if err != nil { + t.Log("Could not empty " + globalConfig.Bucket) + t.Fatal(err) + } + + t.Log("Emptied " + globalConfig.Bucket) + + resp, err := getObjects(sess, &globalConfig.Bucket) + if err != nil { + t.Log("Got error retrieving list of objects:") + t.Fatal(err) + } + + t.Log("Found " + strconv.Itoa(len(resp.Contents)) + " items in " + globalConfig.Bucket + " (should be 0)") + + if bucketCreated { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted bucket " + globalConfig.Bucket) + } } diff --git a/go/s3/DownloadObject/DownloadObject.go b/go/s3/DownloadObject/DownloadObject.go index 231ffdfbb93..d1f342303f2 100644 --- a/go/s3/DownloadObject/DownloadObject.go +++ b/go/s3/DownloadObject/DownloadObject.go @@ -1,91 +1,85 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.download_object] package main // snippet-start:[s3.go.download_object.imports] import ( - "flag" - "fmt" - "os" + "flag" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" ) + // snippet-end:[s3.go.download_object.imports] // DownloadObject downloads a file from a bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// filename is the name of the file -// bucket is the name of the bucket +// +// sess is the current session, which provides configuration for the SDK's service clients +// filename is the name of the file +// bucket is the name of the bucket +// // Output: -// If success, nil -// Otherwise, an error from the call to Create or Download +// +// If success, nil +// Otherwise, an error from the call to Create or Download func DownloadObject(sess *session.Session, filename *string, bucket *string) error { - // snippet-start:[s3.go.download_object.create] - file, err := os.Create(*filename) - // snippet-end:[s3.go.download_object.create] - if err != nil { - return err - } + // snippet-start:[s3.go.download_object.create] + file, err := os.Create(*filename) + // snippet-end:[s3.go.download_object.create] + if err != nil { + return err + } + + defer file.Close() - defer file.Close() - - // snippet-start:[s3.go.download_object.call] - downloader := s3manager.NewDownloader(sess) + // snippet-start:[s3.go.download_object.call] + downloader := s3manager.NewDownloader(sess) - _, err = downloader.Download(file, - &s3.GetObjectInput{ - Bucket: bucket, - Key: filename, - }) - // snippet-end:[s3.go.download_object.call] - if err != nil { - return err - } + _, err = downloader.Download(file, + &s3.GetObjectInput{ + Bucket: bucket, + Key: filename, + }) + // snippet-end:[s3.go.download_object.call] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[s3.go.download_object.args] - bucket := flag.String("b", "", "The bucket to download from") - filename := flag.String("f", "", "The name of the file to download") - flag.Parse() + // snippet-start:[s3.go.download_object.args] + bucket := flag.String("b", "", "The bucket to download from") + filename := flag.String("f", "", "The name of the file to download") + flag.Parse() - if *bucket == "" || *filename == "" { - fmt.Println("You must specify a bucket name (-b BUCKET) and filename (-f FILENAME") - return - } - // snippet-end:[s3.go.download_object.args] + if *bucket == "" || *filename == "" { + fmt.Println("You must specify a bucket name (-b BUCKET) and filename (-f FILENAME") + return + } + // snippet-end:[s3.go.download_object.args] - // snippet-start:[s3.go.download_object.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.download_object.session] + // snippet-start:[s3.go.download_object.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.download_object.session] - err := DownloadObject(sess, filename, bucket) - if err != nil { - fmt.Println("Got error downloading " + *filename + ":") - fmt.Println(err) - return - } + err := DownloadObject(sess, filename, bucket) + if err != nil { + fmt.Println("Got error downloading " + *filename + ":") + fmt.Println(err) + return + } - fmt.Println("Downloaded " + *filename) + fmt.Println("Downloaded " + *filename) } + // snippet-end:[s3.go.download_object] diff --git a/go/s3/DownloadObject/DownloadObject_test.go b/go/s3/DownloadObject/DownloadObject_test.go index 395b9d70d99..d8e554a67f2 100644 --- a/go/s3/DownloadObject/DownloadObject_test.go +++ b/go/s3/DownloadObject/DownloadObject_test.go @@ -1,37 +1,26 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - - "github.com/google/uuid" + "encoding/json" + "fmt" + "io/ioutil" + "os" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` - Filename string `json:"Filename"` + Bucket string `json:"Bucket"` + Filename string `json:"Filename"` } var configFileName = "config.json" @@ -39,152 +28,152 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) - t.Log("Filename: " + globalConfig.Filename) + t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Filename: " + globalConfig.Filename) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func putFile(sess *session.Session, bucket *string, filename *string) error { - file, err := os.Open(*filename) - if err != nil { - fmt.Println("Unable to open file " + *filename) - return err - } - - defer file.Close() - - uploader := s3manager.NewUploader(sess) - - _, err = uploader.Upload(&s3manager.UploadInput{ - Bucket: bucket, - Key: filename, - Body: file, - }) - if err != nil { - return err - } - - return nil + file, err := os.Open(*filename) + if err != nil { + fmt.Println("Unable to open file " + *filename) + return err + } + + defer file.Close() + + uploader := s3manager.NewUploader(sess) + + _, err = uploader.Upload(&s3manager.UploadInput{ + Bucket: bucket, + Key: filename, + Body: file, + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucket, - }) - - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - if err != nil { - return err - } - - _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucket, + }) + + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + if err != nil { + return err + } + + _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestDownloadObject(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - createdBucket := false - - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Created bucket " + globalConfig.Bucket) - } - - if globalConfig.Filename == "" { - globalConfig.Filename = "dummy.txt" - - err := putFile(sess, &globalConfig.Bucket, &globalConfig.Filename) - if err != nil { - t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - err = os.Remove(globalConfig.Filename) - if err != nil { - t.Fatal(err) - } - } - - err = DownloadObject(sess, &globalConfig.Filename, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Downloaded " + globalConfig.Filename + " from bucket " + globalConfig.Bucket) - - if createdBucket { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") - } - - t.Log("Deleted bucket " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + createdBucket := false + + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Created bucket " + globalConfig.Bucket) + } + + if globalConfig.Filename == "" { + globalConfig.Filename = "dummy.txt" + + err := putFile(sess, &globalConfig.Bucket, &globalConfig.Filename) + if err != nil { + t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + err = os.Remove(globalConfig.Filename) + if err != nil { + t.Fatal(err) + } + } + + err = DownloadObject(sess, &globalConfig.Filename, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Downloaded " + globalConfig.Filename + " from bucket " + globalConfig.Bucket) + + if createdBucket { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") + } + + t.Log("Deleted bucket " + globalConfig.Bucket) + } } diff --git a/go/s3/EncryptOnServerWithKms/EncryptOnServerWithKms.go b/go/s3/EncryptOnServerWithKms/EncryptOnServerWithKms.go index ac11f229222..03ae530751f 100644 --- a/go/s3/EncryptOnServerWithKms/EncryptOnServerWithKms.go +++ b/go/s3/EncryptOnServerWithKms/EncryptOnServerWithKms.go @@ -1,85 +1,79 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.encrypt_on_server_with_kms] package main // snippet-start:[s3.go.encrypt_on_server_with_kms.imports] import ( - "flag" - "fmt" - "strings" + "flag" + "fmt" + "strings" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.encrypt_on_server_with_kms.imports] // AddObjectWithServerKms adds an object to a bucket with encryption based on a KMS key // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket -// object is the name of the object to upload to the bucket -// kmsKey is the KMS key used to encrypt the object in the bucket +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// object is the name of the object to upload to the bucket +// kmsKey is the KMS key used to encrypt the object in the bucket +// // Output: -// If success, nil -// Otherwise, an error from the call to PutObject +// +// If success, nil +// Otherwise, an error from the call to PutObject func AddObjectWithServerKms(sess *session.Session, bucket, object, kmsKey *string) error { - // snippet-start:[s3.go.encrypt_on_server_with_kms.call] - svc := s3.New(sess) + // snippet-start:[s3.go.encrypt_on_server_with_kms.call] + svc := s3.New(sess) - _, err := svc.PutObject(&s3.PutObjectInput{ - Body: strings.NewReader(*object), - Bucket: bucket, - Key: object, - ServerSideEncryption: aws.String("aws:kms"), - SSEKMSKeyId: kmsKey, - }) - // snippet-end:[s3.go.encrypt_on_server_with_kms.call] - if err != nil { - return err - } + _, err := svc.PutObject(&s3.PutObjectInput{ + Body: strings.NewReader(*object), + Bucket: bucket, + Key: object, + ServerSideEncryption: aws.String("aws:kms"), + SSEKMSKeyId: kmsKey, + }) + // snippet-end:[s3.go.encrypt_on_server_with_kms.call] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[s3.go.encrypt_on_server_with_kms.args] - bucket := flag.String("b", "", "The bucket") - object := flag.String("o", "", "The file to upload") - kmsKey := flag.String("k", "", "The KMS key to encrypt with") - flag.Parse() + // snippet-start:[s3.go.encrypt_on_server_with_kms.args] + bucket := flag.String("b", "", "The bucket") + object := flag.String("o", "", "The file to upload") + kmsKey := flag.String("k", "", "The KMS key to encrypt with") + flag.Parse() - if *bucket == "" || *object == "" || *kmsKey == "" { - fmt.Println("You must supply a bucket (-b BUCKET), object to upload (-o OBJECT), and KMS key (-k KEY)") - return - } - // snippet-end:[s3.go.encrypt_on_server_with_kms.args] + if *bucket == "" || *object == "" || *kmsKey == "" { + fmt.Println("You must supply a bucket (-b BUCKET), object to upload (-o OBJECT), and KMS key (-k KEY)") + return + } + // snippet-end:[s3.go.encrypt_on_server_with_kms.args] - // snippet-start:[s3.go.encrypt_on_server_with_kms.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.encrypt_on_server_with_kms.session] + // snippet-start:[s3.go.encrypt_on_server_with_kms.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.encrypt_on_server_with_kms.session] - err := AddObjectWithServerKms(sess, bucket, object, kmsKey) - if err != nil { - fmt.Println("Got an error adding object to bucket:") - fmt.Println(err) - return - } + err := AddObjectWithServerKms(sess, bucket, object, kmsKey) + if err != nil { + fmt.Println("Got an error adding object to bucket:") + fmt.Println(err) + return + } - fmt.Println("Added object " + *object + " to bucket " + *bucket + " with AWS KMS encryption") + fmt.Println("Added object " + *object + " to bucket " + *bucket + " with AWS KMS encryption") } + // snippet-end:[s3.go.encrypt_on_server_with_kms] diff --git a/go/s3/EncryptOnServerWithKms/EncryptOnServerWithKms_test.go b/go/s3/EncryptOnServerWithKms/EncryptOnServerWithKms_test.go index f50ad4ed141..18047aba9fd 100644 --- a/go/s3/EncryptOnServerWithKms/EncryptOnServerWithKms_test.go +++ b/go/s3/EncryptOnServerWithKms/EncryptOnServerWithKms_test.go @@ -1,38 +1,27 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - - "github.com/google/uuid" + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` - Object string `json:"Object"` - KmsKey string `json:"KmsKey"` + Bucket string `json:"Bucket"` + Object string `json:"Object"` + KmsKey string `json:"KmsKey"` } var configFileName = "config.json" @@ -40,121 +29,121 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) - t.Log("Object: " + globalConfig.Object) - t.Log("KmsKey: " + globalConfig.KmsKey) + t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Object: " + globalConfig.Object) + t.Log("KmsKey: " + globalConfig.KmsKey) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucket, - }) - - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - if err != nil { - return err - } - - _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucket, + }) + + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + if err != nil { + return err + } + + _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestEncryptOnServerWithKms(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - if globalConfig.KmsKey == "" { - t.Fatal(errors.New("You must supply a KMS key in config.json")) - } - - bucketCreated := false - - if globalConfig.Bucket == "" || globalConfig.Object == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - globalConfig.Object = "Test.txt" - - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Created " + globalConfig.Bucket) - bucketCreated = true - } - - err = AddObjectWithServerKms(sess, &globalConfig.Bucket, &globalConfig.Object, &globalConfig.KmsKey) - if err != nil { - t.Fatal(err) - } - - fmt.Println("Added object " + globalConfig.Object + " to bucket " + globalConfig.Bucket + " with AWS KMS encryption") - - if bucketCreated { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Deleted " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + if globalConfig.KmsKey == "" { + t.Fatal(errors.New("You must supply a KMS key in config.json")) + } + + bucketCreated := false + + if globalConfig.Bucket == "" || globalConfig.Object == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + globalConfig.Object = "Test.txt" + + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Created " + globalConfig.Bucket) + bucketCreated = true + } + + err = AddObjectWithServerKms(sess, &globalConfig.Bucket, &globalConfig.Object, &globalConfig.KmsKey) + if err != nil { + t.Fatal(err) + } + + fmt.Println("Added object " + globalConfig.Object + " to bucket " + globalConfig.Bucket + " with AWS KMS encryption") + + if bucketCreated { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Deleted " + globalConfig.Bucket) + } } diff --git a/go/s3/EnforceMD5/EnforceMD5Content.go b/go/s3/EnforceMD5/EnforceMD5Content.go index f92265d27cb..052e3ab9b9e 100644 --- a/go/s3/EnforceMD5/EnforceMD5Content.go +++ b/go/s3/EnforceMD5/EnforceMD5Content.go @@ -1,112 +1,106 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.enforce_md5] package main // snippet-start:[s3.go.enforce_md5.imports] import ( - "crypto/md5" - "encoding/base64" - "flag" - "fmt" - "net/http" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "crypto/md5" + "encoding/base64" + "flag" + "fmt" + "net/http" + "strings" + "time" + + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.enforce_md5.imports] // SetMd5 enforces an MD5 checksum on the object uploaded to a bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket -// key is the key of the object +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// key is the key of the object +// // Output: -// If success, an HTTP response object and nil -// Otherwise, nil and an error from the call to PutObjectRequest +// +// If success, an HTTP response object and nil +// Otherwise, nil and an error from the call to PutObjectRequest func SetMd5(sess *session.Session, bucket, key *string) (*http.Response, error) { - // snippet-start:[s3.go.enforce_md5.client_md5] - svc := s3.New(sess) - - h := md5.New() - content := strings.NewReader("") - _, err := content.WriteTo(h) - // snippet-end:[s3.go.enforce_md5.client_md5] - if err != nil { - return nil, err - } - - // snippet-start:[s3.go.enforce_md5.put_object] - resp, _ := svc.PutObjectRequest(&s3.PutObjectInput{ - Bucket: bucket, - Key: key, - }) - - md5s := base64.StdEncoding.EncodeToString(h.Sum(nil)) - resp.HTTPRequest.Header.Set("Content-MD5", md5s) - - url, err := resp.Presign(15 * time.Minute) - // snippet-end:[s3.go.enforce_md5.put_object] - if err != nil { - return nil, err - } - - // snippet-start:[s3.go.enforce_md5.new_request] - req, err := http.NewRequest("PUT", url, strings.NewReader("")) - req.Header.Set("Content-MD5", md5s) - // snippet-end:[s3.go.enforce_md5.new_request] - if err != nil { - return nil, err - } - - // snippet-start:[s3.go.enforce_md5.default_client] - defClient, err := http.DefaultClient.Do(req) - // snippet-end:[s3.go.enforce_md5.default_client] - if err != nil { - return nil, err - } - - return defClient, nil + // snippet-start:[s3.go.enforce_md5.client_md5] + svc := s3.New(sess) + + h := md5.New() + content := strings.NewReader("") + _, err := content.WriteTo(h) + // snippet-end:[s3.go.enforce_md5.client_md5] + if err != nil { + return nil, err + } + + // snippet-start:[s3.go.enforce_md5.put_object] + resp, _ := svc.PutObjectRequest(&s3.PutObjectInput{ + Bucket: bucket, + Key: key, + }) + + md5s := base64.StdEncoding.EncodeToString(h.Sum(nil)) + resp.HTTPRequest.Header.Set("Content-MD5", md5s) + + url, err := resp.Presign(15 * time.Minute) + // snippet-end:[s3.go.enforce_md5.put_object] + if err != nil { + return nil, err + } + + // snippet-start:[s3.go.enforce_md5.new_request] + req, err := http.NewRequest("PUT", url, strings.NewReader("")) + req.Header.Set("Content-MD5", md5s) + // snippet-end:[s3.go.enforce_md5.new_request] + if err != nil { + return nil, err + } + + // snippet-start:[s3.go.enforce_md5.default_client] + defClient, err := http.DefaultClient.Do(req) + // snippet-end:[s3.go.enforce_md5.default_client] + if err != nil { + return nil, err + } + + return defClient, nil } func main() { - // snippet-start:[s3.go.enforce_md5.args] - bucket := flag.String("b", "", "The name of the bucket") - key := flag.String("k", "", "The object key") - flag.Parse() - - if *bucket == "" || *key == "" { - fmt.Println("You must supply a bucket name (-b BUCKET) and key name (-k KEY)") - return - } - // snippet-end:[s3.go.enforce_md5.args] - - // snippet-start:[s3.go.enforce_md5.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.enforce_md5.session] - - defClient, err := SetMd5(sess, bucket, key) - if err != nil { - fmt.Println("Got an error setting MD5:") - fmt.Println(err) - return - } - - fmt.Println(defClient, err) + // snippet-start:[s3.go.enforce_md5.args] + bucket := flag.String("b", "", "The name of the bucket") + key := flag.String("k", "", "The object key") + flag.Parse() + + if *bucket == "" || *key == "" { + fmt.Println("You must supply a bucket name (-b BUCKET) and key name (-k KEY)") + return + } + // snippet-end:[s3.go.enforce_md5.args] + + // snippet-start:[s3.go.enforce_md5.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.enforce_md5.session] + + defClient, err := SetMd5(sess, bucket, key) + if err != nil { + fmt.Println("Got an error setting MD5:") + fmt.Println(err) + return + } + + fmt.Println(defClient, err) } + // snippet-end:[s3.go.enforce_md5] diff --git a/go/s3/EnforceMD5/EnforceMD5Content_test.go b/go/s3/EnforceMD5/EnforceMD5Content_test.go index b76241a7cda..25504197c08 100644 --- a/go/s3/EnforceMD5/EnforceMD5Content_test.go +++ b/go/s3/EnforceMD5/EnforceMD5Content_test.go @@ -1,33 +1,22 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "testing" - "time" + "encoding/json" + "io/ioutil" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" - "github.com/google/uuid" + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` - Key string `json:"Key"` + Bucket string `json:"Bucket"` + Key string `json:"Key"` } var configFileName = "config.json" @@ -35,108 +24,108 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) - t.Log("Key: " + globalConfig.Key) + t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Key: " + globalConfig.Key) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestEnforceMD5Content(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - bucketCreated := false - - if globalConfig.Bucket == "" || globalConfig.Key == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - globalConfig.Key = "test-key.txt" - - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Created bucket " + globalConfig.Bucket) - } - - defClient, err := SetMd5(sess, &globalConfig.Bucket, &globalConfig.Key) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log(defClient, err) - - if bucketCreated { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + bucketCreated := false + + if globalConfig.Bucket == "" || globalConfig.Key == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + globalConfig.Key = "test-key.txt" + + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Created bucket " + globalConfig.Bucket) + } + + defClient, err := SetMd5(sess, &globalConfig.Bucket, &globalConfig.Key) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log(defClient, err) + + if bucketCreated { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted " + globalConfig.Bucket) + } } diff --git a/go/s3/GeneratePresignedURL/GeneratePresignedURL.go b/go/s3/GeneratePresignedURL/GeneratePresignedURL.go index 7c74b49ec21..caf70abcdee 100644 --- a/go/s3/GeneratePresignedURL/GeneratePresignedURL.go +++ b/go/s3/GeneratePresignedURL/GeneratePresignedURL.go @@ -1,82 +1,76 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.generate_presigned_url] package main // snippet-start:[s3.go.generate_presigned_url.imports] import ( - "flag" - "fmt" - "time" + "flag" + "fmt" + "time" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.generate_presigned_url.imports] // GetPresignedURL creates a presigned URL for a bucket object // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket -// key is the key of the object +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// key is the key of the object +// // Output: -// If success, the presigned URL, which is valid for 15 minutes, for the object and nil -// Otherwise, an empty string and an error from the call to GetObjectRequest or Presign +// +// If success, the presigned URL, which is valid for 15 minutes, for the object and nil +// Otherwise, an empty string and an error from the call to GetObjectRequest or Presign func GetPresignedURL(sess *session.Session, bucket, key *string) (string, error) { - // snippet-start:[s3.go.generate_presigned_url.call] - svc := s3.New(sess) + // snippet-start:[s3.go.generate_presigned_url.call] + svc := s3.New(sess) - req, _ := svc.GetObjectRequest(&s3.GetObjectInput{ - Bucket: bucket, - Key: key, - }) - urlStr, err := req.Presign(15 * time.Minute) - // snippet-end:[s3.go.generate_presigned_url.call] - if err != nil { - return "", err - } + req, _ := svc.GetObjectRequest(&s3.GetObjectInput{ + Bucket: bucket, + Key: key, + }) + urlStr, err := req.Presign(15 * time.Minute) + // snippet-end:[s3.go.generate_presigned_url.call] + if err != nil { + return "", err + } - return urlStr, nil + return urlStr, nil } func main() { - // snippet-start:[s3.go.generate_presigned_url.args] - bucket := flag.String("b", "", "The bucket") - key := flag.String("k", "", "The object key") - flag.Parse() + // snippet-start:[s3.go.generate_presigned_url.args] + bucket := flag.String("b", "", "The bucket") + key := flag.String("k", "", "The object key") + flag.Parse() - if *bucket == "" || *key == "" { - fmt.Println("You must supply a bucket name (-b BUCKET) and object key (-k KEY)") - return - } - // snippet-end:[s3.go.generate_presigned_url.args] + if *bucket == "" || *key == "" { + fmt.Println("You must supply a bucket name (-b BUCKET) and object key (-k KEY)") + return + } + // snippet-end:[s3.go.generate_presigned_url.args] - // snippet-start:[s3.go.generate_presigned_url.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.generate_presigned_url.session] + // snippet-start:[s3.go.generate_presigned_url.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.generate_presigned_url.session] - urlStr, err := GetPresignedURL(sess, bucket, key) - if err != nil { - fmt.Println("Got an error retrieving a presigned URL:") - fmt.Println(err) - return - } + urlStr, err := GetPresignedURL(sess, bucket, key) + if err != nil { + fmt.Println("Got an error retrieving a presigned URL:") + fmt.Println(err) + return + } - // snippet-start:[s3.go.generate_presigned_url.print] - fmt.Println("The presigned URL: " + urlStr + " is valid for 15 minutes") - // snippet-end:[s3.go.generate_presigned_url.print] + // snippet-start:[s3.go.generate_presigned_url.print] + fmt.Println("The presigned URL: " + urlStr + " is valid for 15 minutes") + // snippet-end:[s3.go.generate_presigned_url.print] } + // snippet-end:[s3.go.generate_presigned_url] diff --git a/go/s3/GeneratePresignedURL/GeneratePresignedURL_test.go b/go/s3/GeneratePresignedURL/GeneratePresignedURL_test.go index 1271ca34adb..c7303052ab1 100644 --- a/go/s3/GeneratePresignedURL/GeneratePresignedURL_test.go +++ b/go/s3/GeneratePresignedURL/GeneratePresignedURL_test.go @@ -1,35 +1,24 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "os" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - "github.com/google/uuid" + "encoding/json" + "io/ioutil" + "os" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` - Key string `json:"Key"` + Bucket string `json:"Bucket"` + Key string `json:"Key"` } var configFileName = "config.json" @@ -37,146 +26,146 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) - t.Log("Key: " + globalConfig.Key) + t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Key: " + globalConfig.Key) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func uploadFile(sess *session.Session, bucket, key *string) error { - file, err := os.Open(*key) - if err != nil { - return err - } - - defer file.Close() - - uploader := s3manager.NewUploader(sess) - _, err = uploader.Upload(&s3manager.UploadInput{ - Bucket: bucket, - Key: key, - Body: file, - }) - if err != nil { - return err - } - - return nil + file, err := os.Open(*key) + if err != nil { + return err + } + + defer file.Close() + + uploader := s3manager.NewUploader(sess) + _, err = uploader.Upload(&s3manager.UploadInput{ + Bucket: bucket, + Key: key, + Body: file, + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucket, - }) - - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - if err != nil { - return err - } - - _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucket, + }) + + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + if err != nil { + return err + } + + _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestGeneratePresignedURL(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - bucketCreated := false - - if globalConfig.Bucket == "" || globalConfig.Key == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - globalConfig.Key = "test.txt" - - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Created " + globalConfig.Bucket) - - err = uploadFile(sess, &globalConfig.Bucket, &globalConfig.Key) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Created " + globalConfig.Bucket) - bucketCreated = true - } - - urlStr, err := GetPresignedURL(sess, &globalConfig.Bucket, &globalConfig.Key) - if err != nil { - t.Fatal(err) - } - - t.Log("The presigned URL: " + urlStr + " is valid for 15 minutes") - - if bucketCreated { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + bucketCreated := false + + if globalConfig.Bucket == "" || globalConfig.Key == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + globalConfig.Key = "test.txt" + + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Created " + globalConfig.Bucket) + + err = uploadFile(sess, &globalConfig.Bucket, &globalConfig.Key) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Created " + globalConfig.Bucket) + bucketCreated = true + } + + urlStr, err := GetPresignedURL(sess, &globalConfig.Bucket, &globalConfig.Key) + if err != nil { + t.Fatal(err) + } + + t.Log("The presigned URL: " + urlStr + " is valid for 15 minutes") + + if bucketCreated { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted " + globalConfig.Bucket) + } } diff --git a/go/s3/GeneratePresignedURLSpecificPayload/GeneratePresignedURLSpecificPayload.go b/go/s3/GeneratePresignedURLSpecificPayload/GeneratePresignedURLSpecificPayload.go index 4fca62eef7c..acad1e78409 100644 --- a/go/s3/GeneratePresignedURLSpecificPayload/GeneratePresignedURLSpecificPayload.go +++ b/go/s3/GeneratePresignedURLSpecificPayload/GeneratePresignedURLSpecificPayload.go @@ -1,84 +1,78 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.generate_presigned_url_specific_payload] package main // snippet-start:[s3.go.generate_presigned_url_specific_payload.imports] import ( - "flag" - "fmt" - "strings" - "time" + "flag" + "fmt" + "strings" + "time" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.generate_presigned_url_specific_payload.imports] // GetPresignedURL creates a presigned URL for a bucket object // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket -// key is the key of the object -// content is the content of the object +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// key is the key of the object +// content is the content of the object +// // Output: -// If success, the presigned URL, which is valid for 15 minutes, for the object and nil -// Otherwise, an empty string and an error from the call to GetObjectRequest or Presign +// +// If success, the presigned URL, which is valid for 15 minutes, for the object and nil +// Otherwise, an empty string and an error from the call to GetObjectRequest or Presign func GetPresignedURL(sess *session.Session, bucket, key, content *string) (string, error) { - // snippet-start:[s3.go.generate_presigned_url_specific_payload.call] - svc := s3.New(sess) + // snippet-start:[s3.go.generate_presigned_url_specific_payload.call] + svc := s3.New(sess) - req, _ := svc.PutObjectRequest(&s3.PutObjectInput{ - Bucket: bucket, - Key: key, - Body: strings.NewReader(*content), - }) - str, err := req.Presign(15 * time.Minute) - // snippet-end:[s3.go.generate_presigned_url_specific_payload.call] - if err != nil { - return "", err - } + req, _ := svc.PutObjectRequest(&s3.PutObjectInput{ + Bucket: bucket, + Key: key, + Body: strings.NewReader(*content), + }) + str, err := req.Presign(15 * time.Minute) + // snippet-end:[s3.go.generate_presigned_url_specific_payload.call] + if err != nil { + return "", err + } - return str, nil + return str, nil } func main() { - // snippet-start:[s3.go.generate_presigned_url_specific_payload.args] - bucket := flag.String("b", "", "The bucket") - key := flag.String("k", "", "The object key") - content := flag.String("c", "", "The content of the object") - flag.Parse() + // snippet-start:[s3.go.generate_presigned_url_specific_payload.args] + bucket := flag.String("b", "", "The bucket") + key := flag.String("k", "", "The object key") + content := flag.String("c", "", "The content of the object") + flag.Parse() - if *bucket == "" || *key == "" || *content == "" { - fmt.Println("You must supply a bucket (-b BUCKET), key (-k KEY), and content (-c CONTENT)") - return - } - // snippet-end:[s3.go.generate_presigned_url_specific_payload.args] + if *bucket == "" || *key == "" || *content == "" { + fmt.Println("You must supply a bucket (-b BUCKET), key (-k KEY), and content (-c CONTENT)") + return + } + // snippet-end:[s3.go.generate_presigned_url_specific_payload.args] - // snippet-start:[s3.go.generate_presigned_url_specific_payload.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.generate_presigned_url_specific_payload.session] + // snippet-start:[s3.go.generate_presigned_url_specific_payload.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.generate_presigned_url_specific_payload.session] - str, err := GetPresignedURL(sess, bucket, key, content) - if err != nil { - fmt.Println("Got an error retrieving the presigned URL:") - fmt.Println(err) - return - } + str, err := GetPresignedURL(sess, bucket, key, content) + if err != nil { + fmt.Println("Got an error retrieving the presigned URL:") + fmt.Println(err) + return + } - fmt.Println("The URL is:", str) + fmt.Println("The URL is:", str) } + // snippet-end:[s3.go.generate_presigned_url_specific_payload] diff --git a/go/s3/GeneratePresignedURLSpecificPayload/GeneratePresignedURLSpecificPayload_test.go b/go/s3/GeneratePresignedURLSpecificPayload/GeneratePresignedURLSpecificPayload_test.go index 179008e4aae..88e491fa726 100644 --- a/go/s3/GeneratePresignedURLSpecificPayload/GeneratePresignedURLSpecificPayload_test.go +++ b/go/s3/GeneratePresignedURLSpecificPayload/GeneratePresignedURLSpecificPayload_test.go @@ -1,36 +1,25 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "os" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - "github.com/google/uuid" + "encoding/json" + "io/ioutil" + "os" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` - Key string `json:"Key"` - Content string `json:"Content"` + Bucket string `json:"Bucket"` + Key string `json:"Key"` + Content string `json:"Content"` } var configFileName = "config.json" @@ -38,148 +27,148 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) - t.Log("Key: " + globalConfig.Key) - t.Log("Content: " + globalConfig.Content) + t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Key: " + globalConfig.Key) + t.Log("Content: " + globalConfig.Content) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func uploadFile(sess *session.Session, bucket, key *string) error { - file, err := os.Open(*key) - if err != nil { - return err - } - - defer file.Close() - - uploader := s3manager.NewUploader(sess) - _, err = uploader.Upload(&s3manager.UploadInput{ - Bucket: bucket, - Key: key, - Body: file, - }) - if err != nil { - return err - } - - return nil + file, err := os.Open(*key) + if err != nil { + return err + } + + defer file.Close() + + uploader := s3manager.NewUploader(sess) + _, err = uploader.Upload(&s3manager.UploadInput{ + Bucket: bucket, + Key: key, + Body: file, + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucket, - }) - - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - if err != nil { - return err - } - - _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucket, + }) + + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + if err != nil { + return err + } + + _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestGeneratePresignedURL(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - bucketCreated := false - - if globalConfig.Bucket == "" || globalConfig.Key == "" || globalConfig.Content == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - globalConfig.Key = "test.txt" - globalConfig.Content = "This is a test" - - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Created " + globalConfig.Bucket) - - err = uploadFile(sess, &globalConfig.Bucket, &globalConfig.Key) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Created " + globalConfig.Bucket) - bucketCreated = true - } - - urlStr, err := GetPresignedURL(sess, &globalConfig.Bucket, &globalConfig.Key, &globalConfig.Content) - if err != nil { - t.Fatal(err) - } - - t.Log("The presigned URL: " + urlStr + " is valid for 15 minutes") - - if bucketCreated { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + bucketCreated := false + + if globalConfig.Bucket == "" || globalConfig.Key == "" || globalConfig.Content == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + globalConfig.Key = "test.txt" + globalConfig.Content = "This is a test" + + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Created " + globalConfig.Bucket) + + err = uploadFile(sess, &globalConfig.Bucket, &globalConfig.Key) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Created " + globalConfig.Bucket) + bucketCreated = true + } + + urlStr, err := GetPresignedURL(sess, &globalConfig.Bucket, &globalConfig.Key, &globalConfig.Content) + if err != nil { + t.Fatal(err) + } + + t.Log("The presigned URL: " + urlStr + " is valid for 15 minutes") + + if bucketCreated { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted " + globalConfig.Bucket) + } } diff --git a/go/s3/GetBucketAcl/GetBucketAcl.go b/go/s3/GetBucketAcl/GetBucketAcl.go index 6b332dcc57d..5491b7b6c5e 100644 --- a/go/s3/GetBucketAcl/GetBucketAcl.go +++ b/go/s3/GetBucketAcl/GetBucketAcl.go @@ -1,90 +1,84 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.get_bucket_acl] package main // snippet-start:[s3.go.get_bucket_acl.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.get_bucket_acl.imports] // GetBucketACL gets the ACL for a bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// // Output: -// If success, nil -// Otherwise, an error from the call to GetBucketAcl +// +// If success, nil +// Otherwise, an error from the call to GetBucketAcl func GetBucketACL(sess *session.Session, bucket *string) (*s3.GetBucketAclOutput, error) { - // snippet-start:[s3.go.get_bucket_acl.call] - svc := s3.New(sess) + // snippet-start:[s3.go.get_bucket_acl.call] + svc := s3.New(sess) - result, err := svc.GetBucketAcl(&s3.GetBucketAclInput{ - Bucket: bucket, - }) - // snippet-end:[s3.go.get_bucket_acl.call] - if err != nil { - return nil, err - } + result, err := svc.GetBucketAcl(&s3.GetBucketAclInput{ + Bucket: bucket, + }) + // snippet-end:[s3.go.get_bucket_acl.call] + if err != nil { + return nil, err + } - return result, nil + return result, nil } func main() { - // snippet-start:[s3.go.get_bucket_acl.args] - bucket := flag.String("b", "", "The bucket for which the ACL is returned") - flag.Parse() + // snippet-start:[s3.go.get_bucket_acl.args] + bucket := flag.String("b", "", "The bucket for which the ACL is returned") + flag.Parse() - if *bucket == "" { - fmt.Println("You must supply a bucket name (-b BUCKET)") - return - } - // snippet-end:[s3.go.get_bucket_acl.args] + if *bucket == "" { + fmt.Println("You must supply a bucket name (-b BUCKET)") + return + } + // snippet-end:[s3.go.get_bucket_acl.args] - // snippet-start:[s3.go.get_bucket_acl.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.get_bucket_acl.session] + // snippet-start:[s3.go.get_bucket_acl.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.get_bucket_acl.session] - result, err := GetBucketACL(sess, bucket) - if err != nil { - fmt.Println("Got an error retrieving ACL for " + *bucket) - } + result, err := GetBucketACL(sess, bucket) + if err != nil { + fmt.Println("Got an error retrieving ACL for " + *bucket) + } - // snippet-start:[s3.go.get_bucket_acl.print] - fmt.Println("Owner:", *result.Owner.DisplayName) - fmt.Println("") - fmt.Println("Grants") + // snippet-start:[s3.go.get_bucket_acl.print] + fmt.Println("Owner:", *result.Owner.DisplayName) + fmt.Println("") + fmt.Println("Grants") - for _, g := range result.Grants { - // If we add a canned ACL, the name is nil - if g.Grantee.DisplayName == nil { - fmt.Println(" Grantee: EVERYONE") - } else { - fmt.Println(" Grantee: ", *g.Grantee.DisplayName) - } + for _, g := range result.Grants { + // If we add a canned ACL, the name is nil + if g.Grantee.DisplayName == nil { + fmt.Println(" Grantee: EVERYONE") + } else { + fmt.Println(" Grantee: ", *g.Grantee.DisplayName) + } - fmt.Println(" Type: ", *g.Grantee.Type) - fmt.Println(" Permission:", *g.Permission) - fmt.Println("") - } - // snippet-end:[s3.go.get_bucket_acl.print] + fmt.Println(" Type: ", *g.Grantee.Type) + fmt.Println(" Permission:", *g.Permission) + fmt.Println("") + } + // snippet-end:[s3.go.get_bucket_acl.print] } + // snippet-end:[s3.go.get_bucket_acl] diff --git a/go/s3/GetBucketAcl/GetBucketAcl_test.go b/go/s3/GetBucketAcl/GetBucketAcl_test.go index 06c33a9b962..cb3578dd725 100644 --- a/go/s3/GetBucketAcl/GetBucketAcl_test.go +++ b/go/s3/GetBucketAcl/GetBucketAcl_test.go @@ -1,33 +1,22 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "fmt" - "io/ioutil" - "testing" - "time" + "encoding/json" + "fmt" + "io/ioutil" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" - "github.com/google/uuid" + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` + Bucket string `json:"Bucket"` } var configFileName = "config.json" @@ -35,121 +24,121 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Bucket: " + globalConfig.Bucket) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestPutBucketAcl(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - bucketCreated := false - - if globalConfig.Bucket == "" { - // Create the resources - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - bucketCreated = true - t.Log("Created bucket " + globalConfig.Bucket) - } - - result, err := GetBucketACL(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - fmt.Println("Owner:", *result.Owner.DisplayName) - fmt.Println("") - fmt.Println("Grants") - - for _, g := range result.Grants { - // If we add a canned ACL, the name is nil - if g.Grantee.DisplayName == nil { - t.Log(" Grantee: EVERYONE") - } else { - t.Log(" Grantee: ", *g.Grantee.DisplayName) - } - - t.Log(" Type: ", *g.Grantee.Type) - t.Log(" Permission:", *g.Permission) - } - - if bucketCreated { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted bucket " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + bucketCreated := false + + if globalConfig.Bucket == "" { + // Create the resources + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + bucketCreated = true + t.Log("Created bucket " + globalConfig.Bucket) + } + + result, err := GetBucketACL(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + fmt.Println("Owner:", *result.Owner.DisplayName) + fmt.Println("") + fmt.Println("Grants") + + for _, g := range result.Grants { + // If we add a canned ACL, the name is nil + if g.Grantee.DisplayName == nil { + t.Log(" Grantee: EVERYONE") + } else { + t.Log(" Grantee: ", *g.Grantee.DisplayName) + } + + t.Log(" Type: ", *g.Grantee.Type) + t.Log(" Permission:", *g.Permission) + } + + if bucketCreated { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted bucket " + globalConfig.Bucket) + } } diff --git a/go/s3/GetBucketPolicy/GetBucketPolicy.go b/go/s3/GetBucketPolicy/GetBucketPolicy.go index bda9422cbcb..53021ab9cfe 100644 --- a/go/s3/GetBucketPolicy/GetBucketPolicy.go +++ b/go/s3/GetBucketPolicy/GetBucketPolicy.go @@ -1,91 +1,85 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.get_bucket_policy] package main // snippet-start:[s3.go.get_bucket_policy.imports] import ( - "bytes" - "encoding/json" - "flag" - "fmt" + "bytes" + "encoding/json" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.get_bucket_policy.imports] // RetrieveBucketPolicy retrieves the policy for a bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// // Output: -// If success, a byte array containing the policy and nil -// Otherwise, an empty byte array and an error from the call to GetBucketPolicy +// +// If success, a byte array containing the policy and nil +// Otherwise, an empty byte array and an error from the call to GetBucketPolicy func RetrieveBucketPolicy(sess *session.Session, bucket *string) (bytes.Buffer, error) { - var dummy bytes.Buffer - // snippet-start:[s3.go.get_bucket_policy.call] - svc := s3.New(sess) + var dummy bytes.Buffer + // snippet-start:[s3.go.get_bucket_policy.call] + svc := s3.New(sess) - result, err := svc.GetBucketPolicy(&s3.GetBucketPolicyInput{ - Bucket: bucket, - }) - // snippet-end:[s3.go.get_bucket_policy.call] - if err != nil { - return dummy, err - } + result, err := svc.GetBucketPolicy(&s3.GetBucketPolicyInput{ + Bucket: bucket, + }) + // snippet-end:[s3.go.get_bucket_policy.call] + if err != nil { + return dummy, err + } - // snippet-start:[s3.go.get_bucket_policy.string] - out := bytes.Buffer{} - policyPtr := aws.StringValue(result.Policy) - err = json.Indent(&out, []byte(policyPtr), "", " ") - // snippet-end:[s3.go.get_bucket_policy.string] - if err != nil { - return bytes.Buffer{}, err - } + // snippet-start:[s3.go.get_bucket_policy.string] + out := bytes.Buffer{} + policyPtr := aws.StringValue(result.Policy) + err = json.Indent(&out, []byte(policyPtr), "", " ") + // snippet-end:[s3.go.get_bucket_policy.string] + if err != nil { + return bytes.Buffer{}, err + } - return out, nil + return out, nil } func main() { - // snippet-start:[s3.go.get_bucket_policy.args] - bucket := flag.String("b", "", "The name of the bucket") - flag.Parse() + // snippet-start:[s3.go.get_bucket_policy.args] + bucket := flag.String("b", "", "The name of the bucket") + flag.Parse() - if *bucket == "" { - fmt.Println("You must supply a bucket name (-b BUCKET)") - return - } - // snippet-end:[s3.go.get_bucket_policy.args] + if *bucket == "" { + fmt.Println("You must supply a bucket name (-b BUCKET)") + return + } + // snippet-end:[s3.go.get_bucket_policy.args] - // snippet-start:[s3.go.get_bucket_policy.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.get_bucket_policy.session] + // snippet-start:[s3.go.get_bucket_policy.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.get_bucket_policy.session] - out, err := RetrieveBucketPolicy(sess, bucket) - if err != nil { - fmt.Println("Got an error retrieving bucket policy:") - fmt.Println(err) - return - } + out, err := RetrieveBucketPolicy(sess, bucket) + if err != nil { + fmt.Println("Got an error retrieving bucket policy:") + fmt.Println(err) + return + } - // snippet-start:[s3.go.get_bucket_policy.print] - fmt.Println("Policy:") - fmt.Println(out.String()) - // snippet-end:[s3.go.get_bucket_policy.print] + // snippet-start:[s3.go.get_bucket_policy.print] + fmt.Println("Policy:") + fmt.Println(out.String()) + // snippet-end:[s3.go.get_bucket_policy.print] } + // snippet-end:[s3.go.get_bucket_policy] diff --git a/go/s3/GetBucketPolicy/GetBucketPolicy_test.go b/go/s3/GetBucketPolicy/GetBucketPolicy_test.go index 292e298e34b..d0ffcac5813 100644 --- a/go/s3/GetBucketPolicy/GetBucketPolicy_test.go +++ b/go/s3/GetBucketPolicy/GetBucketPolicy_test.go @@ -1,34 +1,23 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "fmt" - "io/ioutil" - "testing" - "time" + "encoding/json" + "fmt" + "io/ioutil" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" - "github.com/google/uuid" + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` + Bucket string `json:"Bucket"` } var configFileName = "config.json" @@ -36,151 +25,151 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Bucket: " + globalConfig.Bucket) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func addBucketPolity(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - readOnlyAnonUserPolicy := map[string]interface{}{ - "Version": "2012-10-17", - "Statement": []map[string]interface{}{ - { - "Sid": "AddPerm", - "Effect": "Allow", - "Principal": "*", - "Action": []string{ - "s3:GetObject", - }, - "Resource": []string{ - "arn:aws:s3:::" + *bucket + "/*", - }, - }, - }, - } - - policy, err := json.Marshal(readOnlyAnonUserPolicy) - if err != nil { - return err - } - - _, err = svc.PutBucketPolicy(&s3.PutBucketPolicyInput{ - Bucket: bucket, - Policy: aws.String(string(policy)), - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + readOnlyAnonUserPolicy := map[string]interface{}{ + "Version": "2012-10-17", + "Statement": []map[string]interface{}{ + { + "Sid": "AddPerm", + "Effect": "Allow", + "Principal": "*", + "Action": []string{ + "s3:GetObject", + }, + "Resource": []string{ + "arn:aws:s3:::" + *bucket + "/*", + }, + }, + }, + } + + policy, err := json.Marshal(readOnlyAnonUserPolicy) + if err != nil { + return err + } + + _, err = svc.PutBucketPolicy(&s3.PutBucketPolicyInput{ + Bucket: bucket, + Policy: aws.String(string(policy)), + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestGetBucketPolicy(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - bucketCreated := false - - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - fmt.Println("Created bucket " + globalConfig.Bucket) - bucketCreated = true - } - - err = addBucketPolity(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - out, err := RetrieveBucketPolicy(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Policy:") - t.Log(out.String()) - - if bucketCreated { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted bucket " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + bucketCreated := false + + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + fmt.Println("Created bucket " + globalConfig.Bucket) + bucketCreated = true + } + + err = addBucketPolity(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + out, err := RetrieveBucketPolicy(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Policy:") + t.Log(out.String()) + + if bucketCreated { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted bucket " + globalConfig.Bucket) + } } diff --git a/go/s3/GetBucketWebsite/GetBucketWebsite.go b/go/s3/GetBucketWebsite/GetBucketWebsite.go index 9dee93fc895..fb0bdf21b15 100644 --- a/go/s3/GetBucketWebsite/GetBucketWebsite.go +++ b/go/s3/GetBucketWebsite/GetBucketWebsite.go @@ -1,81 +1,72 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.get_bucket_website] package main // snippet-start:[s3.go.get_bucket_website.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.get_bucket_website.imports] // RetrieveWebSite retrieves the bucket's website configuration. func RetrieveWebSite(sess *session.Session, bucket *string) (*s3.GetBucketWebsiteOutput, error) { - // snippet-start:[s3.go.get_bucket_website.call] - svc := s3.New(sess) + // snippet-start:[s3.go.get_bucket_website.call] + svc := s3.New(sess) - result, err := svc.GetBucketWebsite(&s3.GetBucketWebsiteInput{ - Bucket: bucket, - }) - // snippet-end:[s3.go.get_bucket_website.call] - if err != nil { - return nil, err - } + result, err := svc.GetBucketWebsite(&s3.GetBucketWebsiteInput{ + Bucket: bucket, + }) + // snippet-end:[s3.go.get_bucket_website.call] + if err != nil { + return nil, err + } - return result, nil + return result, nil } func main() { - // snippet-start:[s3.go.get_bucket_website.args] - bucket := flag.String("b", "", "The name of the bucket") - flag.Parse() + // snippet-start:[s3.go.get_bucket_website.args] + bucket := flag.String("b", "", "The name of the bucket") + flag.Parse() - if *bucket == "" { - fmt.Println("You must supply the name of a bucket (-b BUCKET") - return - } - // snippet-end:[s3.go.get_bucket_website.args] + if *bucket == "" { + fmt.Println("You must supply the name of a bucket (-b BUCKET") + return + } + // snippet-end:[s3.go.get_bucket_website.args] - // snippet-start:[s3.go.get_bucket_website.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.get_bucket_website.session] + // snippet-start:[s3.go.get_bucket_website.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.get_bucket_website.session] - result, err := RetrieveWebSite(sess, bucket) - // snippet-start:[s3.go.get_bucket_website.error] - if err != nil { - awsErr, ok := err.(awserr.Error) - if ok && awsErr.Code() == "NoSuchWebsiteConfiguration" { - fmt.Println("Bucket does not have a website configuration") - } else { - fmt.Println("Got error retrieving bucket website configuration:") - fmt.Println(err) - } + result, err := RetrieveWebSite(sess, bucket) + // snippet-start:[s3.go.get_bucket_website.error] + if err != nil { + awsErr, ok := err.(awserr.Error) + if ok && awsErr.Code() == "NoSuchWebsiteConfiguration" { + fmt.Println("Bucket does not have a website configuration") + } else { + fmt.Println("Got error retrieving bucket website configuration:") + fmt.Println(err) + } - return - } - // snippet-end:[s3.go.get_bucket_website.error] + return + } + // snippet-end:[s3.go.get_bucket_website.error] - // snippet-start:[s3.go.get_bucket_website.print] - fmt.Println("Website Configuration:") - fmt.Println(result) - // snippet-end:[s3.go.get_bucket_website.print] + // snippet-start:[s3.go.get_bucket_website.print] + fmt.Println("Website Configuration:") + fmt.Println(result) + // snippet-end:[s3.go.get_bucket_website.print] } + // snippet-end:[s3.go.get_bucket_website] diff --git a/go/s3/GetBucketWebsite/GetBucketWebsite_test.go b/go/s3/GetBucketWebsite/GetBucketWebsite_test.go index 6343dfd8921..d423655313d 100644 --- a/go/s3/GetBucketWebsite/GetBucketWebsite_test.go +++ b/go/s3/GetBucketWebsite/GetBucketWebsite_test.go @@ -1,35 +1,24 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "strings" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - "github.com/google/uuid" + "encoding/json" + "io/ioutil" + "strings" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` + Bucket string `json:"Bucket"` } var configFileName = "config.json" @@ -37,205 +26,205 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Bucket: " + globalConfig.Bucket) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func createObject(sess *session.Session, bucket *string, key *string, content *string) error { - svc := s3.New(sess) - - _, err := svc.PutObject(&s3.PutObjectInput{ - Body: strings.NewReader(*content), - Bucket: bucket, - Key: key, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.PutObject(&s3.PutObjectInput{ + Body: strings.NewReader(*content), + Bucket: bucket, + Key: key, + }) + if err != nil { + return err + } + + return nil } func setWebPage(sess *session.Session, bucket, indexPage, errorPage *string) error { - svc := s3.New(sess) - - params := s3.PutBucketWebsiteInput{ - Bucket: bucket, - WebsiteConfiguration: &s3.WebsiteConfiguration{ - IndexDocument: &s3.IndexDocument{ - Suffix: indexPage, - }, - }, - } - - if len(*errorPage) > 0 { - params.WebsiteConfiguration.ErrorDocument = &s3.ErrorDocument{ - Key: errorPage, - } - } - - _, err := svc.PutBucketWebsite(¶ms) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + params := s3.PutBucketWebsiteInput{ + Bucket: bucket, + WebsiteConfiguration: &s3.WebsiteConfiguration{ + IndexDocument: &s3.IndexDocument{ + Suffix: indexPage, + }, + }, + } + + if len(*errorPage) > 0 { + params.WebsiteConfiguration.ErrorDocument = &s3.ErrorDocument{ + Key: errorPage, + } + } + + _, err := svc.PutBucketWebsite(¶ms) + if err != nil { + return err + } + + return nil } func createBucketWebsite(sess *session.Session, bucket *string) error { - err := createBucket(sess, bucket) - if err != nil { - return err - } - - indexPage := "Index.html" - content := "

This is the index

" - err = createObject(sess, bucket, &indexPage, &content) - if err != nil { - return err - } - - errorPage := "Error.html" - content = "

ERROR!

" - err = createObject(sess, bucket, &errorPage, &content) - if err != nil { - return err - } - - err = setWebPage(sess, bucket, &indexPage, &errorPage) - if err != nil { - return err - } - - return nil + err := createBucket(sess, bucket) + if err != nil { + return err + } + + indexPage := "Index.html" + content := "

This is the index

" + err = createObject(sess, bucket, &indexPage, &content) + if err != nil { + return err + } + + errorPage := "Error.html" + content = "

ERROR!

" + err = createObject(sess, bucket, &errorPage, &content) + if err != nil { + return err + } + + err = setWebPage(sess, bucket, &indexPage, &errorPage) + if err != nil { + return err + } + + return nil } func clearBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucket, - }) + svc := s3.New(sess) + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucket, + }) - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - if err != nil { - return err - } + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + if err != nil { + return err + } - return nil + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestGetBucketWebsite(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - bucketCreated := false - - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - - err := createBucketWebsite(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Created bucket " + globalConfig.Bucket + " with static web site") - bucketCreated = true - } - - msg := "" - - result, err := RetrieveWebSite(sess, &globalConfig.Bucket) - if err != nil { - awsErr, ok := err.(awserr.Error) - if ok && awsErr.Code() == "NoSuchWebsiteConfiguration" { - msg = "Bucket does not have a website configuration" - } else { - msg = "Got error retrieving bucket website configuration" - } - - t.Fatal(msg) - } - - t.Log("Website Configuration:") - t.Log(result) - - if bucketCreated { - err := clearBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - err = deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted bucket " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + bucketCreated := false + + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + + err := createBucketWebsite(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Created bucket " + globalConfig.Bucket + " with static web site") + bucketCreated = true + } + + msg := "" + + result, err := RetrieveWebSite(sess, &globalConfig.Bucket) + if err != nil { + awsErr, ok := err.(awserr.Error) + if ok && awsErr.Code() == "NoSuchWebsiteConfiguration" { + msg = "Bucket does not have a website configuration" + } else { + msg = "Got error retrieving bucket website configuration" + } + + t.Fatal(msg) + } + + t.Log("Website Configuration:") + t.Log(result) + + if bucketCreated { + err := clearBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + err = deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted bucket " + globalConfig.Bucket) + } } diff --git a/go/s3/GetObjectAcl/GetObjectAcl.go b/go/s3/GetObjectAcl/GetObjectAcl.go index 3c2e8552c32..37e2c92f37c 100644 --- a/go/s3/GetObjectAcl/GetObjectAcl.go +++ b/go/s3/GetObjectAcl/GetObjectAcl.go @@ -1,87 +1,81 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.get_object_acl] package main // snippet-start:[s3.go.get_object_acl.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.get_object_acl.imports] // GetObjectACL gets the ACL for a bucket object // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket -// key is the name of the object +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// key is the name of the object +// // Output: -// If success, the ACL of the object and nil -// Otherwise, nil and an error from the call to GetObjectAcl +// +// If success, the ACL of the object and nil +// Otherwise, nil and an error from the call to GetObjectAcl func GetObjectACL(sess *session.Session, bucket, key *string) (*s3.GetObjectAclOutput, error) { - // snippet-start:[s3.go.get_object_acl.call] - svc := s3.New(sess) + // snippet-start:[s3.go.get_object_acl.call] + svc := s3.New(sess) - result, err := svc.GetObjectAcl(&s3.GetObjectAclInput{ - Bucket: bucket, - Key: key, - }) - // snippet-end:[s3.go.get_object_acl.call] - if err != nil { - return nil, err - } - return result, nil + result, err := svc.GetObjectAcl(&s3.GetObjectAclInput{ + Bucket: bucket, + Key: key, + }) + // snippet-end:[s3.go.get_object_acl.call] + if err != nil { + return nil, err + } + return result, nil } func main() { - // snippet-start:[s3.go.get_object_acl.args] - bucket := flag.String("b", "", "The bucket containing the object") - key := flag.String("k", "", "The bucket object to get ACL from") - flag.Parse() + // snippet-start:[s3.go.get_object_acl.args] + bucket := flag.String("b", "", "The bucket containing the object") + key := flag.String("k", "", "The bucket object to get ACL from") + flag.Parse() - if *bucket == "" || *key == "" { - fmt.Println("You must supply a bucket (-b BUCKET) and item key (-k ITEM)") - return - } - // snippet-end:[s3.go.get_object_acl.args] + if *bucket == "" || *key == "" { + fmt.Println("You must supply a bucket (-b BUCKET) and item key (-k ITEM)") + return + } + // snippet-end:[s3.go.get_object_acl.args] - // snippet-start:[s3.go.get_object_acl.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.get_object_acl.session] + // snippet-start:[s3.go.get_object_acl.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.get_object_acl.session] - result, err := GetObjectACL(sess, bucket, key) - if err != nil { - fmt.Println("Got an error getting ACL for " + *key) - return - } + result, err := GetObjectACL(sess, bucket, key) + if err != nil { + fmt.Println("Got an error getting ACL for " + *key) + return + } - // snippet-start:[s3.go.get_object_acl.print] - fmt.Println("Owner:", *result.Owner.DisplayName) - fmt.Println("") - fmt.Println("Grants") + // snippet-start:[s3.go.get_object_acl.print] + fmt.Println("Owner:", *result.Owner.DisplayName) + fmt.Println("") + fmt.Println("Grants") - for _, g := range result.Grants { - fmt.Println(" Grantee: ", *g.Grantee.DisplayName) - fmt.Println(" Type: ", *g.Grantee.Type) - fmt.Println(" Permission:", *g.Permission) - fmt.Println("") - } - // snippet-end:[s3.go.get_object_acl.print] + for _, g := range result.Grants { + fmt.Println(" Grantee: ", *g.Grantee.DisplayName) + fmt.Println(" Type: ", *g.Grantee.Type) + fmt.Println(" Permission:", *g.Permission) + fmt.Println("") + } + // snippet-end:[s3.go.get_object_acl.print] } + // snippet-end:[s3.go.get_object_acl] diff --git a/go/s3/GetObjectAcl/GetObjectAcl_test.go b/go/s3/GetObjectAcl/GetObjectAcl_test.go index 5068c92904b..5a8bc2bd067 100644 --- a/go/s3/GetObjectAcl/GetObjectAcl_test.go +++ b/go/s3/GetObjectAcl/GetObjectAcl_test.go @@ -1,35 +1,24 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "os" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - "github.com/google/uuid" + "encoding/json" + "io/ioutil" + "os" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` - Key string `json:"Key"` + Bucket string `json:"Bucket"` + Key string `json:"Key"` } var configFileName = "config.json" @@ -37,153 +26,153 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) - t.Log("Key: " + globalConfig.Key) + t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Key: " + globalConfig.Key) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func uploadFile(sess *session.Session, bucket, key *string) error { - file, err := os.Open(*key) - if err != nil { - return err - } - - defer file.Close() - - uploader := s3manager.NewUploader(sess) - _, err = uploader.Upload(&s3manager.UploadInput{ - Bucket: bucket, - Key: key, - Body: file, - }) - if err != nil { - return err - } - - return nil + file, err := os.Open(*key) + if err != nil { + return err + } + + defer file.Close() + + uploader := s3manager.NewUploader(sess) + _, err = uploader.Upload(&s3manager.UploadInput{ + Bucket: bucket, + Key: key, + Body: file, + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucket, - }) - - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - if err != nil { - return err - } - - _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucket, + }) + + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + if err != nil { + return err + } + + _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestGetObjectAcl(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - bucketCreated := false - - if globalConfig.Bucket == "" || globalConfig.Key == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - globalConfig.Key = "test.txt" - - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Created bucket " + globalConfig.Bucket) - - err = uploadFile(sess, &globalConfig.Bucket, &globalConfig.Key) - if err != nil { - t.Fatal(err) - } - - bucketCreated = true - t.Log("Uploaded " + globalConfig.Key + " to " + globalConfig.Bucket) - } - - result, err := GetObjectACL(sess, &globalConfig.Bucket, &globalConfig.Key) - if err != nil { - t.Fatal(err) - } - - t.Log("Owner:", *result.Owner.DisplayName) - t.Log("") - t.Log("Grants") - - for _, g := range result.Grants { - t.Log(" Grantee: ", *g.Grantee.DisplayName) - t.Log(" Type: ", *g.Grantee.Type) - t.Log(" Permission:", *g.Permission) - } - - if bucketCreated { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + bucketCreated := false + + if globalConfig.Bucket == "" || globalConfig.Key == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + globalConfig.Key = "test.txt" + + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Created bucket " + globalConfig.Bucket) + + err = uploadFile(sess, &globalConfig.Bucket, &globalConfig.Key) + if err != nil { + t.Fatal(err) + } + + bucketCreated = true + t.Log("Uploaded " + globalConfig.Key + " to " + globalConfig.Bucket) + } + + result, err := GetObjectACL(sess, &globalConfig.Bucket, &globalConfig.Key) + if err != nil { + t.Fatal(err) + } + + t.Log("Owner:", *result.Owner.DisplayName) + t.Log("") + t.Log("Grants") + + for _, g := range result.Grants { + t.Log(" Grantee: ", *g.Grantee.DisplayName) + t.Log(" Type: ", *g.Grantee.Type) + t.Log(" Permission:", *g.Permission) + } + + if bucketCreated { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted " + globalConfig.Bucket) + } } diff --git a/go/s3/ListBuckets/ListBuckets.go b/go/s3/ListBuckets/ListBuckets.go index caf60762e4a..183a8160730 100644 --- a/go/s3/ListBuckets/ListBuckets.go +++ b/go/s3/ListBuckets/ListBuckets.go @@ -1,67 +1,61 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.list_buckets] package main // snippet-start:[s3.go.list_buckets.imports] import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.list_buckets.imports] // GetAllBuckets retrieves a list of all buckets. // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients +// +// sess is the current session, which provides configuration for the SDK's service clients +// // Output: -// If success, the list of buckets and nil -// Otherwise, nil and an error from the call to ListBuckets +// +// If success, the list of buckets and nil +// Otherwise, nil and an error from the call to ListBuckets func GetAllBuckets(sess *session.Session) (*s3.ListBucketsOutput, error) { - // snippet-start:[s3.go.list_buckets.imports.call] - svc := s3.New(sess) + // snippet-start:[s3.go.list_buckets.imports.call] + svc := s3.New(sess) - result, err := svc.ListBuckets(&s3.ListBucketsInput{}) - // snippet-end:[s3.go.list_buckets.imports.call] - if err != nil { - return nil, err - } + result, err := svc.ListBuckets(&s3.ListBucketsInput{}) + // snippet-end:[s3.go.list_buckets.imports.call] + if err != nil { + return nil, err + } - return result, nil + return result, nil } func main() { - // snippet-start:[s3.go.list_buckets.imports.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.list_buckets.imports.session] - - result, err := GetAllBuckets(sess) - if err != nil { - fmt.Println("Got an error retrieving buckets:") - fmt.Println(err) - return - } - - // snippet-start:[s3.go.list_buckets.imports.print] - fmt.Println("Buckets:") - - for _, bucket := range result.Buckets { - fmt.Println(*bucket.Name + ": " + bucket.CreationDate.Format("2006-01-02 15:04:05 Monday")) - } - // snippet-end:[s3.go.list_buckets.imports.print] + // snippet-start:[s3.go.list_buckets.imports.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.list_buckets.imports.session] + + result, err := GetAllBuckets(sess) + if err != nil { + fmt.Println("Got an error retrieving buckets:") + fmt.Println(err) + return + } + + // snippet-start:[s3.go.list_buckets.imports.print] + fmt.Println("Buckets:") + + for _, bucket := range result.Buckets { + fmt.Println(*bucket.Name + ": " + bucket.CreationDate.Format("2006-01-02 15:04:05 Monday")) + } + // snippet-end:[s3.go.list_buckets.imports.print] } -// snippet-end:[s3.go.list_buckets] \ No newline at end of file + +// snippet-end:[s3.go.list_buckets] diff --git a/go/s3/ListBuckets/ListBuckets_test.go b/go/s3/ListBuckets/ListBuckets_test.go index 210152767dc..76d4eb58fb3 100644 --- a/go/s3/ListBuckets/ListBuckets_test.go +++ b/go/s3/ListBuckets/ListBuckets_test.go @@ -1,123 +1,112 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "testing" - "time" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/google/uuid" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/google/uuid" ) func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestListBuckets(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file (~/.aws/credentials) - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - result, err := GetAllBuckets(sess) - if err != nil { - t.Fatal(err) - } - - numBuckets := len(result.Buckets) - - // Create a bucket, make sure it's in the list, - // make sure the list is one item larger, then delete the bucket - id := uuid.New() - bucketName := "some-prefix-" + id.String() - - err = createBucket(sess, &bucketName) - if err != nil { - t.Fatal(err) - } - - result, err = GetAllBuckets(sess) - if err != nil { - t.Fatal(err) - } - - lenEqual := len(result.Buckets) == numBuckets+1 - - if !lenEqual { - t.Log("Adding a bucket didn't work") - } - - foundBucket := false - - for _, b := range result.Buckets { - if *b.Name == bucketName { - foundBucket = true - break - } - } - - if foundBucket { - t.Log("Found bucket in list") - } else { - t.Log("Did not find bucket in list") - } - - err = deleteBucket(sess, &bucketName) - if err != nil { - t.Log("You'll have to delete " + bucketName + " yourself") - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file (~/.aws/credentials) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + result, err := GetAllBuckets(sess) + if err != nil { + t.Fatal(err) + } + + numBuckets := len(result.Buckets) + + // Create a bucket, make sure it's in the list, + // make sure the list is one item larger, then delete the bucket + id := uuid.New() + bucketName := "some-prefix-" + id.String() + + err = createBucket(sess, &bucketName) + if err != nil { + t.Fatal(err) + } + + result, err = GetAllBuckets(sess) + if err != nil { + t.Fatal(err) + } + + lenEqual := len(result.Buckets) == numBuckets+1 + + if !lenEqual { + t.Log("Adding a bucket didn't work") + } + + foundBucket := false + + for _, b := range result.Buckets { + if *b.Name == bucketName { + foundBucket = true + break + } + } + + if foundBucket { + t.Log("Found bucket in list") + } else { + t.Log("Did not find bucket in list") + } + + err = deleteBucket(sess, &bucketName) + if err != nil { + t.Log("You'll have to delete " + bucketName + " yourself") + } } diff --git a/go/s3/ListObjects/ListObjects.go b/go/s3/ListObjects/ListObjects.go index e1e4b4a4228..74e91b2a529 100644 --- a/go/s3/ListObjects/ListObjects.go +++ b/go/s3/ListObjects/ListObjects.go @@ -1,91 +1,86 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.list_objects] package main // snippet-start:[s3.go.list_objects.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.list_objects.imports] // GetObjects retrieves the objects in an Amazon S3 bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// // Output: -// If success, the list of objects and nil -// Otherwise, nil and an error from the call to ListObjectsV2 +// +// If success, the list of objects and nil +// Otherwise, nil and an error from the call to ListObjectsV2 func GetObjects(sess *session.Session, bucket *string) (*s3.ListObjectsV2Output, error) { - // snippet-start:[s3.go.list_objects.call] - svc := s3.New(sess) + // snippet-start:[s3.go.list_objects.call] + svc := s3.New(sess) - // Get the list of items - resp, err := svc.ListObjectsV2(&s3.ListObjectsV2Input{Bucket: bucket}) - // snippet-end:[s3.go.list_objects.call] - if err != nil { - return nil, err - } + // Get the list of items + resp, err := svc.ListObjectsV2(&s3.ListObjectsV2Input{Bucket: bucket}) + // snippet-end:[s3.go.list_objects.call] + if err != nil { + return nil, err + } - return resp, nil + return resp, nil } // Lists the items in the specified S3 bucket // // Usage: -// go run s3_list_objects.go BUCKET_NAME +// +// go run s3_list_objects.go BUCKET_NAME func main() { - // snippet-start:[s3.go.list_objects.args] - bucket := flag.String("b", "", "The name of the bucket") - flag.Parse() + // snippet-start:[s3.go.list_objects.args] + bucket := flag.String("b", "", "The name of the bucket") + flag.Parse() - if *bucket == "" { - fmt.Println("You must supply the name of a bucket (-b BUCKET)") - return - } - // snippet-end:[s3.go.list_objects.args] + if *bucket == "" { + fmt.Println("You must supply the name of a bucket (-b BUCKET)") + return + } + // snippet-end:[s3.go.list_objects.args] - // snippet-start:[s3.go.list_objects.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.list_objects.session] + // snippet-start:[s3.go.list_objects.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.list_objects.session] - resp, err := GetObjects(sess, bucket) - if err != nil { - fmt.Println("Got error retrieving list of objects:") - fmt.Println(err) - return - } + resp, err := GetObjects(sess, bucket) + if err != nil { + fmt.Println("Got error retrieving list of objects:") + fmt.Println(err) + return + } - // snippet-start:[s3.go.list_objects.print] - fmt.Println("Objects in " + *bucket + ":") + // snippet-start:[s3.go.list_objects.print] + fmt.Println("Objects in " + *bucket + ":") - for _, item := range resp.Contents { - fmt.Println("Name: ", *item.Key) - fmt.Println("Last modified: ", *item.LastModified) - fmt.Println("Size: ", *item.Size) - fmt.Println("Storage class: ", *item.StorageClass) - fmt.Println("") - } + for _, item := range resp.Contents { + fmt.Println("Name: ", *item.Key) + fmt.Println("Last modified: ", *item.LastModified) + fmt.Println("Size: ", *item.Size) + fmt.Println("Storage class: ", *item.StorageClass) + fmt.Println("") + } - fmt.Println("Found", len(resp.Contents), "items in bucket", bucket) - fmt.Println("") - // snippet-end:[s3.go.list_objects.print] + fmt.Println("Found", len(resp.Contents), "items in bucket", bucket) + fmt.Println("") + // snippet-end:[s3.go.list_objects.print] } + // snippet-end:[s3.go.list_objects] diff --git a/go/s3/ListObjects/ListObjects_test.go b/go/s3/ListObjects/ListObjects_test.go index 5506ec38ab3..24efc114efd 100644 --- a/go/s3/ListObjects/ListObjects_test.go +++ b/go/s3/ListObjects/ListObjects_test.go @@ -1,160 +1,149 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "fmt" - "strings" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - "github.com/google/uuid" + "fmt" + "strings" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + "github.com/google/uuid" ) func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func createObject(sess *session.Session, bucket *string, key *string) error { - svc := s3.New(sess) - - _, err := svc.PutObject(&s3.PutObjectInput{ - Body: strings.NewReader("Hello World!"), - Bucket: bucket, - Key: key, - }) - if err != nil { - fmt.Println("Got error putting object in bucket:") - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.PutObject(&s3.PutObjectInput{ + Body: strings.NewReader("Hello World!"), + Bucket: bucket, + Key: key, + }) + if err != nil { + fmt.Println("Got error putting object in bucket:") + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucket, - }) - - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - if err != nil { - return err - } - - _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucket, + }) + + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + if err != nil { + return err + } + + _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestListBuckets(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - // Initialize a session that the SDK uses to load - // credentials from the shared credentials file (~/.aws/credentials) - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - // Create a new bucket and add key to it - id := uuid.New() - bucket := "test-bucket-" + id.String() - - err := createBucket(sess, &bucket) - if err != nil { - t.Fatal(err) - } - - // Get original list of objects - result, err := GetObjects(sess, &bucket) - if err != nil { - t.Fatal(err) - } - - numObjects := *result.KeyCount + int64(1) - - key := "TestFile.txt" - - err = createObject(sess, &bucket, &key) - if err != nil { - t.Fatal(err) - } - - // Get new list of objects - result, err = GetObjects(sess, &bucket) - if err != nil { - t.Fatal(err) - } - - lenEqual := *result.KeyCount == numObjects - - if !lenEqual { - t.Log("Did not get new key in new list") - } - - foundKey := false - - for _, obj := range result.Contents { - if *obj.Key == key { - foundKey = true - break - } - } - - if foundKey { - t.Log("Found key in bucket") - } else { - t.Log("Did not find key in bucket") - } - - err = deleteBucket(sess, &bucket) - if err != nil { - t.Log("You'll have to delete " + bucket + " yourself") - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + // Initialize a session that the SDK uses to load + // credentials from the shared credentials file (~/.aws/credentials) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + // Create a new bucket and add key to it + id := uuid.New() + bucket := "test-bucket-" + id.String() + + err := createBucket(sess, &bucket) + if err != nil { + t.Fatal(err) + } + + // Get original list of objects + result, err := GetObjects(sess, &bucket) + if err != nil { + t.Fatal(err) + } + + numObjects := *result.KeyCount + int64(1) + + key := "TestFile.txt" + + err = createObject(sess, &bucket, &key) + if err != nil { + t.Fatal(err) + } + + // Get new list of objects + result, err = GetObjects(sess, &bucket) + if err != nil { + t.Fatal(err) + } + + lenEqual := *result.KeyCount == numObjects + + if !lenEqual { + t.Log("Did not get new key in new list") + } + + foundKey := false + + for _, obj := range result.Contents { + if *obj.Key == key { + foundKey = true + break + } + } + + if foundKey { + t.Log("Found key in bucket") + } else { + t.Log("Did not find key in bucket") + } + + err = deleteBucket(sess, &bucket) + if err != nil { + t.Log("You'll have to delete " + bucket + " yourself") + } } diff --git a/go/s3/MakeBucketPublic/MakeBucketPublic.go b/go/s3/MakeBucketPublic/MakeBucketPublic.go index 7c882625117..23e61436dc1 100644 --- a/go/s3/MakeBucketPublic/MakeBucketPublic.go +++ b/go/s3/MakeBucketPublic/MakeBucketPublic.go @@ -1,78 +1,72 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.make_bucket_public] package main // snippet-start:[s3.go.make_bucket_public.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.make_bucket_public.imports] // SetBucketPublic give everyone access to a bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// // Output: -// If success, nil -// Otherwise, an error from the call to PutBucketAcl +// +// If success, nil +// Otherwise, an error from the call to PutBucketAcl func SetBucketPublic(sess *session.Session, bucket *string) error { - // snippet-start:[s3.go.make_bucket_public.call] - svc := s3.New(sess) + // snippet-start:[s3.go.make_bucket_public.call] + svc := s3.New(sess) - params := &s3.PutBucketAclInput{ - Bucket: bucket, - ACL: aws.String("public-read"), - } + params := &s3.PutBucketAclInput{ + Bucket: bucket, + ACL: aws.String("public-read"), + } - _, err := svc.PutBucketAcl(params) - // snippet-end:[s3.go.make_bucket_public.call] - if err != nil { - return err - } + _, err := svc.PutBucketAcl(params) + // snippet-end:[s3.go.make_bucket_public.call] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[s3.go.make_bucket_public.args] - bucket := flag.String("b", "", "The name of the bucket") - flag.Parse() + // snippet-start:[s3.go.make_bucket_public.args] + bucket := flag.String("b", "", "The name of the bucket") + flag.Parse() - if *bucket == "" { - fmt.Println("You must supply the name of a bucket (-b BUCKET)") - return - } - // snippet-end:[s3.go.make_bucket_public.args] + if *bucket == "" { + fmt.Println("You must supply the name of a bucket (-b BUCKET)") + return + } + // snippet-end:[s3.go.make_bucket_public.args] - // snippet-start:[s3.go.make_bucket_public.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.make_bucket_public.session] + // snippet-start:[s3.go.make_bucket_public.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.make_bucket_public.session] - err := SetBucketPublic(sess, bucket) - if err != nil { - fmt.Println("Could not set public access to bucket " + *bucket) - return - } + err := SetBucketPublic(sess, bucket) + if err != nil { + fmt.Println("Could not set public access to bucket " + *bucket) + return + } - fmt.Println("Bucket " + *bucket + " is now public") + fmt.Println("Bucket " + *bucket + " is now public") } + // snippet-end:[s3.go.make_bucket_public] diff --git a/go/s3/MakeBucketPublic/MakeBucketPublic_test.go b/go/s3/MakeBucketPublic/MakeBucketPublic_test.go index d1de9d12466..1fd27c5b71f 100644 --- a/go/s3/MakeBucketPublic/MakeBucketPublic_test.go +++ b/go/s3/MakeBucketPublic/MakeBucketPublic_test.go @@ -1,32 +1,21 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "testing" - "time" + "encoding/json" + "io/ioutil" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" - "github.com/google/uuid" + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` + Bucket string `json:"Bucket"` } var configFileName = "config.json" @@ -34,107 +23,107 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Bucket: " + globalConfig.Bucket) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestMakeBucketPublic(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - bucketCreated := false - - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Created bucket " + globalConfig.Bucket) - bucketCreated = true - } - - err = SetBucketPublic(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Bucket " + globalConfig.Bucket + " is now public") - - if bucketCreated { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted bucket " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + bucketCreated := false + + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Created bucket " + globalConfig.Bucket) + bucketCreated = true + } + + err = SetBucketPublic(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Bucket " + globalConfig.Bucket + " is now public") + + if bucketCreated { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted bucket " + globalConfig.Bucket) + } } diff --git a/go/s3/PutBucketAcl/PutBucketAcl.go b/go/s3/PutBucketAcl/PutBucketAcl.go index a62d2aee04b..441fd46cf75 100644 --- a/go/s3/PutBucketAcl/PutBucketAcl.go +++ b/go/s3/PutBucketAcl/PutBucketAcl.go @@ -1,16 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.put_bucket_acl] package main @@ -23,15 +12,19 @@ import ( "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.put_bucket_acl.imports] // SetBucketACL gives a user access to a bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// // Output: -// If success, the SOMETHING of the RESOURCE and nil -// Otherwise, an empty string and an error from the call to FUNCTION +// +// If success, the SOMETHING of the RESOURCE and nil +// Otherwise, an empty string and an error from the call to FUNCTION func SetBucketACL(sess *session.Session, bucket, address, permission *string) error { // snippet-start:[s3.go.put_bucket_acl.service_acl] svc := s3.New(sess) @@ -39,7 +32,7 @@ func SetBucketACL(sess *session.Session, bucket, address, permission *string) er result, err := svc.GetBucketAcl(&s3.GetBucketAclInput{ Bucket: bucket, }) - // snippet-end:[s3.go.put_bucket_acl.service_acl] + // snippet-end:[s3.go.put_bucket_acl.service_acl] if err != nil { return err } @@ -99,12 +92,12 @@ func main() { } // snippet-end:[s3.go.put_bucket_acl.args] - // snippet-start:[s3.go.put_bucket_acl.session] + // snippet-start:[s3.go.put_bucket_acl.session] sess := session.Must(session.NewSessionWithOptions(session.Options{ SharedConfigState: session.SharedConfigEnable, })) - // snippet-end:[s3.go.put_bucket_acl.session] - + // snippet-end:[s3.go.put_bucket_acl.session] + err := SetBucketACL(sess, bucket, address, permission) if err != nil { fmt.Println("Got an error setting bucket ACL:") @@ -116,4 +109,5 @@ func main() { fmt.Println("Congratulations. You gave user with email address", address, permission, "permission to bucket", bucket) // snippet-end:[s3.go.put_bucket_acl.print] } + // snippet-end:[s3.go.put_bucket_acl] diff --git a/go/s3/PutBucketAcl/PutBucketAcl_test.go b/go/s3/PutBucketAcl/PutBucketAcl_test.go index 3756a0ada40..254994dd64b 100644 --- a/go/s3/PutBucketAcl/PutBucketAcl_test.go +++ b/go/s3/PutBucketAcl/PutBucketAcl_test.go @@ -1,36 +1,25 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "errors" - "io/ioutil" - "os" - "testing" - "time" + "encoding/json" + "errors" + "io/ioutil" + "os" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" - "github.com/google/uuid" + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` - Address string `json:"Address"` - Permission string `json:"Permission"` + Bucket string `json:"Bucket"` + Address string `json:"Address"` + Permission string `json:"Permission"` } var configFileName = "config.json" @@ -38,123 +27,123 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) - t.Log("Address: " + globalConfig.Address) - t.Log("Permission: " + globalConfig.Permission) + t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Address: " + globalConfig.Address) + t.Log("Permission: " + globalConfig.Permission) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestPutBucketAcl(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - if globalConfig.Address == "" { - // Check environment - globalConfig.Address = os.Getenv("ADDRESS") - t.Log("Set address " + globalConfig.Address + " from environment") - } - - if globalConfig.Address == "" { - t.Fatal(errors.New("Could not find an email address")) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - bucketCreated := false - - if globalConfig.Bucket == "" { - // Create the resources - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - bucketCreated = true - t.Log("Created bucket " + globalConfig.Bucket) - } - - if globalConfig.Permission == "" { - globalConfig.Permission = "READ" - } - - err = SetBucketACL(sess, &globalConfig.Bucket, &globalConfig.Address, &globalConfig.Permission) - if err != nil { - t.Fatal(err) - } - - t.Log("Congratulations. You gave user with email address", globalConfig.Address, globalConfig.Permission, "permission to bucket", globalConfig.Bucket) - - if bucketCreated { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted bucket " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + if globalConfig.Address == "" { + // Check environment + globalConfig.Address = os.Getenv("ADDRESS") + t.Log("Set address " + globalConfig.Address + " from environment") + } + + if globalConfig.Address == "" { + t.Fatal(errors.New("Could not find an email address")) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + bucketCreated := false + + if globalConfig.Bucket == "" { + // Create the resources + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + bucketCreated = true + t.Log("Created bucket " + globalConfig.Bucket) + } + + if globalConfig.Permission == "" { + globalConfig.Permission = "READ" + } + + err = SetBucketACL(sess, &globalConfig.Bucket, &globalConfig.Address, &globalConfig.Permission) + if err != nil { + t.Fatal(err) + } + + t.Log("Congratulations. You gave user with email address", globalConfig.Address, globalConfig.Permission, "permission to bucket", globalConfig.Bucket) + + if bucketCreated { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted bucket " + globalConfig.Bucket) + } } diff --git a/go/s3/PutObjectAcl/PutObjectAcl.go b/go/s3/PutObjectAcl/PutObjectAcl.go index e3049cb1abe..3be7ea37801 100644 --- a/go/s3/PutObjectAcl/PutObjectAcl.go +++ b/go/s3/PutObjectAcl/PutObjectAcl.go @@ -1,77 +1,68 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.put_object_acl] package main // snippet-start:[s3.go.put_object_acl.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3iface" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3iface" ) + // snippet-end:[s3.go.put_object_acl.imports] // PutObjectACL gives the person with EMAIL address read access to BUCKET OBJECT func PutObjectACL(svc s3iface.S3API, bucket, key, address *string) error { - // snippet-start:[s3.go.put_object_acl.call] - _, err := svc.PutObjectAcl(&s3.PutObjectAclInput{ - Bucket: bucket, - Key: key, - GrantRead: aws.String("emailaddress=" + *address), - }) - // snippet-end:[s3.go.put_object_acl.call] - if err != nil { - return err - } + // snippet-start:[s3.go.put_object_acl.call] + _, err := svc.PutObjectAcl(&s3.PutObjectAclInput{ + Bucket: bucket, + Key: key, + GrantRead: aws.String("emailaddress=" + *address), + }) + // snippet-end:[s3.go.put_object_acl.call] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[s3.go.put_object_acl.args] - bucket := flag.String("b", "", "The bucket in which the object is stored") - key := flag.String("k", "", "The key of the object") - address := flag.String("a", "", "The email address") - flag.Parse() + // snippet-start:[s3.go.put_object_acl.args] + bucket := flag.String("b", "", "The bucket in which the object is stored") + key := flag.String("k", "", "The key of the object") + address := flag.String("a", "", "The email address") + flag.Parse() - if *bucket == "" || *key == "" || *address == "" { - fmt.Println("You must supply a bucket (-b BUCKET), key (-k KEY), and email address (-a ADDRESS)") - return - } - // snippet-end:[s3.go.put_object_acl.args] + if *bucket == "" || *key == "" || *address == "" { + fmt.Println("You must supply a bucket (-b BUCKET), key (-k KEY), and email address (-a ADDRESS)") + return + } + // snippet-end:[s3.go.put_object_acl.args] - // snippet-start:[s3.go.put_object_acl.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + // snippet-start:[s3.go.put_object_acl.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - svc := s3.New(sess) - // snippet-end:[s3.go.put_object_acl.session] + svc := s3.New(sess) + // snippet-end:[s3.go.put_object_acl.session] - err := PutObjectACL(svc, bucket, key, address) - if err != nil { - fmt.Println("Got an error retrieving the ACL for " + *key) - fmt.Println(err) - return - } + err := PutObjectACL(svc, bucket, key, address) + if err != nil { + fmt.Println("Got an error retrieving the ACL for " + *key) + fmt.Println(err) + return + } - // snippet-start:[s3.go.put_object_acl.print] - fmt.Println("Congratulations. You gave user with email address", address, "read permission to bucket", bucket, "object", key) - // snippet-end:[s3.go.put_object_acl.print] + // snippet-start:[s3.go.put_object_acl.print] + fmt.Println("Congratulations. You gave user with email address", address, "read permission to bucket", bucket, "object", key) + // snippet-end:[s3.go.put_object_acl.print] } + // snippet-end:[s3.go.put_object_acl] diff --git a/go/s3/PutObjectAcl/PutObjectAcl_test.go b/go/s3/PutObjectAcl/PutObjectAcl_test.go index 2f167b6702a..efa352204f1 100644 --- a/go/s3/PutObjectAcl/PutObjectAcl_test.go +++ b/go/s3/PutObjectAcl/PutObjectAcl_test.go @@ -1,49 +1,38 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "testing" - "time" + "encoding/json" + "io/ioutil" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3iface" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3iface" - "github.com/google/uuid" + "github.com/google/uuid" ) // Define a mock struct to be used in your unit tests of myFunc. type mockS3Client struct { - s3iface.S3API + s3iface.S3API } func (m *mockS3Client) PutObjectAcl(*s3.PutObjectAclInput) (*s3.PutObjectAclOutput, error) { - resp := s3.PutObjectAclOutput{ - RequestCharged: aws.String(""), - } + resp := s3.PutObjectAclOutput{ + RequestCharged: aws.String(""), + } - return &resp, nil + return &resp, nil } type Config struct { - Bucket string `json:"Name"` - Key string `json:"Key"` - Address string `json:"Address"` + Bucket string `json:"Name"` + Key string `json:"Key"` + Address string `json:"Address"` } var configFileName = "config.json" @@ -51,64 +40,64 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) - t.Log("Key: " + globalConfig.Key) - t.Log("Address: " + globalConfig.Address) + t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Key: " + globalConfig.Key) + t.Log("Address: " + globalConfig.Address) - return nil + return nil } func TestPubObjectAcl(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } - if globalConfig.Bucket == "" || globalConfig.Key == "" || globalConfig.Address == "" { - // mock resources - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - globalConfig.Key = "random" - globalConfig.Address = "somebody@somewhere" + if globalConfig.Bucket == "" || globalConfig.Key == "" || globalConfig.Address == "" { + // mock resources + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + globalConfig.Key = "random" + globalConfig.Address = "somebody@somewhere" - mockSvc := &mockS3Client{} + mockSvc := &mockS3Client{} - err = PutObjectACL(mockSvc, &globalConfig.Bucket, &globalConfig.Key, &globalConfig.Address) - if err != nil { - t.Fatal(err) - } + err = PutObjectACL(mockSvc, &globalConfig.Bucket, &globalConfig.Key, &globalConfig.Address) + if err != nil { + t.Fatal(err) + } - t.Log("Congratulations. You gave user with email address", globalConfig.Address, "read permission to bucket", globalConfig.Bucket, "object", globalConfig.Key) - } else { - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + t.Log("Congratulations. You gave user with email address", globalConfig.Address, "read permission to bucket", globalConfig.Bucket, "object", globalConfig.Key) + } else { + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - svc := s3.New(sess) + svc := s3.New(sess) - err = PutObjectACL(svc, &globalConfig.Bucket, &globalConfig.Key, &globalConfig.Address) - if err != nil { + err = PutObjectACL(svc, &globalConfig.Bucket, &globalConfig.Key, &globalConfig.Address) + if err != nil { - t.Fatal(err) - } + t.Fatal(err) + } - t.Log("Congratulations. You gave user with email address", globalConfig.Address, "read permission to bucket", globalConfig.Bucket, "object", globalConfig.Key) - } + t.Log("Congratulations. You gave user with email address", globalConfig.Address, "read permission to bucket", globalConfig.Bucket, "object", globalConfig.Key) + } } diff --git a/go/s3/PutObjectWithSetters/PutObjectWithSetters.go b/go/s3/PutObjectWithSetters/PutObjectWithSetters.go index df2cf50ecb2..a41bb632e01 100644 --- a/go/s3/PutObjectWithSetters/PutObjectWithSetters.go +++ b/go/s3/PutObjectWithSetters/PutObjectWithSetters.go @@ -1,83 +1,77 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ -//snippet-start:[s3.go.put_object] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[s3.go.put_object] package main -//snippet-start:[s3.go.put_object.imports] +// snippet-start:[s3.go.put_object.imports] import ( - "flag" - "fmt" - "strings" + "flag" + "fmt" + "strings" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) -//snippet-end:[s3.go.put_object.imports] + +// snippet-end:[s3.go.put_object.imports] // PutObjectWithSetters uploads a file to a bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket -// key is the name of the file +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// key is the name of the file +// // Output: -// If success, nil -// Otherwise, an error from the call to PutObject +// +// If success, nil +// Otherwise, an error from the call to PutObject func PutObjectWithSetters(sess *session.Session, bucket *string, key *string) error { - //snippet-start:[s3.go.put_object.call] - svc := s3.New(sess) + // snippet-start:[s3.go.put_object.call] + svc := s3.New(sess) - _, err := svc.PutObject((&s3.PutObjectInput{}). - SetBucket(*bucket). - SetKey(*key). - SetBody(strings.NewReader("object body")), //. - // SetWebsiteRedirectLocation("https://example.com/something"), - ) - //snippet-end:[s3.go.put_object.call] - if err != nil { - return err - } + _, err := svc.PutObject((&s3.PutObjectInput{}). + SetBucket(*bucket). + SetKey(*key). + SetBody(strings.NewReader("object body")), //. + // SetWebsiteRedirectLocation("https://example.com/something"), + ) + // snippet-end:[s3.go.put_object.call] + if err != nil { + return err + } - return nil + return nil } func main() { - //snippet-start:[s3.go.put_object.args] - bucket := flag.String("b", "", "The bucket to upload to") - key := flag.String("k", "", "The object to upload") - flag.Parse() + // snippet-start:[s3.go.put_object.args] + bucket := flag.String("b", "", "The bucket to upload to") + key := flag.String("k", "", "The object to upload") + flag.Parse() - if *bucket == "" || *key == "" { - fmt.Println("You must supply a bucket name (-b BUCKET) and key (-k KEY)") - return - } - //snippet-end:[s3.go.put_object.args] + if *bucket == "" || *key == "" { + fmt.Println("You must supply a bucket name (-b BUCKET) and key (-k KEY)") + return + } + // snippet-end:[s3.go.put_object.args] - //snippet-start:[s3.go.put_object.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - //snippet-end:[s3.go.put_object.session] + // snippet-start:[s3.go.put_object.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.put_object.session] - err := PutObjectWithSetters(sess, bucket, key) - if err != nil { - fmt.Println("Got an error putting object:") - fmt.Println(err) - return - } + err := PutObjectWithSetters(sess, bucket, key) + if err != nil { + fmt.Println("Got an error putting object:") + fmt.Println(err) + return + } - //snippet-start:[s3.go.put_object.print] - fmt.Println("Put object with key " + *key + " into bucket" + *bucket) - //snippet-end:[s3.go.put_object.print] + // snippet-start:[s3.go.put_object.print] + fmt.Println("Put object with key " + *key + " into bucket" + *bucket) + // snippet-end:[s3.go.put_object.print] } -//snippet-end:[s3.go.put_object] + +// snippet-end:[s3.go.put_object] diff --git a/go/s3/PutObjectWithSetters/PutObjectWithSetters_test.go b/go/s3/PutObjectWithSetters/PutObjectWithSetters_test.go index 4844d276e6f..66f61da4a97 100644 --- a/go/s3/PutObjectWithSetters/PutObjectWithSetters_test.go +++ b/go/s3/PutObjectWithSetters/PutObjectWithSetters_test.go @@ -1,35 +1,24 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "testing" - "time" + "encoding/json" + "io/ioutil" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" - "github.com/google/uuid" + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` - Key string `json:"Key"` + Bucket string `json:"Bucket"` + Key string `json:"Key"` } var configFileName = "config.json" @@ -37,122 +26,122 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) - t.Log("Key: " + globalConfig.Key) + t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Key: " + globalConfig.Key) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucket, - }) - - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - if err != nil { - return err - } - - _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucket, + }) + + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + if err != nil { + return err + } + + _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestPutObjectWithSetters(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - createdBucket := false - - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - createdBucket = true - t.Log("Created bucket " + globalConfig.Bucket) - } - - if globalConfig.Key == "" { - globalConfig.Key = "dummy.txt" - } - - err = PutObjectWithSetters(sess, &globalConfig.Bucket, &globalConfig.Key) - if err != nil { - if createdBucket { - t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") - } - - t.Fatal(err) - } - - if createdBucket { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted bucket " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + createdBucket := false + + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + createdBucket = true + t.Log("Created bucket " + globalConfig.Bucket) + } + + if globalConfig.Key == "" { + globalConfig.Key = "dummy.txt" + } + + err = PutObjectWithSetters(sess, &globalConfig.Bucket, &globalConfig.Key) + if err != nil { + if createdBucket { + t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") + } + + t.Fatal(err) + } + + if createdBucket { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted bucket " + globalConfig.Bucket) + } } diff --git a/go/s3/RequireServerEncryption/RequireServerEncryption.go b/go/s3/RequireServerEncryption/RequireServerEncryption.go index 633886dd186..2f6892797f7 100644 --- a/go/s3/RequireServerEncryption/RequireServerEncryption.go +++ b/go/s3/RequireServerEncryption/RequireServerEncryption.go @@ -1,115 +1,109 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.require_server_encryption] package main // snippet-start:[s3.go.require_server_encryption.imports] import ( - "encoding/json" - "flag" - "fmt" + "encoding/json" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.require_server_encryption.imports] // AddKmsBucketPolicy adds a policy to enable KMS encryption by default on a bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// // Output: -// If success, nil -// Otherwise, an error from the call to json.Marshall or PutBucketPolicy +// +// If success, nil +// Otherwise, an error from the call to json.Marshall or PutBucketPolicy func AddKmsBucketPolicy(sess *session.Session, bucket *string) error { - // snippet-start:[s3.go.require_server_encryption.policy] - svc := s3.New(sess) + // snippet-start:[s3.go.require_server_encryption.policy] + svc := s3.New(sess) - PolicyDoc := map[string]interface{}{ - "Version": "2012-10-17", - "Statement": []map[string]interface{}{ - { - "Sid": "DenyIncorrectEncryptionHeader", - "Effect": "Deny", - "Principal": "*", - "Action": "s3:PutObject", - "Resource": "arn:aws:s3:::" + *bucket + "/*", - "Condition": map[string]interface{}{ - "StringNotEquals": map[string]interface{}{ - "s3:x-amz-server-side-encryption": "aws:kms", - }, - }, - }, - { - "Sid": "DenyUnEncryptedObjectUploads", - "Effect": "Deny", - "Principal": "*", - "Action": "s3:PutObject", - "Resource": "arn:aws:s3:::" + *bucket + "/*", - "Condition": map[string]interface{}{ - "Null": map[string]interface{}{ - "s3:x-amz-server-side-encryption": "true", - }, - }, - }, - }, - } + PolicyDoc := map[string]interface{}{ + "Version": "2012-10-17", + "Statement": []map[string]interface{}{ + { + "Sid": "DenyIncorrectEncryptionHeader", + "Effect": "Deny", + "Principal": "*", + "Action": "s3:PutObject", + "Resource": "arn:aws:s3:::" + *bucket + "/*", + "Condition": map[string]interface{}{ + "StringNotEquals": map[string]interface{}{ + "s3:x-amz-server-side-encryption": "aws:kms", + }, + }, + }, + { + "Sid": "DenyUnEncryptedObjectUploads", + "Effect": "Deny", + "Principal": "*", + "Action": "s3:PutObject", + "Resource": "arn:aws:s3:::" + *bucket + "/*", + "Condition": map[string]interface{}{ + "Null": map[string]interface{}{ + "s3:x-amz-server-side-encryption": "true", + }, + }, + }, + }, + } - policy, err := json.Marshal(PolicyDoc) - // snippet-end:[s3.go.require_server_encryption.policy] - if err != nil { - return err - } + policy, err := json.Marshal(PolicyDoc) + // snippet-end:[s3.go.require_server_encryption.policy] + if err != nil { + return err + } - // snippet-start:[s3.go.require_server_encryption.call] - _, err = svc.PutBucketPolicy(&s3.PutBucketPolicyInput{ - Bucket: bucket, - Policy: aws.String(string(policy)), - }) - // snippet-end:[s3.go.require_server_encryption.call] - if err != nil { - return err - } + // snippet-start:[s3.go.require_server_encryption.call] + _, err = svc.PutBucketPolicy(&s3.PutBucketPolicyInput{ + Bucket: bucket, + Policy: aws.String(string(policy)), + }) + // snippet-end:[s3.go.require_server_encryption.call] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[s3.go.require_server_encryption.args] - bucket := flag.String("b", "", "The bucket to encrypt") - flag.Parse() + // snippet-start:[s3.go.require_server_encryption.args] + bucket := flag.String("b", "", "The bucket to encrypt") + flag.Parse() - if *bucket == "" { - fmt.Println("You must supply a bucket name (-b BUCKET)") - return - } - // snippet-end:[s3.go.require_server_encryption.args] + if *bucket == "" { + fmt.Println("You must supply a bucket name (-b BUCKET)") + return + } + // snippet-end:[s3.go.require_server_encryption.args] - // snippet-start:[s3.go.require_server_encryption.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.require_server_encryption.session] + // snippet-start:[s3.go.require_server_encryption.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.require_server_encryption.session] - err := AddKmsBucketPolicy(sess, bucket) - if err != nil { - fmt.Println("Got an error adding policy to bucket " + *bucket + ":") - fmt.Println(err) - return - } + err := AddKmsBucketPolicy(sess, bucket) + if err != nil { + fmt.Println("Got an error adding policy to bucket " + *bucket + ":") + fmt.Println(err) + return + } - fmt.Println("Set policy for " + *bucket) + fmt.Println("Set policy for " + *bucket) } + // snippet-end:[s3.go.require_server_encryption] diff --git a/go/s3/RequireServerEncryption/RequireServerEncryption_test.go b/go/s3/RequireServerEncryption/RequireServerEncryption_test.go index 909da37811e..be3aed2d9ca 100644 --- a/go/s3/RequireServerEncryption/RequireServerEncryption_test.go +++ b/go/s3/RequireServerEncryption/RequireServerEncryption_test.go @@ -1,34 +1,23 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "testing" - "time" + "encoding/json" + "io/ioutil" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" - "github.com/google/uuid" + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` + Bucket string `json:"Bucket"` } var configFileName = "config.json" @@ -36,116 +25,116 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Bucket: " + globalConfig.Bucket) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucket, - }) - - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - if err != nil { - return err - } - - _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucket, + }) + + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + if err != nil { + return err + } + + _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestRequireServerEncryption(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - bucketCreated := false - - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Created " + globalConfig.Bucket) - bucketCreated = true - } - - err = AddKmsBucketPolicy(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Added default KMS encryption to " + globalConfig.Bucket) - - if bucketCreated { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + bucketCreated := false + + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Created " + globalConfig.Bucket) + bucketCreated = true + } + + err = AddKmsBucketPolicy(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Added default KMS encryption to " + globalConfig.Bucket) + + if bucketCreated { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted " + globalConfig.Bucket) + } } diff --git a/go/s3/RestoreObject/RestoreObject.go b/go/s3/RestoreObject/RestoreObject.go index dff5ee3886e..c45d0d07c3f 100644 --- a/go/s3/RestoreObject/RestoreObject.go +++ b/go/s3/RestoreObject/RestoreObject.go @@ -1,85 +1,79 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.restore_object] package main // snippet-start:[s3.go.restore_object.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3iface" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3iface" ) + // snippet-end:[s3.go.restore_object.imports] // RestoreItem restores an item to a bucket for a number of days // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket -// item is the name of the bucket object to delete +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// item is the name of the bucket object to delete +// // Output: -// If success, nil -// Otherwise, an error from the call to DeleteObject or WaitUntilObjectNotExists +// +// If success, nil +// Otherwise, an error from the call to DeleteObject or WaitUntilObjectNotExists func RestoreItem(svc s3iface.S3API, bucket *string, item *string, days *int64) error { - // snippet-start:[s3.go.restore_object.call] - _, err := svc.RestoreObject(&s3.RestoreObjectInput{ - Bucket: bucket, - Key: item, - RestoreRequest: &s3.RestoreRequest{ - Days: days, - }, - }) - // snippet-end:[s3.go.restore_object.call] - if err != nil { - return err - } + // snippet-start:[s3.go.restore_object.call] + _, err := svc.RestoreObject(&s3.RestoreObjectInput{ + Bucket: bucket, + Key: item, + RestoreRequest: &s3.RestoreRequest{ + Days: days, + }, + }) + // snippet-end:[s3.go.restore_object.call] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[s3.go.restore_object.args] - bucket := flag.String("b", "", "The bucket to which the object is restored") - item := flag.String("i", "", "The object to restore") - days := flag.Int64("d", 30, "The number of days to restore it from Glacier") - flag.Parse() + // snippet-start:[s3.go.restore_object.args] + bucket := flag.String("b", "", "The bucket to which the object is restored") + item := flag.String("i", "", "The object to restore") + days := flag.Int64("d", 30, "The number of days to restore it from Glacier") + flag.Parse() - if *bucket == "" || *item == "" { - fmt.Println("You must supply the bucket (-b BUCKET), and item to restore (-i ITEM") - return - } - // snippet-end:[s3.go.restore_object.args] + if *bucket == "" || *item == "" { + fmt.Println("You must supply the bucket (-b BUCKET), and item to restore (-i ITEM") + return + } + // snippet-end:[s3.go.restore_object.args] - // snippet-start:[s3.go.restore_object.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + // snippet-start:[s3.go.restore_object.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - svc := s3.New(sess) - // snippet-end:[s3.go.restore_object.session] + svc := s3.New(sess) + // snippet-end:[s3.go.restore_object.session] - err := RestoreItem(svc, bucket, item, days) - if err != nil { - fmt.Println("Got an error restoring the item:") - fmt.Println(err) - return - } + err := RestoreItem(svc, bucket, item, days) + if err != nil { + fmt.Println("Got an error restoring the item:") + fmt.Println(err) + return + } - // snippet-start:[s3.go.restore_object.print] - fmt.Println("Restored " + *item + " to " + *bucket) - // snippet-end:[s3.go.restore_object.print] + // snippet-start:[s3.go.restore_object.print] + fmt.Println("Restored " + *item + " to " + *bucket) + // snippet-end:[s3.go.restore_object.print] } + // snippet-end:[s3.go.restore_object] diff --git a/go/s3/RestoreObject/RestoreObject_test.go b/go/s3/RestoreObject/RestoreObject_test.go index a075f0d93ee..712e30a9be5 100644 --- a/go/s3/RestoreObject/RestoreObject_test.go +++ b/go/s3/RestoreObject/RestoreObject_test.go @@ -1,16 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( diff --git a/go/s3/SetBucketPolicy/SetBucketPolicy.go b/go/s3/SetBucketPolicy/SetBucketPolicy.go index b8ab2e6c9f7..c9c292a327c 100644 --- a/go/s3/SetBucketPolicy/SetBucketPolicy.go +++ b/go/s3/SetBucketPolicy/SetBucketPolicy.go @@ -1,100 +1,94 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.set_bucket_policy] package main // snippet-start:[s3.go.set_bucket_policy.imports] import ( - "encoding/json" - "flag" - "fmt" + "encoding/json" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.set_bucket_policy.imports] // SetBucketPolicy applies the policy to a bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// // Output: -// If success, nil -// Otherwise, an error from the call to PutBucketPolicy +// +// If success, nil +// Otherwise, an error from the call to PutBucketPolicy func SetBucketPolicy(sess *session.Session, bucket *string) error { - // snippet-start:[s3.go.set_bucket_policy.call] - svc := s3.New(sess) + // snippet-start:[s3.go.set_bucket_policy.call] + svc := s3.New(sess) - readOnlyAnonUserPolicy := map[string]interface{}{ - "Version": "2012-10-17", - "Statement": []map[string]interface{}{ - { - "Sid": "AddPerm", - "Effect": "Allow", - "Principal": "*", - "Action": []string{ - "s3:GetObject", - }, - "Resource": []string{ - "arn:aws:s3:::" + *bucket + "/*", - }, - }, - }, - } + readOnlyAnonUserPolicy := map[string]interface{}{ + "Version": "2012-10-17", + "Statement": []map[string]interface{}{ + { + "Sid": "AddPerm", + "Effect": "Allow", + "Principal": "*", + "Action": []string{ + "s3:GetObject", + }, + "Resource": []string{ + "arn:aws:s3:::" + *bucket + "/*", + }, + }, + }, + } - policy, err := json.Marshal(readOnlyAnonUserPolicy) - if err != nil { - return err - } + policy, err := json.Marshal(readOnlyAnonUserPolicy) + if err != nil { + return err + } - _, err = svc.PutBucketPolicy(&s3.PutBucketPolicyInput{ - Bucket: bucket, - Policy: aws.String(string(policy)), - }) - // snippet-end:[s3.go.set_bucket_policy.call] - if err != nil { - return err - } + _, err = svc.PutBucketPolicy(&s3.PutBucketPolicyInput{ + Bucket: bucket, + Policy: aws.String(string(policy)), + }) + // snippet-end:[s3.go.set_bucket_policy.call] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[s3.go.set_bucket_policy.args] - bucket := flag.String("b", "", "The name of the bucket") - flag.Parse() + // snippet-start:[s3.go.set_bucket_policy.args] + bucket := flag.String("b", "", "The name of the bucket") + flag.Parse() - if *bucket == "" { - fmt.Println("You must supply a bucket name (-b BUCKET)") - return - } - // snippet-end:[s3.go.set_bucket_policy.args] + if *bucket == "" { + fmt.Println("You must supply a bucket name (-b BUCKET)") + return + } + // snippet-end:[s3.go.set_bucket_policy.args] - // snippet-start:[s3.go.set_bucket_policy.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.set_bucket_policy.session] + // snippet-start:[s3.go.set_bucket_policy.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.set_bucket_policy.session] - err := SetBucketPolicy(sess, bucket) - if err != nil { - fmt.Println("Got an error setting bucket policy:") - fmt.Println(err) - return - } + err := SetBucketPolicy(sess, bucket) + if err != nil { + fmt.Println("Got an error setting bucket policy:") + fmt.Println(err) + return + } - fmt.Println("Set the bucket policy") + fmt.Println("Set the bucket policy") } + // snippet-end:[s3.go.set_bucket_policy] diff --git a/go/s3/SetBucketPolicy/SetBucketPolicy_test.go b/go/s3/SetBucketPolicy/SetBucketPolicy_test.go index c0ce69c7d43..ba7968004ea 100644 --- a/go/s3/SetBucketPolicy/SetBucketPolicy_test.go +++ b/go/s3/SetBucketPolicy/SetBucketPolicy_test.go @@ -1,33 +1,22 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "fmt" - "io/ioutil" - "testing" - "time" + "encoding/json" + "fmt" + "io/ioutil" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" - "github.com/google/uuid" + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` + Bucket string `json:"Bucket"` } var configFileName = "config.json" @@ -35,107 +24,107 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Bucket: " + globalConfig.Bucket) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestGetBucketPolicy(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - bucketCreated := false - - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - fmt.Println("Created bucket " + globalConfig.Bucket) - bucketCreated = true - } - - err = SetBucketPolicy(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Created policy") - - if bucketCreated { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted bucket " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + bucketCreated := false + + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + fmt.Println("Created bucket " + globalConfig.Bucket) + bucketCreated = true + } + + err = SetBucketPolicy(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Created policy") + + if bucketCreated { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted bucket " + globalConfig.Bucket) + } } diff --git a/go/s3/SetBucketWebsite/SetBucketWebsite.go b/go/s3/SetBucketWebsite/SetBucketWebsite.go index 2f7a187b09e..7e2ae64da96 100644 --- a/go/s3/SetBucketWebsite/SetBucketWebsite.go +++ b/go/s3/SetBucketWebsite/SetBucketWebsite.go @@ -1,92 +1,86 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.put_bucket_website] package main // snippet-start:[s3.go.put_bucket_website.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.put_bucket_website.imports] // SetWebPage sets up a bucket as a static website // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket -// indexPage is the name of the index page -// errorPage is the name of the error page +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// indexPage is the name of the index page +// errorPage is the name of the error page +// // Output: -// If success, nil -// Otherwise, an error from the call to PutBucketWebsite +// +// If success, nil +// Otherwise, an error from the call to PutBucketWebsite func SetWebPage(sess *session.Session, bucket, indexPage, errorPage *string) error { - // snippet-start:[s3.go.put_bucket_website.call] - svc := s3.New(sess) + // snippet-start:[s3.go.put_bucket_website.call] + svc := s3.New(sess) - params := s3.PutBucketWebsiteInput{ - Bucket: bucket, - WebsiteConfiguration: &s3.WebsiteConfiguration{ - IndexDocument: &s3.IndexDocument{ - Suffix: indexPage, - }, - }, - } + params := s3.PutBucketWebsiteInput{ + Bucket: bucket, + WebsiteConfiguration: &s3.WebsiteConfiguration{ + IndexDocument: &s3.IndexDocument{ + Suffix: indexPage, + }, + }, + } - if len(*errorPage) > 0 { - params.WebsiteConfiguration.ErrorDocument = &s3.ErrorDocument{ - Key: errorPage, - } - } + if len(*errorPage) > 0 { + params.WebsiteConfiguration.ErrorDocument = &s3.ErrorDocument{ + Key: errorPage, + } + } - _, err := svc.PutBucketWebsite(¶ms) - // snippet-end:[s3.go.put_bucket_website.call] - if err != nil { - return err - } + _, err := svc.PutBucketWebsite(¶ms) + // snippet-end:[s3.go.put_bucket_website.call] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[s3.go.put_bucket_website.args] - bucket := flag.String("b", "", "The name of the bucket") - indexPage := flag.String("i", "", "The name of the index page") - errorPage := flag.String("e", "", "The name of the error page (optional)") - flag.Parse() + // snippet-start:[s3.go.put_bucket_website.args] + bucket := flag.String("b", "", "The name of the bucket") + indexPage := flag.String("i", "", "The name of the index page") + errorPage := flag.String("e", "", "The name of the error page (optional)") + flag.Parse() - if *bucket == "" || *indexPage == "" { - fmt.Println("You must supply a bucket name (-b BUCKET) and index page (-i INDEX)") - return - } - // snippet-end:[s3.go.put_bucket_website.args] + if *bucket == "" || *indexPage == "" { + fmt.Println("You must supply a bucket name (-b BUCKET) and index page (-i INDEX)") + return + } + // snippet-end:[s3.go.put_bucket_website.args] - // snippet-start:[s3.go.put_bucket_website.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.put_bucket_website.session] + // snippet-start:[s3.go.put_bucket_website.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.put_bucket_website.session] - err := SetWebPage(sess, bucket, indexPage, errorPage) - if err != nil { - fmt.Println("Got an error setting bucket as static website:") - fmt.Println(err) - return - } + err := SetWebPage(sess, bucket, indexPage, errorPage) + if err != nil { + fmt.Println("Got an error setting bucket as static website:") + fmt.Println(err) + return + } - fmt.Println("Set bucket website configuration") + fmt.Println("Set bucket website configuration") } + // snippet-end:[s3.go.put_bucket_website] diff --git a/go/s3/SetBucketWebsite/SetBucketWebsite_test.go b/go/s3/SetBucketWebsite/SetBucketWebsite_test.go index 64cb51b1f8c..435538dfb50 100644 --- a/go/s3/SetBucketWebsite/SetBucketWebsite_test.go +++ b/go/s3/SetBucketWebsite/SetBucketWebsite_test.go @@ -1,37 +1,26 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "strings" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - - "github.com/google/uuid" + "encoding/json" + "io/ioutil" + "strings" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` - IndexPage string `json:"IndexPage"` - ErrorPage string `json:"ErrorPage"` + Bucket string `json:"Bucket"` + IndexPage string `json:"IndexPage"` + ErrorPage string `json:"ErrorPage"` } var configFileName = "config.json" @@ -39,163 +28,163 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) - t.Log("IndexPage: " + globalConfig.IndexPage) - t.Log("ErrorPage: " + globalConfig.ErrorPage) + t.Log("Bucket: " + globalConfig.Bucket) + t.Log("IndexPage: " + globalConfig.IndexPage) + t.Log("ErrorPage: " + globalConfig.ErrorPage) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func createObject(sess *session.Session, bucket *string, key *string, content *string) error { - svc := s3.New(sess) - - _, err := svc.PutObject(&s3.PutObjectInput{ - Body: strings.NewReader(*content), - Bucket: bucket, - Key: key, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.PutObject(&s3.PutObjectInput{ + Body: strings.NewReader(*content), + Bucket: bucket, + Key: key, + }) + if err != nil { + return err + } + + return nil } func clearBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucket, - }) + svc := s3.New(sess) + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucket, + }) - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - if err != nil { - return err - } + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + if err != nil { + return err + } - return nil + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestSetBucketWebsite(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - bucketCreated := false - - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - if globalConfig.IndexPage == "" { - globalConfig.IndexPage = "Index.html" - content := "

This is the index

" - err := createObject(sess, &globalConfig.Bucket, &globalConfig.IndexPage, &content) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - } - - if globalConfig.ErrorPage == "" { - globalConfig.ErrorPage = "Error.html" - content := "

ERROR!

" - err := createObject(sess, &globalConfig.Bucket, &globalConfig.ErrorPage, &content) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - } - - bucketCreated = true - t.Log("Created bucket " + globalConfig.Bucket) - } - - err = SetWebPage(sess, &globalConfig.Bucket, &globalConfig.IndexPage, &globalConfig.ErrorPage) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - if bucketCreated { - err := clearBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - err = deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + bucketCreated := false + + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + if globalConfig.IndexPage == "" { + globalConfig.IndexPage = "Index.html" + content := "

This is the index

" + err := createObject(sess, &globalConfig.Bucket, &globalConfig.IndexPage, &content) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + } + + if globalConfig.ErrorPage == "" { + globalConfig.ErrorPage = "Error.html" + content := "

ERROR!

" + err := createObject(sess, &globalConfig.Bucket, &globalConfig.ErrorPage, &content) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + } + + bucketCreated = true + t.Log("Created bucket " + globalConfig.Bucket) + } + + err = SetWebPage(sess, &globalConfig.Bucket, &globalConfig.IndexPage, &globalConfig.ErrorPage) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + if bucketCreated { + err := clearBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + err = deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted " + globalConfig.Bucket) + } } diff --git a/go/s3/SetCors/SetCors.go b/go/s3/SetCors/SetCors.go index b69706d2d1e..ef6c17b6d7a 100644 --- a/go/s3/SetCors/SetCors.go +++ b/go/s3/SetCors/SetCors.go @@ -1,114 +1,109 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.put_bucket_cors] package main // snippet-start:[s3.go.put_bucket_cors.imports] import ( - "flag" - "fmt" - "strings" + "flag" + "fmt" + "strings" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.put_bucket_cors.imports] // SetCors configures CORS rules for a bucket by setting the allowed HTTP methods. // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of bucket -// methods are the HTTP methods: "POST", "GET", "PUT", "PATCH", "DELETE" +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of bucket +// methods are the HTTP methods: "POST", "GET", "PUT", "PATCH", "DELETE" +// // Output: -// If success, the SOMETHING of the RESOURCE and nil -// Otherwise, an empty string and an error from the call to FUNCTION +// +// If success, the SOMETHING of the RESOURCE and nil +// Otherwise, an empty string and an error from the call to FUNCTION +// // Requires the bucket name, and can also take a space separated // list of HTTP methods. func SetCors(sess *session.Session, bucket *string, methods []string) error { - // snippet-start:[s3.go.put_bucket_cors.rule] - rule := s3.CORSRule{ - AllowedHeaders: aws.StringSlice([]string{"Authorization"}), - AllowedOrigins: aws.StringSlice([]string{"*"}), - MaxAgeSeconds: aws.Int64(3000), - AllowedMethods: aws.StringSlice(methods), - } - // snippet-end:[s3.go.put_bucket_cors.rule] - - // snippet-start:[s3.go.put_bucket_cors.call] - svc := s3.New(sess) - - _, err := svc.PutBucketCors(&s3.PutBucketCorsInput{ - Bucket: bucket, - CORSConfiguration: &s3.CORSConfiguration{ - CORSRules: []*s3.CORSRule{&rule}, - }, - }) - // snippet-end:[s3.go.put_bucket_cors.call] - if err != nil { - return err - } - - return nil + // snippet-start:[s3.go.put_bucket_cors.rule] + rule := s3.CORSRule{ + AllowedHeaders: aws.StringSlice([]string{"Authorization"}), + AllowedOrigins: aws.StringSlice([]string{"*"}), + MaxAgeSeconds: aws.Int64(3000), + AllowedMethods: aws.StringSlice(methods), + } + // snippet-end:[s3.go.put_bucket_cors.rule] + + // snippet-start:[s3.go.put_bucket_cors.call] + svc := s3.New(sess) + + _, err := svc.PutBucketCors(&s3.PutBucketCorsInput{ + Bucket: bucket, + CORSConfiguration: &s3.CORSConfiguration{ + CORSRules: []*s3.CORSRule{&rule}, + }, + }) + // snippet-end:[s3.go.put_bucket_cors.call] + if err != nil { + return err + } + + return nil } // FilterMethods takes an array of strings and returns any that are HTTP methods // snippet-start:[s3.go.put_bucket_cors.filter] func FilterMethods(methods []string) []string { - filtered := make([]string, 0, len(methods)) - for _, m := range methods { - v := strings.ToUpper(m) - switch v { - case "POST", "GET", "PUT", "PATCH", "DELETE": - filtered = append(filtered, v) - } - } - - return filtered + filtered := make([]string, 0, len(methods)) + for _, m := range methods { + v := strings.ToUpper(m) + switch v { + case "POST", "GET", "PUT", "PATCH", "DELETE": + filtered = append(filtered, v) + } + } + + return filtered } // snippet-end:[s3.go.put_bucket_cors.filter] func main() { - // snippet-start:[s3.go.put_bucket_cors.args] - bucket := flag.String("b", "", "Bucket to set CORS on, (required)") - - flag.Parse() - - if *bucket == "" { - fmt.Println("You must supply the name of a bucket (-b BUCKET)") - return - } - - methods := FilterMethods(flag.Args()) - if len(methods) == 0 { - fmt.Println("You must supply at least one HTTP method: POST, GET, PUT, PATCH, or DELETE") - } - // snippet-end:[s3.go.put_bucket_cors.args] - - // snippet-start:[s3.go.put_bucket_cors.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.put_bucket_cors.session] - - err := SetCors(sess, bucket, methods) - if err != nil { - fmt.Println("Got an error setting CORS:") - fmt.Println(err) - return - } + // snippet-start:[s3.go.put_bucket_cors.args] + bucket := flag.String("b", "", "Bucket to set CORS on, (required)") + + flag.Parse() + + if *bucket == "" { + fmt.Println("You must supply the name of a bucket (-b BUCKET)") + return + } + + methods := FilterMethods(flag.Args()) + if len(methods) == 0 { + fmt.Println("You must supply at least one HTTP method: POST, GET, PUT, PATCH, or DELETE") + } + // snippet-end:[s3.go.put_bucket_cors.args] + + // snippet-start:[s3.go.put_bucket_cors.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.put_bucket_cors.session] + + err := SetCors(sess, bucket, methods) + if err != nil { + fmt.Println("Got an error setting CORS:") + fmt.Println(err) + return + } } + // snippet-end:[s3.go.put_bucket_cors] diff --git a/go/s3/SetCors/SetCors_test.go b/go/s3/SetCors/SetCors_test.go index d91a2dc54ea..1c23976bd5c 100644 --- a/go/s3/SetCors/SetCors_test.go +++ b/go/s3/SetCors/SetCors_test.go @@ -1,33 +1,22 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "testing" - "time" + "encoding/json" + "io/ioutil" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" - "github.com/google/uuid" + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` - Methods []string `json:"Methods"` + Bucket string `json:"Bucket"` + Methods []string `json:"Methods"` } var configFileName = "config.json" @@ -35,117 +24,117 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - if globalConfig.Methods == nil { - globalConfig.Methods = []string{"POST"} - } + if globalConfig.Methods == nil { + globalConfig.Methods = []string{"POST"} + } - t.Log("Bucket: " + globalConfig.Bucket) - t.Log("Methods: ", globalConfig.Methods) + t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Methods: ", globalConfig.Methods) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestSetCors(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - bucketCreated := false - - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Created bucket " + globalConfig.Bucket) - bucketCreated = true - } - - methods := FilterMethods(globalConfig.Methods) - if len(methods) == 0 { - methods = []string{"POST"} - } - - err = SetCors(sess, &globalConfig.Bucket, methods) - if err != nil { - t.Log("You must delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Added CORS for ", methods, "to bucket "+globalConfig.Bucket) - - if bucketCreated { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You must delete " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + bucketCreated := false + + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Created bucket " + globalConfig.Bucket) + bucketCreated = true + } + + methods := FilterMethods(globalConfig.Methods) + if len(methods) == 0 { + methods = []string{"POST"} + } + + err = SetCors(sess, &globalConfig.Bucket, methods) + if err != nil { + t.Log("You must delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Added CORS for ", methods, "to bucket "+globalConfig.Bucket) + + if bucketCreated { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You must delete " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted " + globalConfig.Bucket) + } } diff --git a/go/s3/SetDefaultEncryption/SetDefaultEncryption.go b/go/s3/SetDefaultEncryption/SetDefaultEncryption.go index 770a0ede7cb..8025e8e39be 100644 --- a/go/s3/SetDefaultEncryption/SetDefaultEncryption.go +++ b/go/s3/SetDefaultEncryption/SetDefaultEncryption.go @@ -1,88 +1,82 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.set_default_encryption] package main // snippet-start:[s3.go.set_default_encryption.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" ) + // snippet-end:[s3.go.set_default_encryption.imports] // AddKmsEncryption enforces encryption using a KMS key on a bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket -// kmsKeyID is the ID of a KMS key +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// kmsKeyID is the ID of a KMS key +// // Output: -// If success, nil -// Otherwise, an error from the call to PutBucketEncryption +// +// If success, nil +// Otherwise, an error from the call to PutBucketEncryption func AddKmsEncryption(sess *session.Session, bucket, kmsKeyID *string) error { - // snippet-start:[s3.go.set_default_encryption.call] - svc := s3.New(sess) + // snippet-start:[s3.go.set_default_encryption.call] + svc := s3.New(sess) - // Encrypt with KMS by default - defEnc := &s3.ServerSideEncryptionByDefault{ - KMSMasterKeyID: kmsKeyID, - SSEAlgorithm: aws.String(s3.ServerSideEncryptionAwsKms), - } - rule := &s3.ServerSideEncryptionRule{ApplyServerSideEncryptionByDefault: defEnc} - rules := []*s3.ServerSideEncryptionRule{rule} - serverConfig := &s3.ServerSideEncryptionConfiguration{Rules: rules} + // Encrypt with KMS by default + defEnc := &s3.ServerSideEncryptionByDefault{ + KMSMasterKeyID: kmsKeyID, + SSEAlgorithm: aws.String(s3.ServerSideEncryptionAwsKms), + } + rule := &s3.ServerSideEncryptionRule{ApplyServerSideEncryptionByDefault: defEnc} + rules := []*s3.ServerSideEncryptionRule{rule} + serverConfig := &s3.ServerSideEncryptionConfiguration{Rules: rules} - _, err := svc.PutBucketEncryption(&s3.PutBucketEncryptionInput{ - Bucket: bucket, - ServerSideEncryptionConfiguration: serverConfig, - }) - // snippet-end:[s3.go.set_default_encryption.call] - if err != nil { - return err - } + _, err := svc.PutBucketEncryption(&s3.PutBucketEncryptionInput{ + Bucket: bucket, + ServerSideEncryptionConfiguration: serverConfig, + }) + // snippet-end:[s3.go.set_default_encryption.call] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[s3.go.set_default_encryption.args] - bucket := flag.String("b", "", "The bucket") - kmsKeyID := flag.String("k", "", "The KMS key ID") - flag.Parse() + // snippet-start:[s3.go.set_default_encryption.args] + bucket := flag.String("b", "", "The bucket") + kmsKeyID := flag.String("k", "", "The KMS key ID") + flag.Parse() - if *bucket == "" || *kmsKeyID == "" { - fmt.Println("You must supply bucket (-b BUCKET) and KMS key ID (-k KEY)") - return - } - // snippet-end:[s3.go.set_default_encryption.args] + if *bucket == "" || *kmsKeyID == "" { + fmt.Println("You must supply bucket (-b BUCKET) and KMS key ID (-k KEY)") + return + } + // snippet-end:[s3.go.set_default_encryption.args] - // snippet-start:[s3.go.set_default_encryption.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.set_default_encryption.session] + // snippet-start:[s3.go.set_default_encryption.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.set_default_encryption.session] - err := AddKmsEncryption(sess, bucket, kmsKeyID) - if err != nil { - fmt.Println("Got an error adding default KMS encryption to bucket:") - fmt.Println(err) - return - } + err := AddKmsEncryption(sess, bucket, kmsKeyID) + if err != nil { + fmt.Println("Got an error adding default KMS encryption to bucket:") + fmt.Println(err) + return + } - fmt.Println("Bucket " + *bucket + " now has KMS encryption by default") + fmt.Println("Bucket " + *bucket + " now has KMS encryption by default") } + // snippet-end:[s3.go.set_default_encryption] diff --git a/go/s3/SetDefaultEncryption/SetDefaultEncryption_test.go b/go/s3/SetDefaultEncryption/SetDefaultEncryption_test.go index b4613c7ff0d..277a18466e1 100644 --- a/go/s3/SetDefaultEncryption/SetDefaultEncryption_test.go +++ b/go/s3/SetDefaultEncryption/SetDefaultEncryption_test.go @@ -1,36 +1,25 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "errors" - "io/ioutil" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - - "github.com/google/uuid" + "encoding/json" + "errors" + "io/ioutil" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` - KmsKeyID string `json:"KmsKeyID"` + Bucket string `json:"Bucket"` + KmsKeyID string `json:"KmsKeyID"` } var configFileName = "config.json" @@ -38,119 +27,119 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) - t.Log("KmsKeyID: " + globalConfig.KmsKeyID) + t.Log("Bucket: " + globalConfig.Bucket) + t.Log("KmsKeyID: " + globalConfig.KmsKeyID) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucket, - }) - - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - if err != nil { - return err - } - - _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucket, + }) + + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + if err != nil { + return err + } + + _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestSetDefaultEncryption(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - if globalConfig.KmsKeyID == "" { - t.Fatal(errors.New("You must supply an AWS KMS key ID in config.json")) - } + if globalConfig.KmsKeyID == "" { + t.Fatal(errors.New("You must supply an AWS KMS key ID in config.json")) + } - bucketCreated := false + bucketCreated := false - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } - t.Log("Created " + globalConfig.Bucket) - bucketCreated = true - } + t.Log("Created " + globalConfig.Bucket) + bucketCreated = true + } - err = AddKmsEncryption(sess, &globalConfig.Bucket, &globalConfig.KmsKeyID) - if err != nil { - t.Fatal(err) - } + err = AddKmsEncryption(sess, &globalConfig.Bucket, &globalConfig.KmsKeyID) + if err != nil { + t.Fatal(err) + } - t.Log("Added AMS KMS encryption to " + globalConfig.Bucket) + t.Log("Added AMS KMS encryption to " + globalConfig.Bucket) - if bucketCreated { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") - } + if bucketCreated { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete " + globalConfig.Bucket + " yourself") + } - t.Log("Deleted " + globalConfig.Bucket) - } + t.Log("Deleted " + globalConfig.Bucket) + } } diff --git a/go/s3/TLS/s3SetTls12.go b/go/s3/TLS/s3SetTls12.go index 99e72540160..f180990c3ea 100644 --- a/go/s3/TLS/s3SetTls12.go +++ b/go/s3/TLS/s3SetTls12.go @@ -1,127 +1,115 @@ -// snippet-comment:[The snippet tags are for the AWS SDK for Go Developer Guide. Do not remove.] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.set_tls_12] package main import ( - "crypto/tls" - "flag" - "fmt" - "net/http" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "golang.org/x/net/http2" + "crypto/tls" + "flag" + "fmt" + "net/http" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "golang.org/x/net/http2" ) // GetTLSVersion gets the version of TLS you have configured // snippet-start:[s3.go.get_tls_version] func GetTLSVersion(tr *http.Transport) string { - switch tr.TLSClientConfig.MinVersion { - case tls.VersionTLS10: - return "TLS 1.0" - case tls.VersionTLS11: - return "TLS 1.1" - case tls.VersionTLS12: - return "TLS 1.2" - case tls.VersionTLS13: - return "TLS 1.3" - } - - return "Unknown" + switch tr.TLSClientConfig.MinVersion { + case tls.VersionTLS10: + return "TLS 1.0" + case tls.VersionTLS11: + return "TLS 1.1" + case tls.VersionTLS12: + return "TLS 1.2" + case tls.VersionTLS13: + return "TLS 1.3" + } + + return "Unknown" } // snippet-end:[s3.go.get_tls_version] // ConfirmBucketItemExists returns nil if the bucket and item can be accessed func ConfirmBucketItemExists(sess *session.Session, bucket *string, item *string) error { - // snippet-start:[s3.go.set_tls_12_client] - svc := s3.New(sess) - _, err := svc.HeadObject(&s3.HeadObjectInput{ - Bucket: bucket, - Key: item, - }) - // snippet-end:[s3.go.set_tls_12_client] - if err != nil { - return err - } - - return nil + // snippet-start:[s3.go.set_tls_12_client] + svc := s3.New(sess) + _, err := svc.HeadObject(&s3.HeadObjectInput{ + Bucket: bucket, + Key: item, + }) + // snippet-end:[s3.go.set_tls_12_client] + if err != nil { + return err + } + + return nil } func main() { - bucket := flag.String("b", "", "The bucket to check") - object := flag.String("o", "", "The bucket object to check") - region := flag.String("r", "us-west-2", "The region where the bucket lives") - goV112 := flag.Bool("v", false, "Whether the Go version is prior to 1.13") - - flag.Parse() - - if *bucket == "" || *object == "" { - fmt.Println("You must supply a bucket name (-b BUCKET) and item name (-o OBJECT)") - return - } - - // snippet-start:[s3.go.set_tls_12_transport] - tr := &http.Transport{ - TLSClientConfig: &tls.Config{ - MinVersion: tls.VersionTLS12, - }, - } - // snippet-end:[s3.go.set_tls_12_transport] - - if *goV112 { - // snippet-start:[s3.go.set_tls_12_cfg_112] - err := http2.ConfigureTransport(tr) - if err != nil { - fmt.Println("Got an error configuring HTTP transport") - fmt.Println(err) - return - } - // snippet-end:[s3.go.set_tls_12_cfg_112] - } else { - // snippet-start:[s3.go.set_tls_12_cfg_113] - tr.ForceAttemptHTTP2 = true - // snippet-end:[s3.go.set_tls_12_cfg_113] - } - - // snippet-start:[s3.go.set_tls_12_session] - client := http.Client{Transport: tr} - - sess := session.Must(session.NewSession(&aws.Config{ - Region: region, - HTTPClient: &client, - })) - // snippet-end:[s3.go.set_tls_12_session] - - // Confirm TLS version - // snippet-start:[s3.go.get_tls_version_call] - s3Client := s3.New(sess) - if tr, ok := s3Client.Config.HTTPClient.Transport.(*http.Transport); ok { - fmt.Println("Client uses " + GetTLSVersion(tr)) - } - // snippet-end:[s3.go.get_tls_version_call] - - err := ConfirmBucketItemExists(sess, bucket, object) - if err != nil { - fmt.Println("Could not confirm whether bucket and item exists") - return - } - - fmt.Println("Bucket " + *bucket + " and item " + *object + " can be accessed") + bucket := flag.String("b", "", "The bucket to check") + object := flag.String("o", "", "The bucket object to check") + region := flag.String("r", "us-west-2", "The region where the bucket lives") + goV112 := flag.Bool("v", false, "Whether the Go version is prior to 1.13") + + flag.Parse() + + if *bucket == "" || *object == "" { + fmt.Println("You must supply a bucket name (-b BUCKET) and item name (-o OBJECT)") + return + } + + // snippet-start:[s3.go.set_tls_12_transport] + tr := &http.Transport{ + TLSClientConfig: &tls.Config{ + MinVersion: tls.VersionTLS12, + }, + } + // snippet-end:[s3.go.set_tls_12_transport] + + if *goV112 { + // snippet-start:[s3.go.set_tls_12_cfg_112] + err := http2.ConfigureTransport(tr) + if err != nil { + fmt.Println("Got an error configuring HTTP transport") + fmt.Println(err) + return + } + // snippet-end:[s3.go.set_tls_12_cfg_112] + } else { + // snippet-start:[s3.go.set_tls_12_cfg_113] + tr.ForceAttemptHTTP2 = true + // snippet-end:[s3.go.set_tls_12_cfg_113] + } + + // snippet-start:[s3.go.set_tls_12_session] + client := http.Client{Transport: tr} + + sess := session.Must(session.NewSession(&aws.Config{ + Region: region, + HTTPClient: &client, + })) + // snippet-end:[s3.go.set_tls_12_session] + + // Confirm TLS version + // snippet-start:[s3.go.get_tls_version_call] + s3Client := s3.New(sess) + if tr, ok := s3Client.Config.HTTPClient.Transport.(*http.Transport); ok { + fmt.Println("Client uses " + GetTLSVersion(tr)) + } + // snippet-end:[s3.go.get_tls_version_call] + + err := ConfirmBucketItemExists(sess, bucket, object) + if err != nil { + fmt.Println("Could not confirm whether bucket and item exists") + return + } + + fmt.Println("Bucket " + *bucket + " and item " + *object + " can be accessed") } // snippet-end:[s3.go.set_tls_12] diff --git a/go/s3/TLS/s3SetTls12_test.go b/go/s3/TLS/s3SetTls12_test.go index 203ae15f7ac..1e4b823dae7 100644 --- a/go/s3/TLS/s3SetTls12_test.go +++ b/go/s3/TLS/s3SetTls12_test.go @@ -1,44 +1,33 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "crypto/tls" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "strings" - "testing" - - "github.com/google/uuid" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - - "golang.org/x/net/http2" + "crypto/tls" + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "strings" + "testing" + + "github.com/google/uuid" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + + "golang.org/x/net/http2" ) type Config struct { - Bucket string `json:"Bucket"` - Object string `json:"Object"` - Region string `json:"Region"` - GoVersion float32 `json:"GoVersion"` - BucketCreated bool + Bucket string `json:"Bucket"` + Object string `json:"Object"` + Region string `json:"Region"` + GoVersion float32 `json:"GoVersion"` + BucketCreated bool } var configFileName = "config.json" @@ -46,150 +35,150 @@ var globalConfig Config var defaultRegion = "us-west-2" func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - if globalConfig.Region == "" { - globalConfig.Region = defaultRegion - } + if globalConfig.Region == "" { + globalConfig.Region = defaultRegion + } - t.Log("Region: " + globalConfig.Region) - t.Log("GoVersion: " + fmt.Sprintf("%f", globalConfig.GoVersion)) + t.Log("Region: " + globalConfig.Region) + t.Log("GoVersion: " + fmt.Sprintf("%f", globalConfig.GoVersion)) - return nil + return nil } func createBucketAndObject(sess *session.Session, bucketName *string, itemName *string) error { - svc := s3.New(sess) - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucketName, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucketName, - }) - if err != nil { - return err - } - - _, err = svc.PutObject(&s3.PutObjectInput{ - Body: strings.NewReader("Hello World!"), - Bucket: bucketName, - Key: itemName, - }) - - return err + svc := s3.New(sess) + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucketName, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucketName, + }) + if err != nil { + return err + } + + _, err = svc.PutObject(&s3.PutObjectInput{ + Body: strings.NewReader("Hello World!"), + Bucket: bucketName, + Key: itemName, + }) + + return err } func deleteBucket(sess *session.Session, bucketName *string) error { - svc := s3.New(sess) - - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucketName, - }) - - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - if err != nil { - return err - } - - _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucketName, - }) - if err != nil { - return err - } - - return svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucketName, - }) + svc := s3.New(sess) + + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucketName, + }) + + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + if err != nil { + return err + } + + _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucketName, + }) + if err != nil { + return err + } + + return svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucketName, + }) } func TestTLSVersion(t *testing.T) { - err := populateConfiguration(t) - if err != nil { - t.Fatal("Could not get configuration values") - } - - // Create HTTP client with minimum TLS version - tr := &http.Transport{ - TLSClientConfig: &tls.Config{ - MinVersion: tls.VersionTLS12, - }, - } - - minGo := (float32)(1.12) - - if globalConfig.GoVersion > minGo { - tr.ForceAttemptHTTP2 = true - t.Log("Created TLS 1.2 for Go version 1.13") - } else { - err := http2.ConfigureTransport(tr) - t.Log("Created TLS 1.12 for Go version 1.12 (or previous)") - if err != nil { - t.Fatal(err) - } - } - - // Create an HTTP client with the configured transport. - client := http.Client{Transport: tr} - - // Create the SDK's session with the custom HTTP client. - sess := session.Must(session.NewSession(&aws.Config{ - Region: &globalConfig.Region, - HTTPClient: &client, - })) - - s3Client := s3.New(sess) - - if tr, ok := s3Client.Config.HTTPClient.Transport.(*http.Transport); ok { - t.Log("Client uses " + GetTLSVersion(tr)) - } - - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "testbucket-" + id.String() - - if globalConfig.Object == "" { - globalConfig.Object = "testitem" - } - - // Create the bucket and object - err := createBucketAndObject(sess, &globalConfig.Bucket, &globalConfig.Object) - if err != nil { - t.Fatal(err) - } - - t.Log("Created bucket: " + globalConfig.Bucket) - t.Log("With item : " + globalConfig.Object) - } - - err = ConfirmBucketItemExists(sess, &globalConfig.Bucket, &globalConfig.Object) - if err != nil { - t.Fatal(err) - } - - t.Log("Bucket " + globalConfig.Bucket + " and object " + globalConfig.Object + " can be accessed") - - if globalConfig.BucketCreated { - err = deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You will have to delete bucket " + globalConfig.Bucket + " yourself") - t.Fatal(err) - } - - t.Log("Deleted bucket: " + globalConfig.Bucket) - } + err := populateConfiguration(t) + if err != nil { + t.Fatal("Could not get configuration values") + } + + // Create HTTP client with minimum TLS version + tr := &http.Transport{ + TLSClientConfig: &tls.Config{ + MinVersion: tls.VersionTLS12, + }, + } + + minGo := (float32)(1.12) + + if globalConfig.GoVersion > minGo { + tr.ForceAttemptHTTP2 = true + t.Log("Created TLS 1.2 for Go version 1.13") + } else { + err := http2.ConfigureTransport(tr) + t.Log("Created TLS 1.12 for Go version 1.12 (or previous)") + if err != nil { + t.Fatal(err) + } + } + + // Create an HTTP client with the configured transport. + client := http.Client{Transport: tr} + + // Create the SDK's session with the custom HTTP client. + sess := session.Must(session.NewSession(&aws.Config{ + Region: &globalConfig.Region, + HTTPClient: &client, + })) + + s3Client := s3.New(sess) + + if tr, ok := s3Client.Config.HTTPClient.Transport.(*http.Transport); ok { + t.Log("Client uses " + GetTLSVersion(tr)) + } + + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "testbucket-" + id.String() + + if globalConfig.Object == "" { + globalConfig.Object = "testitem" + } + + // Create the bucket and object + err := createBucketAndObject(sess, &globalConfig.Bucket, &globalConfig.Object) + if err != nil { + t.Fatal(err) + } + + t.Log("Created bucket: " + globalConfig.Bucket) + t.Log("With item : " + globalConfig.Object) + } + + err = ConfirmBucketItemExists(sess, &globalConfig.Bucket, &globalConfig.Object) + if err != nil { + t.Fatal(err) + } + + t.Log("Bucket " + globalConfig.Bucket + " and object " + globalConfig.Object + " can be accessed") + + if globalConfig.BucketCreated { + err = deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You will have to delete bucket " + globalConfig.Bucket + " yourself") + t.Fatal(err) + } + + t.Log("Deleted bucket: " + globalConfig.Bucket) + } } diff --git a/go/s3/UploadDirectory/UploadDirectory.go b/go/s3/UploadDirectory/UploadDirectory.go index 90f517afe23..96ee2157380 100644 --- a/go/s3/UploadDirectory/UploadDirectory.go +++ b/go/s3/UploadDirectory/UploadDirectory.go @@ -1,142 +1,136 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.upload_directory] package main // snippet-start:[s3.go.upload_directory.imports] import ( - "flag" - "fmt" - "os" - "path/filepath" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3/s3manager" + "flag" + "fmt" + "os" + "path/filepath" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3/s3manager" ) + // snippet-end:[s3.go.upload_directory.imports] // DirectoryIterator represents an iterator of a specified directory type DirectoryIterator struct { - filePaths []string - bucket string - next struct { - path string - f *os.File - } - err error + filePaths []string + bucket string + next struct { + path string + f *os.File + } + err error } // const exitError = 1 // UploadDirectory uploads the files in a directory to a bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket -// path is the path to the directory to upload +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// path is the path to the directory to upload +// // Output: -// If success, nil -// Otherwise, an error from the call to UploadWithIterator +// +// If success, nil +// Otherwise, an error from the call to UploadWithIterator func UploadDirectory(sess *session.Session, bucket *string, path *string) error { - di := NewDirectoryIterator(bucket, path) - uploader := s3manager.NewUploader(sess) + di := NewDirectoryIterator(bucket, path) + uploader := s3manager.NewUploader(sess) - err := uploader.UploadWithIterator(aws.BackgroundContext(), di) - if err != nil { - return err - } + err := uploader.UploadWithIterator(aws.BackgroundContext(), di) + if err != nil { + return err + } - return nil + return nil } // NewDirectoryIterator builds a new DirectoryIterator func NewDirectoryIterator(bucket *string, dir *string) s3manager.BatchUploadIterator { - var paths []string - filepath.Walk(*dir, func(path string, info os.FileInfo, err error) error { - if !info.IsDir() { - paths = append(paths, path) - } - return nil - }) - - return &DirectoryIterator{ - filePaths: paths, - bucket: *bucket, - } + var paths []string + filepath.Walk(*dir, func(path string, info os.FileInfo, err error) error { + if !info.IsDir() { + paths = append(paths, path) + } + return nil + }) + + return &DirectoryIterator{ + filePaths: paths, + bucket: *bucket, + } } // Next returns whether next file exists func (di *DirectoryIterator) Next() bool { - if len(di.filePaths) == 0 { - di.next.f = nil - return false - } - - f, err := os.Open(di.filePaths[0]) - di.err = err - di.next.f = f - di.next.path = di.filePaths[0] - di.filePaths = di.filePaths[1:] - - return true && di.Err() == nil + if len(di.filePaths) == 0 { + di.next.f = nil + return false + } + + f, err := os.Open(di.filePaths[0]) + di.err = err + di.next.f = f + di.next.path = di.filePaths[0] + di.filePaths = di.filePaths[1:] + + return true && di.Err() == nil } // Err returns error of DirectoryIterator func (di *DirectoryIterator) Err() error { - return di.err + return di.err } // UploadObject uploads a file func (di *DirectoryIterator) UploadObject() s3manager.BatchUploadObject { - f := di.next.f - return s3manager.BatchUploadObject{ - Object: &s3manager.UploadInput{ - Bucket: &di.bucket, - Key: &di.next.path, - Body: f, - }, - After: func() error { - return f.Close() - }, - } + f := di.next.f + return s3manager.BatchUploadObject{ + Object: &s3manager.UploadInput{ + Bucket: &di.bucket, + Key: &di.next.path, + Body: f, + }, + After: func() error { + return f.Close() + }, + } } func main() { - // snippet-start:[s3.go.upload_directory.args] - bucket := flag.String("b", "", "The name of the bucket") - directory := flag.String("d", "", "The directory to upload") - flag.Parse() - - if *bucket == "" || *directory == "" { - fmt.Println("You must supply the bucket name (-b BUCKET) and directory path (-d DIRECTORY)") - return - } - // snippet-end:[s3.go.upload_directory.args] - - // snippet-start:[s3.go.upload_directory.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.upload_directory.session] - - err := UploadDirectory(sess, bucket, directory) - if err != nil { - fmt.Println("Got an error uploading directory " + *directory + " to bucket " + *bucket) - return - } - - fmt.Println("Uploaded directory " + *directory + " to bucket " + *bucket) + // snippet-start:[s3.go.upload_directory.args] + bucket := flag.String("b", "", "The name of the bucket") + directory := flag.String("d", "", "The directory to upload") + flag.Parse() + + if *bucket == "" || *directory == "" { + fmt.Println("You must supply the bucket name (-b BUCKET) and directory path (-d DIRECTORY)") + return + } + // snippet-end:[s3.go.upload_directory.args] + + // snippet-start:[s3.go.upload_directory.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.upload_directory.session] + + err := UploadDirectory(sess, bucket, directory) + if err != nil { + fmt.Println("Got an error uploading directory " + *directory + " to bucket " + *bucket) + return + } + + fmt.Println("Uploaded directory " + *directory + " to bucket " + *bucket) } + // snippet-end:[s3.go.upload_directory] diff --git a/go/s3/UploadDirectory/UploadDirectory_test.go b/go/s3/UploadDirectory/UploadDirectory_test.go index d485c700003..1764b7f03f6 100644 --- a/go/s3/UploadDirectory/UploadDirectory_test.go +++ b/go/s3/UploadDirectory/UploadDirectory_test.go @@ -1,36 +1,25 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "fmt" - "io/ioutil" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - - "github.com/google/uuid" + "encoding/json" + "fmt" + "io/ioutil" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` - Directory string `json:"Directory"` + Bucket string `json:"Bucket"` + Directory string `json:"Directory"` } var configFileName = "config.json" @@ -38,120 +27,120 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) - t.Log("Directory: " + globalConfig.Directory) + t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Directory: " + globalConfig.Directory) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucket, - }) - - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - if err != nil { - return err - } - - _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucket, + }) + + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + if err != nil { + return err + } + + _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestUploadDirectory(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - bucketCreated := false - - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Created bucket " + globalConfig.Bucket) - bucketCreated = true - } - - if globalConfig.Directory == "" { - globalConfig.Directory = "dummy" - } - - err = UploadDirectory(sess, &globalConfig.Bucket, &globalConfig.Directory) - if err != nil { - fmt.Println("Got an error uploading directory " + globalConfig.Directory + " to bucket " + globalConfig.Bucket) - return - } - - fmt.Println("Uploaded directory " + globalConfig.Directory + " to bucket " + globalConfig.Bucket) - - if bucketCreated { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Deleted bucket " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + bucketCreated := false + + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Created bucket " + globalConfig.Bucket) + bucketCreated = true + } + + if globalConfig.Directory == "" { + globalConfig.Directory = "dummy" + } + + err = UploadDirectory(sess, &globalConfig.Bucket, &globalConfig.Directory) + if err != nil { + fmt.Println("Got an error uploading directory " + globalConfig.Directory + " to bucket " + globalConfig.Bucket) + return + } + + fmt.Println("Uploaded directory " + globalConfig.Directory + " to bucket " + globalConfig.Bucket) + + if bucketCreated { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Deleted bucket " + globalConfig.Bucket) + } } diff --git a/go/s3/UploadObject/UploadObject.go b/go/s3/UploadObject/UploadObject.go index defa664b0ab..c4e33ab7787 100644 --- a/go/s3/UploadObject/UploadObject.go +++ b/go/s3/UploadObject/UploadObject.go @@ -1,89 +1,83 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.upload_object] package main // snippet-start:[s3.go.upload_object.imports] import ( - "flag" - "fmt" - "os" + "flag" + "fmt" + "os" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3/s3manager" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3/s3manager" ) + // snippet-end:[s3.go.upload_object.imports] // PutFile uploads a file to a bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket -// filename is the name of the file +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// filename is the name of the file +// // Output: -// If success, nil -// Otherwise, an error from the call to Open or Upload +// +// If success, nil +// Otherwise, an error from the call to Open or Upload func PutFile(sess *session.Session, bucket *string, filename *string) error { - // snippet-start:[s3.go.upload_object.open] - file, err := os.Open(*filename) - // snippet-end:[s3.go.upload_object.open] - if err != nil { - fmt.Println("Unable to open file " + *filename) - return err - } + // snippet-start:[s3.go.upload_object.open] + file, err := os.Open(*filename) + // snippet-end:[s3.go.upload_object.open] + if err != nil { + fmt.Println("Unable to open file " + *filename) + return err + } - defer file.Close() + defer file.Close() - // snippet-start:[s3.go.upload_object.call] - uploader := s3manager.NewUploader(sess) + // snippet-start:[s3.go.upload_object.call] + uploader := s3manager.NewUploader(sess) - _, err = uploader.Upload(&s3manager.UploadInput{ - Bucket: bucket, - Key: filename, - Body: file, - }) - // snippet-end:[s3.go.upload_object.call] - if err != nil { - return err - } + _, err = uploader.Upload(&s3manager.UploadInput{ + Bucket: bucket, + Key: filename, + Body: file, + }) + // snippet-end:[s3.go.upload_object.call] + if err != nil { + return err + } - return nil + return nil } func main() { - // snippet-start:[s3.go.upload_object.args] - bucket := flag.String("b", "", "The bucket to upload the file to") - filename := flag.String("f", "", "The file to upload") - flag.Parse() + // snippet-start:[s3.go.upload_object.args] + bucket := flag.String("b", "", "The bucket to upload the file to") + filename := flag.String("f", "", "The file to upload") + flag.Parse() - if *bucket == "" || *filename == "" { - fmt.Println("You must supply a bucket name (-b BUCKET) and file name (-f FILE)") - return - } - // snippet-end:[s3.go.upload_object.args] + if *bucket == "" || *filename == "" { + fmt.Println("You must supply a bucket name (-b BUCKET) and file name (-f FILE)") + return + } + // snippet-end:[s3.go.upload_object.args] - // snippet-start:[s3.go.upload_object.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.upload_object.session] + // snippet-start:[s3.go.upload_object.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.upload_object.session] - err := PutFile(sess, bucket, filename) - if err != nil { - fmt.Println("Got error uploading file:") - fmt.Println(err) - return - } + err := PutFile(sess, bucket, filename) + if err != nil { + fmt.Println("Got error uploading file:") + fmt.Println(err) + return + } } + // snippet-end:[s3.go.upload_object] diff --git a/go/s3/UploadObject/UploadObject_test.go b/go/s3/UploadObject/UploadObject_test.go index 51518f5c202..d330be179bb 100644 --- a/go/s3/UploadObject/UploadObject_test.go +++ b/go/s3/UploadObject/UploadObject_test.go @@ -1,35 +1,24 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "testing" - "time" + "encoding/json" + "io/ioutil" + "testing" + "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" - "github.com/google/uuid" + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` - Filename string `json:"Filename"` + Bucket string `json:"Bucket"` + Filename string `json:"Filename"` } var configFileName = "config.json" @@ -37,120 +26,120 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) - t.Log("Filename: " + globalConfig.Filename) + t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Filename: " + globalConfig.Filename) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucket, - }) - - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - if err != nil { - return err - } - - _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucket, + }) + + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + if err != nil { + return err + } + + _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestUploadObject(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - createdBucket := false - - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() - - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } - - t.Log("Created bucket " + globalConfig.Bucket) - createdBucket = true - } - - if globalConfig.Filename == "" { - globalConfig.Filename = "test.txt" - } - - err = PutFile(sess, &globalConfig.Bucket, &globalConfig.Filename) - if err != nil { - t.Fatal(err) - } - - t.Log("Uploaded " + globalConfig.Filename + " to bucket " + globalConfig.Bucket) - - if createdBucket { - // Delete bucket and contents - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You must delete bucket " + globalConfig.Bucket + " yourself") - } - - t.Log("Deleted bucket " + globalConfig.Bucket) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + createdBucket := false + + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() + + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } + + t.Log("Created bucket " + globalConfig.Bucket) + createdBucket = true + } + + if globalConfig.Filename == "" { + globalConfig.Filename = "test.txt" + } + + err = PutFile(sess, &globalConfig.Bucket, &globalConfig.Filename) + if err != nil { + t.Fatal(err) + } + + t.Log("Uploaded " + globalConfig.Filename + " to bucket " + globalConfig.Bucket) + + if createdBucket { + // Delete bucket and contents + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You must delete bucket " + globalConfig.Bucket + " yourself") + } + + t.Log("Deleted bucket " + globalConfig.Bucket) + } } diff --git a/go/s3/UploadStream/UploadStream.go b/go/s3/UploadStream/UploadStream.go index f7f7777dc9b..0a45e65139b 100644 --- a/go/s3/UploadStream/UploadStream.go +++ b/go/s3/UploadStream/UploadStream.go @@ -1,101 +1,95 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.go.upload_stream] package main // snippet-start:[s3.go.upload_stream.imports] import ( - "compress/gzip" - "flag" - "fmt" - "io" - "os" - - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3/s3manager" + "compress/gzip" + "flag" + "fmt" + "io" + "os" + + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3/s3manager" ) + // snippet-end:[s3.go.upload_stream.imports] // UploadStream uploads a stream for a file to a bucket // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// bucket is the name of the bucket -// key is the name of the object in the bucket -// filename is the name of the file to stream to the bucket +// +// sess is the current session, which provides configuration for the SDK's service clients +// bucket is the name of the bucket +// key is the name of the object in the bucket +// filename is the name of the file to stream to the bucket +// // Output: -// If success, nil -// Otherwise, an error from the call to Open or Upload +// +// If success, nil +// Otherwise, an error from the call to Open or Upload func UploadStream(sess *session.Session, bucket *string, key *string, filename *string) error { - // snippet-start:[s3.go.upload_stream.call] - file, err := os.Open(*filename) - if err != nil { - return err - } - - reader, writer := io.Pipe() - - go func() { - gw := gzip.NewWriter(writer) - _, err := io.Copy(gw, file) - if err != nil { - return - } - file.Close() - gw.Close() - writer.Close() - }() - - uploader := s3manager.NewUploader(sess) - - _, err = uploader.Upload(&s3manager.UploadInput{ - Body: reader, - Bucket: bucket, - Key: key, - }) - // snippet-end:[s3.go.upload_stream.call] - if err != nil { - return err - } - - return nil + // snippet-start:[s3.go.upload_stream.call] + file, err := os.Open(*filename) + if err != nil { + return err + } + + reader, writer := io.Pipe() + + go func() { + gw := gzip.NewWriter(writer) + _, err := io.Copy(gw, file) + if err != nil { + return + } + file.Close() + gw.Close() + writer.Close() + }() + + uploader := s3manager.NewUploader(sess) + + _, err = uploader.Upload(&s3manager.UploadInput{ + Body: reader, + Bucket: bucket, + Key: key, + }) + // snippet-end:[s3.go.upload_stream.call] + if err != nil { + return err + } + + return nil } func main() { - // snippet-start:[s3.go.upload_stream.args] - bucket := flag.String("b", "", "The bucket to which the stream is uploaded") - filename := flag.String("f", "", "The file to upload to the bucket") - key := flag.String("k", "", "The name of the object in the bucket") - flag.Parse() - - if *bucket == "" || *filename == "" || *key == "" { - fmt.Println("You must supply a bucket name (-b BUCKET), filename (-f FILENAME), and key value (-k KEY)") - return - } - - // snippet-end:[s3.go.upload_stream.args] - - // snippet-start:[s3.go.upload_stream.session] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[s3.go.upload_stream.session] - - err := UploadStream(sess, bucket, key, filename) - if err != nil { - fmt.Println("Failed to upload " + *filename + " to bucket " + *bucket) - } - - fmt.Println("Successfully uploaded " + *filename + " to " + *bucket) + // snippet-start:[s3.go.upload_stream.args] + bucket := flag.String("b", "", "The bucket to which the stream is uploaded") + filename := flag.String("f", "", "The file to upload to the bucket") + key := flag.String("k", "", "The name of the object in the bucket") + flag.Parse() + + if *bucket == "" || *filename == "" || *key == "" { + fmt.Println("You must supply a bucket name (-b BUCKET), filename (-f FILENAME), and key value (-k KEY)") + return + } + + // snippet-end:[s3.go.upload_stream.args] + + // snippet-start:[s3.go.upload_stream.session] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[s3.go.upload_stream.session] + + err := UploadStream(sess, bucket, key, filename) + if err != nil { + fmt.Println("Failed to upload " + *filename + " to bucket " + *bucket) + } + + fmt.Println("Successfully uploaded " + *filename + " to " + *bucket) } + // snippet-end:[s3.go.upload_stream] diff --git a/go/s3/UploadStream/UploadStream_test.go b/go/s3/UploadStream/UploadStream_test.go index e9821e97ca2..669184c2f56 100644 --- a/go/s3/UploadStream/UploadStream_test.go +++ b/go/s3/UploadStream/UploadStream_test.go @@ -1,35 +1,24 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "testing" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3manager" - "github.com/google/uuid" + "encoding/json" + "io/ioutil" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + "github.com/google/uuid" ) type Config struct { - Bucket string `json:"Bucket"` - Filename string `json:"Filename"` - Key string `json:"Key"` + Bucket string `json:"Bucket"` + Filename string `json:"Filename"` + Key string `json:"Key"` } var configFileName = "config.json" @@ -37,124 +26,124 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - text := string(content) + text := string(content) - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Bucket: " + globalConfig.Bucket) - t.Log("Filename: " + globalConfig.Filename) - t.Log("Key: " + globalConfig.Key) + t.Log("Bucket: " + globalConfig.Bucket) + t.Log("Filename: " + globalConfig.Filename) + t.Log("Key: " + globalConfig.Key) - return nil + return nil } func createBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - _, err := svc.CreateBucket(&s3.CreateBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + _, err := svc.CreateBucket(&s3.CreateBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func deleteBucket(sess *session.Session, bucket *string) error { - svc := s3.New(sess) - - iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ - Bucket: bucket, - }) - - err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) - if err != nil { - return err - } - - _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ - Bucket: bucket, - }) - if err != nil { - return err - } - - return nil + svc := s3.New(sess) + + iter := s3manager.NewDeleteListIterator(svc, &s3.ListObjectsInput{ + Bucket: bucket, + }) + + err := s3manager.NewBatchDeleteWithClient(svc).Delete(aws.BackgroundContext(), iter) + if err != nil { + return err + } + + _, err = svc.DeleteBucket(&s3.DeleteBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + err = svc.WaitUntilBucketNotExists(&s3.HeadBucketInput{ + Bucket: bucket, + }) + if err != nil { + return err + } + + return nil } func TestUploadStream(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) - createdBucket := false + createdBucket := false - if globalConfig.Bucket == "" { - id := uuid.New() - globalConfig.Bucket = "test-bucket-" + id.String() + if globalConfig.Bucket == "" { + id := uuid.New() + globalConfig.Bucket = "test-bucket-" + id.String() - err := createBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Fatal(err) - } + err := createBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Fatal(err) + } - t.Log("Created bucket " + globalConfig.Bucket) - createdBucket = true - } + t.Log("Created bucket " + globalConfig.Bucket) + createdBucket = true + } - if globalConfig.Filename == "" { - globalConfig.Filename = "test.txt" - } + if globalConfig.Filename == "" { + globalConfig.Filename = "test.txt" + } - if globalConfig.Key == "" { - globalConfig.Key = "test.txt" - } + if globalConfig.Key == "" { + globalConfig.Key = "test.txt" + } - err = UploadStream(sess, &globalConfig.Bucket, &globalConfig.Key, &globalConfig.Filename) - if err != nil { - t.Fatal(err) - } + err = UploadStream(sess, &globalConfig.Bucket, &globalConfig.Key, &globalConfig.Filename) + if err != nil { + t.Fatal(err) + } - t.Log("Uploaded file " + globalConfig.Filename + " to bucket " + globalConfig.Bucket + " with key " + globalConfig.Key) + t.Log("Uploaded file " + globalConfig.Filename + " to bucket " + globalConfig.Bucket + " with key " + globalConfig.Key) - if createdBucket { - err := deleteBucket(sess, &globalConfig.Bucket) - if err != nil { - t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") - } + if createdBucket { + err := deleteBucket(sess, &globalConfig.Bucket) + if err != nil { + t.Log("You'll have to delete bucket " + globalConfig.Bucket + " yourself") + } - t.Log("Deleted bucket " + globalConfig.Bucket) - } + t.Log("Deleted bucket " + globalConfig.Bucket) + } } diff --git a/go/sqs/ChangeMsgVisibility/ChangeMsgVisibility.go b/go/sqs/ChangeMsgVisibility/ChangeMsgVisibility.go index 086a890fb64..0bf78fc58ea 100644 --- a/go/sqs/ChangeMsgVisibility/ChangeMsgVisibility.go +++ b/go/sqs/ChangeMsgVisibility/ChangeMsgVisibility.go @@ -1,123 +1,120 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sqs.go.change_message_visibility] package main // snippet-start:[sqs.go.change_message_visibility.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) + // snippet-end:[sqs.go.change_message_visibility.imports] // GetQueueURL gets the URL of an Amazon SQS queue // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// queueName is the name of the queue +// +// sess is the current session, which provides configuration for the SDK's service clients +// queueName is the name of the queue +// // Output: -// If success, the URL of the queue and nil -// Otherwise, an empty string and an error from the call to +// +// If success, the URL of the queue and nil +// Otherwise, an empty string and an error from the call to func GetQueueURL(sess *session.Session, queue *string) (*sqs.GetQueueUrlOutput, error) { - // Create an SQS service client - svc := sqs.New(sess) + // Create an SQS service client + svc := sqs.New(sess) - urlResult, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ - QueueName: queue, - }) - if err != nil { - return nil, err - } + urlResult, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ + QueueName: queue, + }) + if err != nil { + return nil, err + } - return urlResult, nil + return urlResult, nil } // SetMsgVisibility sets the visibility timeout for a message in an SQS queue // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// handle is the receipt handle of the message -// queueURL is the URL of the queue -// visibility is the duration, in seconds, while messages are in the queue, but not available +// +// sess is the current session, which provides configuration for the SDK's service clients +// handle is the receipt handle of the message +// queueURL is the URL of the queue +// visibility is the duration, in seconds, while messages are in the queue, but not available +// // Output: -// If success, nil -// Otherwise, an error from the call to ReceiveQueue +// +// If success, nil +// Otherwise, an error from the call to ReceiveQueue func SetMsgVisibility(sess *session.Session, handle *string, queueURL *string, visibility *int64) error { - // Create an SQS service client - svc := sqs.New(sess) - - // snippet-start:[sqs.go.change_message_visibility.op] - _, err := svc.ChangeMessageVisibility(&sqs.ChangeMessageVisibilityInput{ - ReceiptHandle: handle, - QueueUrl: queueURL, - VisibilityTimeout: visibility, - }) - // snippet-end:[sqs.go.change_message_visibility.op] - if err != nil { - return err - } - - return nil + // Create an SQS service client + svc := sqs.New(sess) + + // snippet-start:[sqs.go.change_message_visibility.op] + _, err := svc.ChangeMessageVisibility(&sqs.ChangeMessageVisibilityInput{ + ReceiptHandle: handle, + QueueUrl: queueURL, + VisibilityTimeout: visibility, + }) + // snippet-end:[sqs.go.change_message_visibility.op] + if err != nil { + return err + } + + return nil } func main() { - // snippet-start:[sqs.go.change_message_visibility.args] - queue := flag.String("q", "", "The name of the queue") - handle := flag.String("h", "", "The receipt handle of the message") - visibility := flag.Int64("v", 30, "The duration, in seconds, that the message is not visible to other consumers") - flag.Parse() - - if *queue == "" || *handle == "" { - fmt.Println("You must supply a queue name (-q QUEUE) and message receipt handle (-h HANDLE)") - return - } - - if *visibility < 0 { - *visibility = 0 - } - - if *visibility > 12*60*60 { - *visibility = 12 * 60 * 60 - } - // snippet-end:[sqs.go.change_message_visibility.args] - - // Create a session that gets credential values from ~/.aws/credentials - // and the default Region from ~/.aws/config - // snippet-start:[sqs.go.change_message_visibility.sess] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[sqs.go.change_message_visibility.sess] - - // Get URL of queue - urlResult, err := GetQueueURL(sess, queue) - if err != nil { - fmt.Println("Got an error getting the queue URL:") - fmt.Println(err) - return - } - - // snippet-start:[sqs.go.change_message_visibility.url] - queueURL := urlResult.QueueUrl - // snippet-end:[sqs.go.change_message_visibility.url] - - err = SetMsgVisibility(sess, handle, queueURL, visibility) - if err != nil { - fmt.Println("Got an error setting the visibility of the message:") - fmt.Println(err) - return - } + // snippet-start:[sqs.go.change_message_visibility.args] + queue := flag.String("q", "", "The name of the queue") + handle := flag.String("h", "", "The receipt handle of the message") + visibility := flag.Int64("v", 30, "The duration, in seconds, that the message is not visible to other consumers") + flag.Parse() + + if *queue == "" || *handle == "" { + fmt.Println("You must supply a queue name (-q QUEUE) and message receipt handle (-h HANDLE)") + return + } + + if *visibility < 0 { + *visibility = 0 + } + + if *visibility > 12*60*60 { + *visibility = 12 * 60 * 60 + } + // snippet-end:[sqs.go.change_message_visibility.args] + + // Create a session that gets credential values from ~/.aws/credentials + // and the default Region from ~/.aws/config + // snippet-start:[sqs.go.change_message_visibility.sess] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[sqs.go.change_message_visibility.sess] + + // Get URL of queue + urlResult, err := GetQueueURL(sess, queue) + if err != nil { + fmt.Println("Got an error getting the queue URL:") + fmt.Println(err) + return + } + + // snippet-start:[sqs.go.change_message_visibility.url] + queueURL := urlResult.QueueUrl + // snippet-end:[sqs.go.change_message_visibility.url] + + err = SetMsgVisibility(sess, handle, queueURL, visibility) + if err != nil { + fmt.Println("Got an error setting the visibility of the message:") + fmt.Println(err) + return + } } + // snippet-end:[sqs.go.change_message_visibility] diff --git a/go/sqs/ChangeMsgVisibility/ChangeMsgVisibility_test.go b/go/sqs/ChangeMsgVisibility/ChangeMsgVisibility_test.go index bcf6beeba93..88887e65882 100644 --- a/go/sqs/ChangeMsgVisibility/ChangeMsgVisibility_test.go +++ b/go/sqs/ChangeMsgVisibility/ChangeMsgVisibility_test.go @@ -1,38 +1,27 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "strconv" - "testing" - "time" + "encoding/json" + "io/ioutil" + "strconv" + "testing" + "time" - "github.com/google/uuid" + "github.com/google/uuid" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // Config defines a set of configuration values type Config struct { - Queue string `json:"Queue"` - Visibility int64 `json:"Visibility"` - WaitTime int `json:"WaitTime"` + Queue string `json:"Queue"` + Visibility int64 `json:"Visibility"` + WaitTime int `json:"WaitTime"` } // configFile defines the name of the file containing configuration values @@ -42,232 +31,232 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - // Get configuration from config.json + // Get configuration from config.json - // Get entire file as a JSON string - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + // Get entire file as a JSON string + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - // Convert []byte to string - text := string(content) + // Convert []byte to string + text := string(content) - // Marshall JSON string in text into global struct - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + // Marshall JSON string in text into global struct + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - if globalConfig.Visibility < 0 { - globalConfig.Visibility = 0 - } + if globalConfig.Visibility < 0 { + globalConfig.Visibility = 0 + } - if globalConfig.Visibility > 12*60*60 { // 12 hours - globalConfig.Visibility = 12 * 60 * 60 - } + if globalConfig.Visibility > 12*60*60 { // 12 hours + globalConfig.Visibility = 12 * 60 * 60 + } - if globalConfig.WaitTime < 0 { - globalConfig.WaitTime = 0 - } + if globalConfig.WaitTime < 0 { + globalConfig.WaitTime = 0 + } - if globalConfig.WaitTime > 20 { - globalConfig.WaitTime = 20 - } + if globalConfig.WaitTime > 20 { + globalConfig.WaitTime = 20 + } - t.Log("Queue: " + globalConfig.Queue) - t.Log("Visibility: " + strconv.Itoa(int(globalConfig.Visibility))) - t.Log("WaitTime: " + strconv.Itoa(globalConfig.WaitTime)) + t.Log("Queue: " + globalConfig.Queue) + t.Log("Visibility: " + strconv.Itoa(int(globalConfig.Visibility))) + t.Log("WaitTime: " + strconv.Itoa(globalConfig.WaitTime)) - return nil + return nil } func createQueue(sess *session.Session, queue *string) (string, error) { - // Create an SQS service client - svc := sqs.New(sess) - - result, err := svc.CreateQueue(&sqs.CreateQueueInput{ - QueueName: queue, - Attributes: map[string]*string{ - "DelaySeconds": aws.String("60"), - "MessageRetentionPeriod": aws.String("86400"), - }, - }) - if err != nil { - return "", err - } - - return *result.QueueUrl, nil + // Create an SQS service client + svc := sqs.New(sess) + + result, err := svc.CreateQueue(&sqs.CreateQueueInput{ + QueueName: queue, + Attributes: map[string]*string{ + "DelaySeconds": aws.String("60"), + "MessageRetentionPeriod": aws.String("86400"), + }, + }) + if err != nil { + return "", err + } + + return *result.QueueUrl, nil } func configureLPQueue(sess *session.Session, queueURL *string, timeout int) error { - // Create an SQS service client - svc := sqs.New(sess) - - _, err := svc.SetQueueAttributes(&sqs.SetQueueAttributesInput{ - QueueUrl: queueURL, - Attributes: aws.StringMap(map[string]string{ - "ReceiveMessageWaitTimeSeconds": strconv.Itoa(timeout), - }), - }) - if err != nil { - return err - } - - return nil + // Create an SQS service client + svc := sqs.New(sess) + + _, err := svc.SetQueueAttributes(&sqs.SetQueueAttributesInput{ + QueueUrl: queueURL, + Attributes: aws.StringMap(map[string]string{ + "ReceiveMessageWaitTimeSeconds": strconv.Itoa(timeout), + }), + }) + if err != nil { + return err + } + + return nil } func sendMessage(sess *session.Session, queueURL string) error { - // Create an SQS service client - svc := sqs.New(sess) + // Create an SQS service client + svc := sqs.New(sess) - currentTime := time.Now() + currentTime := time.Now() - _, err := svc.SendMessage(&sqs.SendMessageInput{ - DelaySeconds: aws.Int64(0), - MessageBody: aws.String(currentTime.Format("2006-01-02 15:04:05 Monday")), - QueueUrl: &queueURL, - }) - if err != nil { - return err - } + _, err := svc.SendMessage(&sqs.SendMessageInput{ + DelaySeconds: aws.Int64(0), + MessageBody: aws.String(currentTime.Format("2006-01-02 15:04:05 Monday")), + QueueUrl: &queueURL, + }) + if err != nil { + return err + } - return nil + return nil } func receiveMessage(sess *session.Session, queueURL string) (string, error) { - // Create an SQS service client - svc := sqs.New(sess) - - result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{ - AttributeNames: []*string{ - aws.String(sqs.MessageSystemAttributeNameSentTimestamp), - }, - MessageAttributeNames: []*string{ - aws.String(sqs.QueueAttributeNameAll), - }, - QueueUrl: &queueURL, - MaxNumberOfMessages: aws.Int64(1), - }) - if err != nil { - return "", err - } - - if len(result.Messages) > 0 { - return *result.Messages[0].ReceiptHandle, nil - } - - return "", nil + // Create an SQS service client + svc := sqs.New(sess) + + result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{ + AttributeNames: []*string{ + aws.String(sqs.MessageSystemAttributeNameSentTimestamp), + }, + MessageAttributeNames: []*string{ + aws.String(sqs.QueueAttributeNameAll), + }, + QueueUrl: &queueURL, + MaxNumberOfMessages: aws.Int64(1), + }) + if err != nil { + return "", err + } + + if len(result.Messages) > 0 { + return *result.Messages[0].ReceiptHandle, nil + } + + return "", nil } func deleteMsg(sess *session.Session, url string, handle string) error { - svc := sqs.New(sess) + svc := sqs.New(sess) - _, err := svc.DeleteMessage(&sqs.DeleteMessageInput{ - QueueUrl: &url, - ReceiptHandle: &handle, - }) - if err != nil { - return err - } + _, err := svc.DeleteMessage(&sqs.DeleteMessageInput{ + QueueUrl: &url, + ReceiptHandle: &handle, + }) + if err != nil { + return err + } - return nil + return nil } func deleteQueue(sess *session.Session, queueURL string) error { - // Create an SQS service client - svc := sqs.New(sess) + // Create an SQS service client + svc := sqs.New(sess) - _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ - QueueUrl: aws.String(queueURL), - }) - if err != nil { - return err - } + _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ + QueueUrl: aws.String(queueURL), + }) + if err != nil { + return err + } - return nil + return nil } func TestChangeVisibility(t *testing.T) { - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - // Create a session using credentials from ~/.aws/credentials - // and the Region from ~/.aws/config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - queueCreated := false - queueURL := "" - - if globalConfig.Queue == "" { - // Create a unique, random queue name - id := uuid.New() - globalConfig.Queue = "myqueue-" + id.String() - - queueURL, err = createQueue(sess, &globalConfig.Queue) - if err != nil { - t.Fatal(err) - } - - t.Log("Created queue " + globalConfig.Queue) - } - - if globalConfig.WaitTime > 0 { - err := configureLPQueue(sess, &queueURL, globalConfig.WaitTime) - if err != nil { - t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") - t.Fatal(err) - } - } - - err = sendMessage(sess, queueURL) - if err != nil { - t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") - t.Fatal(err) - } - - t.Log("Sent message to queue " + globalConfig.Queue) - - msgHandle, err := receiveMessage(sess, queueURL) - if err != nil { - t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") - t.Fatal(err) - } - - if msgHandle != "" { - t.Log("Received message") - - err = SetMsgVisibility(sess, &msgHandle, &queueURL, &globalConfig.Visibility) - if err != nil { - t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") - t.Fatal(err) - } - - t.Log("Changed message's visibility to " + strconv.Itoa(int(globalConfig.Visibility))) - - // Delete message - err = deleteMsg(sess, queueURL, msgHandle) - if err != nil { - t.Log("Got an error deleting msg:") - t.Fatal(err) - } - - t.Log("Deleted message") - } else { - t.Log("Did not receive message") - } - - if queueCreated { - err = deleteQueue(sess, queueURL) - if err != nil { - t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") - t.Fatal(err) - } - - t.Log("Deleted queue " + globalConfig.Queue) - } + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + // Create a session using credentials from ~/.aws/credentials + // and the Region from ~/.aws/config + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + queueCreated := false + queueURL := "" + + if globalConfig.Queue == "" { + // Create a unique, random queue name + id := uuid.New() + globalConfig.Queue = "myqueue-" + id.String() + + queueURL, err = createQueue(sess, &globalConfig.Queue) + if err != nil { + t.Fatal(err) + } + + t.Log("Created queue " + globalConfig.Queue) + } + + if globalConfig.WaitTime > 0 { + err := configureLPQueue(sess, &queueURL, globalConfig.WaitTime) + if err != nil { + t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") + t.Fatal(err) + } + } + + err = sendMessage(sess, queueURL) + if err != nil { + t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") + t.Fatal(err) + } + + t.Log("Sent message to queue " + globalConfig.Queue) + + msgHandle, err := receiveMessage(sess, queueURL) + if err != nil { + t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") + t.Fatal(err) + } + + if msgHandle != "" { + t.Log("Received message") + + err = SetMsgVisibility(sess, &msgHandle, &queueURL, &globalConfig.Visibility) + if err != nil { + t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") + t.Fatal(err) + } + + t.Log("Changed message's visibility to " + strconv.Itoa(int(globalConfig.Visibility))) + + // Delete message + err = deleteMsg(sess, queueURL, msgHandle) + if err != nil { + t.Log("Got an error deleting msg:") + t.Fatal(err) + } + + t.Log("Deleted message") + } else { + t.Log("Did not receive message") + } + + if queueCreated { + err = deleteQueue(sess, queueURL) + if err != nil { + t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") + t.Fatal(err) + } + + t.Log("Deleted queue " + globalConfig.Queue) + } } diff --git a/go/sqs/ConfigureLPQueue/ConfigureLPQueue.go b/go/sqs/ConfigureLPQueue/ConfigureLPQueue.go index b6538816369..70b102c6f01 100644 --- a/go/sqs/ConfigureLPQueue/ConfigureLPQueue.go +++ b/go/sqs/ConfigureLPQueue/ConfigureLPQueue.go @@ -1,125 +1,122 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sqs.go.configure_lp_queue] package main // snippet-start:[sqs.go.configure_lp_queue.imports] import ( - "flag" - "fmt" - "strconv" + "flag" + "fmt" + "strconv" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) + // snippet-end:[sqs.go.configure_lp_queue.imports] // GetQueueURL gets the URL of an Amazon SQS queue // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// queueName is the name of the queue +// +// sess is the current session, which provides configuration for the SDK's service clients +// queueName is the name of the queue +// // Output: -// If success, the URL of the queue and nil -// Otherwise, an empty string and an error from the call to +// +// If success, the URL of the queue and nil +// Otherwise, an empty string and an error from the call to func GetQueueURL(sess *session.Session, queue *string) (*sqs.GetQueueUrlOutput, error) { - // snippet-start:[sqs.go.configure_lp_queue.get_url] - svc := sqs.New(sess) - - result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ - QueueName: queue, - }) - // snippet-end:[sqs.go.configure_lp_queue.get_url] - if err != nil { - return nil, err - } - - return result, nil + // snippet-start:[sqs.go.configure_lp_queue.get_url] + svc := sqs.New(sess) + + result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ + QueueName: queue, + }) + // snippet-end:[sqs.go.configure_lp_queue.get_url] + if err != nil { + return nil, err + } + + return result, nil } // ConfigureLPQueue configures an Amazon SQS queue to use long polling // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// queueURL is the URL of the queue +// +// sess is the current session, which provides configuration for the SDK's service clients +// queueURL is the URL of the queue +// // Output: -// If success, nil -// Otherwise, an error from the call to DeleteQueue +// +// If success, nil +// Otherwise, an error from the call to DeleteQueue func ConfigureLPQueue(sess *session.Session, queueURL *string, waitTime *int) error { - // Create an SQS service client - svc := sqs.New(sess) - - // snippet-start:[sqs.go.configure_lp_queue.set_attributes] - _, err := svc.SetQueueAttributes(&sqs.SetQueueAttributesInput{ - QueueUrl: queueURL, - Attributes: aws.StringMap(map[string]string{ - "ReceiveMessageWaitTimeSeconds": strconv.Itoa(aws.IntValue(waitTime)), - }), - }) - // snippet-end:[sqs.go.configure_lp_queue.set_attributes] - if err != nil { - return err - } - - return nil + // Create an SQS service client + svc := sqs.New(sess) + + // snippet-start:[sqs.go.configure_lp_queue.set_attributes] + _, err := svc.SetQueueAttributes(&sqs.SetQueueAttributesInput{ + QueueUrl: queueURL, + Attributes: aws.StringMap(map[string]string{ + "ReceiveMessageWaitTimeSeconds": strconv.Itoa(aws.IntValue(waitTime)), + }), + }) + // snippet-end:[sqs.go.configure_lp_queue.set_attributes] + if err != nil { + return err + } + + return nil } func main() { - // snippet-start:[sqs.go.configure_lp_queue.args] - queue := flag.String("q", "", "The name of the queue") - waitTime := flag.Int("w", 10, "The wait time, in seconds, for long polling") - flag.Parse() - - if *queue == "" { - fmt.Println("You must supply a queue name (-q QUEUE") - return - } - - if *waitTime < 1 { - *waitTime = 1 - } - - if *waitTime > 20 { - *waitTime = 20 - } - // snippet-end:[sqs.go.configure_lp_queue.args] - - // Create a session that gets credential values from ~/.aws/credentials - // and the default region from ~/.aws/config - // snippet-start:[sqs.go.configure_lp_queue.sess] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[sqs.go.configure_lp_queue.sess] - - result, err := GetQueueURL(sess, queue) - if err != nil { - fmt.Println("Got an error getting the queue URL:") - fmt.Println(err) - return - } - - // snippet-start:[sqs.go.configure_lp_queue.url] - queueURL := result.QueueUrl - // snippet-end:[sqs.go.configure_lp_queue.url] - - err = ConfigureLPQueue(sess, queueURL, waitTime) - if err != nil { - fmt.Println("Got an error deleting the queue:") - fmt.Println(err) - return - } - - fmt.Println("Queue with URL " + *queueURL + " deleted") + // snippet-start:[sqs.go.configure_lp_queue.args] + queue := flag.String("q", "", "The name of the queue") + waitTime := flag.Int("w", 10, "The wait time, in seconds, for long polling") + flag.Parse() + + if *queue == "" { + fmt.Println("You must supply a queue name (-q QUEUE") + return + } + + if *waitTime < 1 { + *waitTime = 1 + } + + if *waitTime > 20 { + *waitTime = 20 + } + // snippet-end:[sqs.go.configure_lp_queue.args] + + // Create a session that gets credential values from ~/.aws/credentials + // and the default region from ~/.aws/config + // snippet-start:[sqs.go.configure_lp_queue.sess] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[sqs.go.configure_lp_queue.sess] + + result, err := GetQueueURL(sess, queue) + if err != nil { + fmt.Println("Got an error getting the queue URL:") + fmt.Println(err) + return + } + + // snippet-start:[sqs.go.configure_lp_queue.url] + queueURL := result.QueueUrl + // snippet-end:[sqs.go.configure_lp_queue.url] + + err = ConfigureLPQueue(sess, queueURL, waitTime) + if err != nil { + fmt.Println("Got an error deleting the queue:") + fmt.Println(err) + return + } + + fmt.Println("Queue with URL " + *queueURL + " deleted") } + // snippet-end:[sqs.go.configure_lp_queue] diff --git a/go/sqs/ConfigureLPQueue/ConfigureLPQueue_test.go b/go/sqs/ConfigureLPQueue/ConfigureLPQueue_test.go index ef77d0e129c..1be783e0302 100644 --- a/go/sqs/ConfigureLPQueue/ConfigureLPQueue_test.go +++ b/go/sqs/ConfigureLPQueue/ConfigureLPQueue_test.go @@ -1,36 +1,25 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "strconv" - "testing" + "encoding/json" + "io/ioutil" + "strconv" + "testing" - "github.com/google/uuid" + "github.com/google/uuid" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // Config defines a set of configuration values type Config struct { - Queue string `json:"Queue"` - WaitTime int `json:"WaitTime"` + Queue string `json:"Queue"` + WaitTime int `json:"WaitTime"` } // configFile defines the name of the file containing configuration values @@ -40,106 +29,106 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - // Get configuration from config.json + // Get configuration from config.json - // Get entire file as a JSON string - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + // Get entire file as a JSON string + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - // Convert []byte to string - text := string(content) + // Convert []byte to string + text := string(content) - // Marshall JSON string in text into global struct - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + // Marshall JSON string in text into global struct + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Queue: " + globalConfig.Queue) - t.Log("WaitTime: " + strconv.Itoa(globalConfig.WaitTime)) + t.Log("Queue: " + globalConfig.Queue) + t.Log("WaitTime: " + strconv.Itoa(globalConfig.WaitTime)) - return nil + return nil } func createQueue(sess *session.Session, queue *string) (string, error) { - // Create an SQS service client - svc := sqs.New(sess) - - result, err := svc.CreateQueue(&sqs.CreateQueueInput{ - QueueName: queue, - Attributes: map[string]*string{ - "DelaySeconds": aws.String("60"), - "MessageRetentionPeriod": aws.String("86400"), - }, - }) - if err != nil { - return "", err - } - - return *result.QueueUrl, nil + // Create an SQS service client + svc := sqs.New(sess) + + result, err := svc.CreateQueue(&sqs.CreateQueueInput{ + QueueName: queue, + Attributes: map[string]*string{ + "DelaySeconds": aws.String("60"), + "MessageRetentionPeriod": aws.String("86400"), + }, + }) + if err != nil { + return "", err + } + + return *result.QueueUrl, nil } func deleteQueue(sess *session.Session, queueURL *string) error { - // Create an SQS service client - svc := sqs.New(sess) + // Create an SQS service client + svc := sqs.New(sess) - _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ - QueueUrl: queueURL, - }) - if err != nil { - return err - } + _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ + QueueUrl: queueURL, + }) + if err != nil { + return err + } - return nil + return nil } func TestConfigureLpQueue(t *testing.T) { - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - // Create a session using credentials from ~/.aws/credentials - // and the Region from ~/.aws/config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - queueCreated := false - queueURL := "" - - if globalConfig.Queue == "" { - // Create a unique, random queue name - id := uuid.New() - globalConfig.Queue = "myqueue-" + id.String() - - queueURL, err = createQueue(sess, &globalConfig.Queue) - if err != nil { - t.Fatal(err) - } - - t.Log("Created queue " + globalConfig.Queue) - queueCreated = true - } - - err = ConfigureLPQueue(sess, &queueURL, &globalConfig.WaitTime) - if err != nil { - t.Log("Could not configure queue to use long polling") - t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") - t.Fatal(err) - } - - t.Log("Configured long polling queue") - - if queueCreated { - err = deleteQueue(sess, &queueURL) - if err != nil { - t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") - t.Fatal(err) - } - - t.Log("Deleted queue " + globalConfig.Queue) - } + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + // Create a session using credentials from ~/.aws/credentials + // and the Region from ~/.aws/config + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + queueCreated := false + queueURL := "" + + if globalConfig.Queue == "" { + // Create a unique, random queue name + id := uuid.New() + globalConfig.Queue = "myqueue-" + id.String() + + queueURL, err = createQueue(sess, &globalConfig.Queue) + if err != nil { + t.Fatal(err) + } + + t.Log("Created queue " + globalConfig.Queue) + queueCreated = true + } + + err = ConfigureLPQueue(sess, &queueURL, &globalConfig.WaitTime) + if err != nil { + t.Log("Could not configure queue to use long polling") + t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") + t.Fatal(err) + } + + t.Log("Configured long polling queue") + + if queueCreated { + err = deleteQueue(sess, &queueURL) + if err != nil { + t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") + t.Fatal(err) + } + + t.Log("Deleted queue " + globalConfig.Queue) + } } diff --git a/go/sqs/CreateLPQueue/CreateLPQueue.go b/go/sqs/CreateLPQueue/CreateLPQueue.go index d7b3cf21eeb..fcd8a39f151 100644 --- a/go/sqs/CreateLPQueue/CreateLPQueue.go +++ b/go/sqs/CreateLPQueue/CreateLPQueue.go @@ -1,94 +1,88 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sqs.go.create_lp_queue] package main // snippet-start:[sqs.go.create_lp_queue.imports] import ( - "flag" - "fmt" - "strconv" + "flag" + "fmt" + "strconv" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) + // snippet-end:[sqs.go.create_lp_queue.imports] // CreateLPQueue creates an Amazon SQS queue with long polling enabled // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// queueName is the name of the queue -// waitTime is the wait time, in seconds, for long polling to wait for messages +// +// sess is the current session, which provides configuration for the SDK's service clients +// queueName is the name of the queue +// waitTime is the wait time, in seconds, for long polling to wait for messages +// // Output: -// If success, the URL of the queue and nil -// Otherwise, an empty string and an error from the call to CreateQueue +// +// If success, the URL of the queue and nil +// Otherwise, an empty string and an error from the call to CreateQueue func CreateLPQueue(sess *session.Session, queueName *string, waitTime *int) (string, error) { - // snippet-start:[sqs.go.create_lp_queue.call] - svc := sqs.New(sess) + // snippet-start:[sqs.go.create_lp_queue.call] + svc := sqs.New(sess) - result, err := svc.CreateQueue(&sqs.CreateQueueInput{ - QueueName: queueName, - Attributes: aws.StringMap(map[string]string{ - "ReceiveMessageWaitTimeSeconds": strconv.Itoa(*waitTime), - }), - }) - // snippet-end:[sqs.go.create_lp_queue.call] - if err != nil { - return "", err - } + result, err := svc.CreateQueue(&sqs.CreateQueueInput{ + QueueName: queueName, + Attributes: aws.StringMap(map[string]string{ + "ReceiveMessageWaitTimeSeconds": strconv.Itoa(*waitTime), + }), + }) + // snippet-end:[sqs.go.create_lp_queue.call] + if err != nil { + return "", err + } - return *result.QueueUrl, nil + return *result.QueueUrl, nil } func main() { - // snippet-start:[sqs.go.create_lp_queue.args] - queue := flag.String("q", "", "The name of the queue") - waitTime := flag.Int("w", 10, "How long, in seconds, to wait for long polling") - flag.Parse() + // snippet-start:[sqs.go.create_lp_queue.args] + queue := flag.String("q", "", "The name of the queue") + waitTime := flag.Int("w", 10, "How long, in seconds, to wait for long polling") + flag.Parse() + + if *queue == "" { + fmt.Println("You must supply a queue name (-q QUEUE") + return + } - if *queue == "" { - fmt.Println("You must supply a queue name (-q QUEUE") - return - } + if *waitTime < 1 { + *waitTime = 1 + } - if *waitTime < 1 { - *waitTime = 1 - } + if *waitTime > 20 { + *waitTime = 20 + } + // snippet-end:[sqs.go.create_lp_queue.args] - if *waitTime > 20 { - *waitTime = 20 - } - // snippet-end:[sqs.go.create_lp_queue.args] - - // Create a session that gets credential values from ~/.aws/credentials - // and the default region from ~/.aws/config - // snippet-start:[sqs.go.create_lp_queue.sess] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[sqs.go.create_lp_queue.sess] + // Create a session that gets credential values from ~/.aws/credentials + // and the default region from ~/.aws/config + // snippet-start:[sqs.go.create_lp_queue.sess] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[sqs.go.create_lp_queue.sess] - url, err := CreateLPQueue(sess, queue, waitTime) - if err != nil { - fmt.Println("Got an error creating the long polling queue:") - fmt.Println(err) - return - } + url, err := CreateLPQueue(sess, queue, waitTime) + if err != nil { + fmt.Println("Got an error creating the long polling queue:") + fmt.Println(err) + return + } - // snippet-start:[sqs.go.create_lp_queue.url] - fmt.Println("URL for long polling queue " + *queue + ": " + url) - // snippet-end:[sqs.go.create_lp_queue.url] + // snippet-start:[sqs.go.create_lp_queue.url] + fmt.Println("URL for long polling queue " + *queue + ": " + url) + // snippet-end:[sqs.go.create_lp_queue.url] } + // snippet-end:[sqs.go.create_lp_queue] diff --git a/go/sqs/CreateLPQueue/CreateLPQueue_test.go b/go/sqs/CreateLPQueue/CreateLPQueue_test.go index 94beadf0a65..bdeb9a79f23 100644 --- a/go/sqs/CreateLPQueue/CreateLPQueue_test.go +++ b/go/sqs/CreateLPQueue/CreateLPQueue_test.go @@ -1,37 +1,26 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "strconv" - "testing" - "time" + "encoding/json" + "io/ioutil" + "strconv" + "testing" + "time" - "github.com/google/uuid" + "github.com/google/uuid" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // Config defines a set of configuration values type Config struct { - Queue string `json:"Queue"` - WaitTime int `json:"WaitTime"` + Queue string `json:"Queue"` + WaitTime int `json:"WaitTime"` } // configFile defines the name of the file containing configuration values @@ -41,90 +30,90 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - // Get configuration from config.json + // Get configuration from config.json - // Get entire file as a JSON string - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + // Get entire file as a JSON string + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - // Convert []byte to string - text := string(content) + // Convert []byte to string + text := string(content) - // Marshall JSON string in text into global struct - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + // Marshall JSON string in text into global struct + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - if globalConfig.WaitTime < 1 { - globalConfig.WaitTime = 1 - } + if globalConfig.WaitTime < 1 { + globalConfig.WaitTime = 1 + } - if globalConfig.WaitTime > 20 { - globalConfig.WaitTime = 20 - } + if globalConfig.WaitTime > 20 { + globalConfig.WaitTime = 20 + } - t.Log("Queue: " + globalConfig.Queue) - t.Log("WaitTime: " + strconv.Itoa(globalConfig.WaitTime)) + t.Log("Queue: " + globalConfig.Queue) + t.Log("WaitTime: " + strconv.Itoa(globalConfig.WaitTime)) - return nil + return nil } func deleteQueue(sess *session.Session, queueURL string) error { - // Create an SQS service client - svc := sqs.New(sess) + // Create an SQS service client + svc := sqs.New(sess) - _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ - QueueUrl: aws.String(queueURL), - }) - if err != nil { - return err - } + _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ + QueueUrl: aws.String(queueURL), + }) + if err != nil { + return err + } - return nil + return nil } func TestCreateLpQueue(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - // Create a session using credentials from ~/.aws/credentials - // and the Region from ~/.aws/config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - shouldDelete := false - - if globalConfig.Queue == "" { - // Create a unique, random queue name - id := uuid.New() - globalConfig.Queue = "mylpqueue-" + id.String() - shouldDelete = true - } - - url, err := CreateLPQueue(sess, &globalConfig.Queue, &globalConfig.WaitTime) - if err != nil { - t.Fatal(err) - } - - t.Log("Got URL " + url + " for long polling queue " + globalConfig.Queue) - - if shouldDelete { - err = deleteQueue(sess, url) - if err != nil { - t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") - t.Fatal(err) - } - - t.Log("Deleted queue " + globalConfig.Queue) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + // Create a session using credentials from ~/.aws/credentials + // and the Region from ~/.aws/config + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + shouldDelete := false + + if globalConfig.Queue == "" { + // Create a unique, random queue name + id := uuid.New() + globalConfig.Queue = "mylpqueue-" + id.String() + shouldDelete = true + } + + url, err := CreateLPQueue(sess, &globalConfig.Queue, &globalConfig.WaitTime) + if err != nil { + t.Fatal(err) + } + + t.Log("Got URL " + url + " for long polling queue " + globalConfig.Queue) + + if shouldDelete { + err = deleteQueue(sess, url) + if err != nil { + t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") + t.Fatal(err) + } + + t.Log("Deleted queue " + globalConfig.Queue) + } } diff --git a/go/sqs/CreateQueue/CreateQueue.go b/go/sqs/CreateQueue/CreateQueue.go index 818468863bf..e50b4bd05f6 100644 --- a/go/sqs/CreateQueue/CreateQueue.go +++ b/go/sqs/CreateQueue/CreateQueue.go @@ -1,85 +1,79 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sqs.go.create_queue] package main // snippet-start:[sqs.go.create_queue.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) + // snippet-end:[sqs.go.create_queue.imports] // CreateQueue creates an Amazon SQS queue // Inputs: -// sess is the -// queueName is the name of the queue +// +// sess is the +// queueName is the name of the queue +// // Output: -// If success, the URL of the queue and nil -// Otherwise, an empty string and an error from the call to CreateQueue +// +// If success, the URL of the queue and nil +// Otherwise, an empty string and an error from the call to CreateQueue func CreateQueue(sess *session.Session, queue *string) (*sqs.CreateQueueOutput, error) { - // Create an SQS service client - // snippet-start:[sqs.go.create_queue.call] - svc := sqs.New(sess) + // Create an SQS service client + // snippet-start:[sqs.go.create_queue.call] + svc := sqs.New(sess) - result, err := svc.CreateQueue(&sqs.CreateQueueInput{ - QueueName: queue, - Attributes: map[string]*string{ - "DelaySeconds": aws.String("60"), - "MessageRetentionPeriod": aws.String("86400"), - }, - }) - // snippet-end:[sqs.go.create_queue.call] - if err != nil { - return nil, err - } + result, err := svc.CreateQueue(&sqs.CreateQueueInput{ + QueueName: queue, + Attributes: map[string]*string{ + "DelaySeconds": aws.String("60"), + "MessageRetentionPeriod": aws.String("86400"), + }, + }) + // snippet-end:[sqs.go.create_queue.call] + if err != nil { + return nil, err + } - return result, nil + return result, nil } func main() { - // snippet-start:[sqs.go.create_queue.args] - queue := flag.String("q", "", "The name of the queue") - flag.Parse() + // snippet-start:[sqs.go.create_queue.args] + queue := flag.String("q", "", "The name of the queue") + flag.Parse() - if *queue == "" { - fmt.Println("You must supply a queue name (-q QUEUE") - return - } - // snippet-end:[sqs.go.create_queue.args] + if *queue == "" { + fmt.Println("You must supply a queue name (-q QUEUE") + return + } + // snippet-end:[sqs.go.create_queue.args] - // Create a session that gets credential values from ~/.aws/credentials - // and the default region from ~/.aws/config - // snippet-start:[sqs.go.create_queue.sess] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[sqs.go.create_queue.sess] + // Create a session that gets credential values from ~/.aws/credentials + // and the default region from ~/.aws/config + // snippet-start:[sqs.go.create_queue.sess] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[sqs.go.create_queue.sess] - result, err := CreateQueue(sess, queue) - if err != nil { - fmt.Println("Got an error creating the queue:") - fmt.Println(err) - return - } + result, err := CreateQueue(sess, queue) + if err != nil { + fmt.Println("Got an error creating the queue:") + fmt.Println(err) + return + } - // snippet-start:[sqs.go.create_queue.print] - fmt.Println("URL: " + *result.QueueUrl) - // snippet-end:[sqs.go.create_queue.print] + // snippet-start:[sqs.go.create_queue.print] + fmt.Println("URL: " + *result.QueueUrl) + // snippet-end:[sqs.go.create_queue.print] } + // snippet-end:[sqs.go.create_queue] diff --git a/go/sqs/CreateQueue/CreateQueue_test.go b/go/sqs/CreateQueue/CreateQueue_test.go index 424de663184..dafefd640c5 100644 --- a/go/sqs/CreateQueue/CreateQueue_test.go +++ b/go/sqs/CreateQueue/CreateQueue_test.go @@ -1,33 +1,22 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "testing" + "encoding/json" + "io/ioutil" + "testing" - "github.com/google/uuid" + "github.com/google/uuid" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // Config defines a set of configuration values type Config struct { - Queue string `json:"Queue"` + Queue string `json:"Queue"` } // configFile defines the name of the file containing configuration values @@ -37,77 +26,77 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - // Get configuration from config.json + // Get configuration from config.json - // Get entire file as a JSON string - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + // Get entire file as a JSON string + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - // Convert []byte to string - text := string(content) + // Convert []byte to string + text := string(content) - // Marshall JSON string in text into global struct - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + // Marshall JSON string in text into global struct + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Queue: " + globalConfig.Queue) + t.Log("Queue: " + globalConfig.Queue) - return nil + return nil } func deleteQueue(sess *session.Session, queueURL *string) error { - // Create an SQS service client - svc := sqs.New(sess) + // Create an SQS service client + svc := sqs.New(sess) - _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ - QueueUrl: queueURL, - }) - if err != nil { - return err - } + _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ + QueueUrl: queueURL, + }) + if err != nil { + return err + } - return nil + return nil } func TestCreateQueue(t *testing.T) { - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - queueCreated := false - - if globalConfig.Queue == "" { - // Create a unique, random queue name - id := uuid.New() - globalConfig.Queue = "myqueue-" + id.String() - queueCreated = true - } - - // Create a session using credentials from ~/.aws/credentials - // and the Region from ~/.aws/config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - result, err := CreateQueue(sess, &globalConfig.Queue) - if err != nil { - t.Fatal(err) - } - - t.Log("Got URL " + *result.QueueUrl + " for queue " + globalConfig.Queue) - - if queueCreated { - err = deleteQueue(sess, result.QueueUrl) - if err != nil { - t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") - t.Fatal(err) - } - - t.Log("Deleted queue " + globalConfig.Queue) - } + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + queueCreated := false + + if globalConfig.Queue == "" { + // Create a unique, random queue name + id := uuid.New() + globalConfig.Queue = "myqueue-" + id.String() + queueCreated = true + } + + // Create a session using credentials from ~/.aws/credentials + // and the Region from ~/.aws/config + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + result, err := CreateQueue(sess, &globalConfig.Queue) + if err != nil { + t.Fatal(err) + } + + t.Log("Got URL " + *result.QueueUrl + " for queue " + globalConfig.Queue) + + if queueCreated { + err = deleteQueue(sess, result.QueueUrl) + if err != nil { + t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") + t.Fatal(err) + } + + t.Log("Deleted queue " + globalConfig.Queue) + } } diff --git a/go/sqs/DeadLetterQueue/DeadLetterQueue.go b/go/sqs/DeadLetterQueue/DeadLetterQueue.go index 7d812b8e151..b2752609f08 100644 --- a/go/sqs/DeadLetterQueue/DeadLetterQueue.go +++ b/go/sqs/DeadLetterQueue/DeadLetterQueue.go @@ -1,157 +1,154 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sqs.go.dead_letter_queue] package main // snippet-start:[sqs.go.dead_letter_queue.imports] import ( - "encoding/json" - "flag" - "fmt" - "strings" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "encoding/json" + "flag" + "fmt" + "strings" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) + // snippet-end:[sqs.go.dead_letter_queue.imports] // GetQueueURL gets the URL of an Amazon SQS queue // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// queueName is the name of the queue +// +// sess is the current session, which provides configuration for the SDK's service clients +// queueName is the name of the queue +// // Output: -// If success, the URL of the queue and nil -// Otherwise, an empty string and an error from the call to +// +// If success, the URL of the queue and nil +// Otherwise, an empty string and an error from the call to func GetQueueURL(sess *session.Session, queue *string) (*sqs.GetQueueUrlOutput, error) { - svc := sqs.New(sess) + svc := sqs.New(sess) - result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ - QueueName: queue, - }) - if err != nil { - return nil, err - } + result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ + QueueName: queue, + }) + if err != nil { + return nil, err + } - return result, nil + return result, nil } // GetQueueArn gets the ARN of a queue based on its URL func GetQueueArn(queueURL *string) *string { - // snippet-start:[sqs.go.get_queue_url.arn] - parts := strings.Split(*queueURL, "/") - subParts := strings.Split(parts[2], ".") + // snippet-start:[sqs.go.get_queue_url.arn] + parts := strings.Split(*queueURL, "/") + subParts := strings.Split(parts[2], ".") - arn := "arn:aws:" + subParts[0] + ":" + subParts[1] + ":" + parts[3] + ":" + parts[4] - // snippet-end:[sqs.go.get_queue_url.arn] + arn := "arn:aws:" + subParts[0] + ":" + subParts[1] + ":" + parts[3] + ":" + parts[4] + // snippet-end:[sqs.go.get_queue_url.arn] - return &arn + return &arn } // ConfigureDeadLetterQueue configures an Amazon SQS queue for messages that could not be delivered to another queue // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// deadLetterQueueARN is the ARN of the dead-letter queue -// queueURL is the URL of the queue that did not get messages +// +// sess is the current session, which provides configuration for the SDK's service clients +// deadLetterQueueARN is the ARN of the dead-letter queue +// queueURL is the URL of the queue that did not get messages +// // Output: -// If success, the URL of the queue and nil -// Otherwise, an empty string and an error from the call to json.Marshal or SetQueueAttributes +// +// If success, the URL of the queue and nil +// Otherwise, an empty string and an error from the call to json.Marshal or SetQueueAttributes func ConfigureDeadLetterQueue(sess *session.Session, dlQueueARN *string, queueURL *string) error { - // Create an SQS service client - svc := sqs.New(sess) - - // Our redrive policy for our queue - // snippet-start:[sqs.go.dead_letter_queue.policy] - policy := map[string]string{ - "deadLetterTargetArn": *dlQueueARN, - "maxReceiveCount": "10", - } - // snippet-end:[sqs.go.dead_letter_queue.policy] - - // Marshal policy for SetQueueAttributes - // snippet-start:[sqs.go.dead_letter_queue.marshall] - b, err := json.Marshal(policy) - // snippet-end:[sqs.go.dead_letter_queue.marshall] - if err != nil { - return err - } - - // snippet-start:[sqs.go.dead_letter_queue.set_attributes] - _, err = svc.SetQueueAttributes(&sqs.SetQueueAttributesInput{ - QueueUrl: queueURL, - Attributes: map[string]*string{ - sqs.QueueAttributeNameRedrivePolicy: aws.String(string(b)), - }, - }) - // snippet-end:[sqs.go.dead_letter_queue.set_attributes] - if err != nil { - return err - } - - return nil + // Create an SQS service client + svc := sqs.New(sess) + + // Our redrive policy for our queue + // snippet-start:[sqs.go.dead_letter_queue.policy] + policy := map[string]string{ + "deadLetterTargetArn": *dlQueueARN, + "maxReceiveCount": "10", + } + // snippet-end:[sqs.go.dead_letter_queue.policy] + + // Marshal policy for SetQueueAttributes + // snippet-start:[sqs.go.dead_letter_queue.marshall] + b, err := json.Marshal(policy) + // snippet-end:[sqs.go.dead_letter_queue.marshall] + if err != nil { + return err + } + + // snippet-start:[sqs.go.dead_letter_queue.set_attributes] + _, err = svc.SetQueueAttributes(&sqs.SetQueueAttributesInput{ + QueueUrl: queueURL, + Attributes: map[string]*string{ + sqs.QueueAttributeNameRedrivePolicy: aws.String(string(b)), + }, + }) + // snippet-end:[sqs.go.dead_letter_queue.set_attributes] + if err != nil { + return err + } + + return nil } func main() { - // snippet-start:[sqs.go.dead_letter_queue.args] - queue := flag.String("q", "", "The name of the queue") - dlQueue := flag.String("d", "", "The name of the dead-letter queue") - flag.Parse() - - if *queue == "" || *dlQueue == "" { - fmt.Println("You must supply the names of the queue (-q QUEUE) and the dead-letter queue (-d DLQUEUE)") - return - } - // snippet-end:[sqs.go.dead_letter_queue.args] - - // Create a session that gets credential values from ~/.aws/credentials - // and the default region from ~/.aws/config - // snippet-start:[sqs.go.dead_letter_queue.sess] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[sqs.go.dead_letter_queue.sess] - - result, err := GetQueueURL(sess, queue) - if err != nil { - fmt.Println("Got an error getting the queue URL:") - fmt.Println(err) - return - } - - // snippet-start:[sqs.go.dead_letter_queue.url] - queueURL := result.QueueUrl - // snippet-end:[sqs.go.dead_letter_queue.url] - - result, err = GetQueueURL(sess, dlQueue) - if err != nil { - fmt.Println("Got an error getting the queue URL:") - fmt.Println(err) - return - } - - dlQueueURL := result.QueueUrl - - // Get the ARN for the dead-letter queue - arn := GetQueueArn(dlQueueURL) - - err = ConfigureDeadLetterQueue(sess, arn, queueURL) - if err != nil { - fmt.Println("Got an error configuring the dead-letter queue:") - fmt.Println(err) - return - } - - fmt.Println("Created dead-letter queue") + // snippet-start:[sqs.go.dead_letter_queue.args] + queue := flag.String("q", "", "The name of the queue") + dlQueue := flag.String("d", "", "The name of the dead-letter queue") + flag.Parse() + + if *queue == "" || *dlQueue == "" { + fmt.Println("You must supply the names of the queue (-q QUEUE) and the dead-letter queue (-d DLQUEUE)") + return + } + // snippet-end:[sqs.go.dead_letter_queue.args] + + // Create a session that gets credential values from ~/.aws/credentials + // and the default region from ~/.aws/config + // snippet-start:[sqs.go.dead_letter_queue.sess] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[sqs.go.dead_letter_queue.sess] + + result, err := GetQueueURL(sess, queue) + if err != nil { + fmt.Println("Got an error getting the queue URL:") + fmt.Println(err) + return + } + + // snippet-start:[sqs.go.dead_letter_queue.url] + queueURL := result.QueueUrl + // snippet-end:[sqs.go.dead_letter_queue.url] + + result, err = GetQueueURL(sess, dlQueue) + if err != nil { + fmt.Println("Got an error getting the queue URL:") + fmt.Println(err) + return + } + + dlQueueURL := result.QueueUrl + + // Get the ARN for the dead-letter queue + arn := GetQueueArn(dlQueueURL) + + err = ConfigureDeadLetterQueue(sess, arn, queueURL) + if err != nil { + fmt.Println("Got an error configuring the dead-letter queue:") + fmt.Println(err) + return + } + + fmt.Println("Created dead-letter queue") } + // snippet-end:[sqs.go.dead_letter_queue] diff --git a/go/sqs/DeadLetterQueue/DeadLetterQueue_test.go b/go/sqs/DeadLetterQueue/DeadLetterQueue_test.go index 3433bf47ef1..5a51dc1f8a4 100644 --- a/go/sqs/DeadLetterQueue/DeadLetterQueue_test.go +++ b/go/sqs/DeadLetterQueue/DeadLetterQueue_test.go @@ -1,35 +1,24 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "testing" + "encoding/json" + "io/ioutil" + "testing" - "github.com/google/uuid" + "github.com/google/uuid" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // Config defines a set of configuration values type Config struct { - Queue string `json:"Queue"` - DlQueue string `json:"DlQueue"` + Queue string `json:"Queue"` + DlQueue string `json:"DlQueue"` } // configFile defines the name of the file containing configuration values @@ -39,131 +28,131 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - // Get configuration from config.json + // Get configuration from config.json - // Get entire file as a JSON string - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + // Get entire file as a JSON string + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - // Convert []byte to string - text := string(content) + // Convert []byte to string + text := string(content) - // Marshall JSON string in text into global struct - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + // Marshall JSON string in text into global struct + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Queue: " + globalConfig.Queue) - t.Log("DlQueue: " + globalConfig.DlQueue) + t.Log("Queue: " + globalConfig.Queue) + t.Log("DlQueue: " + globalConfig.DlQueue) - return nil + return nil } func createQueue(sess *session.Session, queue *string) (string, error) { - // Create an SQS service client - svc := sqs.New(sess) - - result, err := svc.CreateQueue(&sqs.CreateQueueInput{ - QueueName: queue, - Attributes: map[string]*string{ - "DelaySeconds": aws.String("60"), - "MessageRetentionPeriod": aws.String("86400"), - }, - }) - if err != nil { - return "", err - } - - return *result.QueueUrl, nil + // Create an SQS service client + svc := sqs.New(sess) + + result, err := svc.CreateQueue(&sqs.CreateQueueInput{ + QueueName: queue, + Attributes: map[string]*string{ + "DelaySeconds": aws.String("60"), + "MessageRetentionPeriod": aws.String("86400"), + }, + }) + if err != nil { + return "", err + } + + return *result.QueueUrl, nil } func deleteQueue(sess *session.Session, queueURL *string) error { - // Create an SQS service client - svc := sqs.New(sess) + // Create an SQS service client + svc := sqs.New(sess) - _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ - QueueUrl: queueURL, - }) - if err != nil { - return err - } + _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ + QueueUrl: queueURL, + }) + if err != nil { + return err + } - return nil + return nil } func TestDeadLetterQueue(t *testing.T) { - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - // Create a session using credentials from ~/.aws/credentials - // and the Region from ~/.aws/config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - queueURL := "" - dlQueueURL := "" - dlARN := "" - queueCreated := false - dlQueueCreated := false - - id := uuid.New() - - if globalConfig.Queue == "" { - // Create a unique, random queue name - globalConfig.Queue = "myqueue-" + id.String() - - queueURL, err = createQueue(sess, &globalConfig.Queue) - if err != nil { - t.Fatal(err) - } - - t.Log("Created queue " + globalConfig.Queue) - queueCreated = true - } - - if globalConfig.DlQueue == "" { - // Create a unique, random queue name - globalConfig.DlQueue = "mydlqueue-" + id.String() - - dlQueueURL, err = createQueue(sess, &globalConfig.DlQueue) - if err != nil { - t.Fatal(err) - } - - dlARN = *GetQueueArn(&dlQueueURL) - - t.Log("Created dead-letter queue " + globalConfig.DlQueue) - dlQueueCreated = true - } - - err = ConfigureDeadLetterQueue(sess, &dlARN, &queueURL) - if err != nil { - t.Fatal(err) - } - - if queueCreated { - err = deleteQueue(sess, &queueURL) - if err != nil { - t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") - t.Fatal(err) - } - - t.Log("Deleted queue " + globalConfig.Queue) - } - - if dlQueueCreated { - err = deleteQueue(sess, &dlQueueURL) - if err != nil { - t.Log("You'll have to delete queue " + globalConfig.DlQueue + " yourself") - t.Fatal(err) - } - - t.Log("Deleted queue " + globalConfig.DlQueue) - } + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + // Create a session using credentials from ~/.aws/credentials + // and the Region from ~/.aws/config + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + queueURL := "" + dlQueueURL := "" + dlARN := "" + queueCreated := false + dlQueueCreated := false + + id := uuid.New() + + if globalConfig.Queue == "" { + // Create a unique, random queue name + globalConfig.Queue = "myqueue-" + id.String() + + queueURL, err = createQueue(sess, &globalConfig.Queue) + if err != nil { + t.Fatal(err) + } + + t.Log("Created queue " + globalConfig.Queue) + queueCreated = true + } + + if globalConfig.DlQueue == "" { + // Create a unique, random queue name + globalConfig.DlQueue = "mydlqueue-" + id.String() + + dlQueueURL, err = createQueue(sess, &globalConfig.DlQueue) + if err != nil { + t.Fatal(err) + } + + dlARN = *GetQueueArn(&dlQueueURL) + + t.Log("Created dead-letter queue " + globalConfig.DlQueue) + dlQueueCreated = true + } + + err = ConfigureDeadLetterQueue(sess, &dlARN, &queueURL) + if err != nil { + t.Fatal(err) + } + + if queueCreated { + err = deleteQueue(sess, &queueURL) + if err != nil { + t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") + t.Fatal(err) + } + + t.Log("Deleted queue " + globalConfig.Queue) + } + + if dlQueueCreated { + err = deleteQueue(sess, &dlQueueURL) + if err != nil { + t.Log("You'll have to delete queue " + globalConfig.DlQueue + " yourself") + t.Fatal(err) + } + + t.Log("Deleted queue " + globalConfig.DlQueue) + } } diff --git a/go/sqs/DeleteMessage/DeleteMessage.go b/go/sqs/DeleteMessage/DeleteMessage.go index 86f8d081b5a..50a22ed12cd 100644 --- a/go/sqs/DeleteMessage/DeleteMessage.go +++ b/go/sqs/DeleteMessage/DeleteMessage.go @@ -1,111 +1,108 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sqs.go.delete_message] package main // snippet-start:[sqs.go.delete_message.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) + // snippet-end:[sqs.go.delete_message.imports] // GetQueueURL gets the URL of an Amazon SQS queue // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// queueName is the name of the queue +// +// sess is the current session, which provides configuration for the SDK's service clients +// queueName is the name of the queue +// // Output: -// If success, the URL of the queue and nil -// Otherwise, an empty string and an error from the call to +// +// If success, the URL of the queue and nil +// Otherwise, an empty string and an error from the call to func GetQueueURL(sess *session.Session, queue *string) (*sqs.GetQueueUrlOutput, error) { - // Create an SQS service client - svc := sqs.New(sess) + // Create an SQS service client + svc := sqs.New(sess) - result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ - QueueName: queue, - }) - if err != nil { - return nil, err - } + result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ + QueueName: queue, + }) + if err != nil { + return nil, err + } - return result, nil + return result, nil } // DeleteMessage deletes a message from an Amazon SQS queue // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// queueURL is the URL of the queue -// messageID is the ID of the message +// +// sess is the current session, which provides configuration for the SDK's service clients +// queueURL is the URL of the queue +// messageID is the ID of the message +// // Output: -// If success, nil -// Otherwise, an error from the call to DeleteMessage +// +// If success, nil +// Otherwise, an error from the call to DeleteMessage func DeleteMessage(sess *session.Session, queueURL *string, messageHandle *string) error { - // snippet-start:[sqs.go.delete_message.call] - svc := sqs.New(sess) - - _, err := svc.DeleteMessage(&sqs.DeleteMessageInput{ - QueueUrl: queueURL, - ReceiptHandle: messageHandle, - }) - // snippet-end:[sqs.go.delete_message.call] - if err != nil { - return err - } - - return nil + // snippet-start:[sqs.go.delete_message.call] + svc := sqs.New(sess) + + _, err := svc.DeleteMessage(&sqs.DeleteMessageInput{ + QueueUrl: queueURL, + ReceiptHandle: messageHandle, + }) + // snippet-end:[sqs.go.delete_message.call] + if err != nil { + return err + } + + return nil } func main() { - // snippet-start:[sqs.go.delete_message.args] - queue := flag.String("q", "", "The name of the queue") - messageHandle := flag.String("m", "", "The receipt handle of the message") - flag.Parse() - - if *queue == "" || *messageHandle == "" { - fmt.Println("You must supply a queue name (-q QUEUE) and message receipt handle (-m MESSAGE-HANDLE)") - return - } - // snippet-end:[sqs.go.delete_message.args] - - // Create a session that gets credential values from ~/.aws/credentials - // and the default region from ~/.aws/config - // snippet-start:[sqs.go.delete_message.sess] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[sqs.go.delete_message.sess] - - // Get URL of queue - result, err := GetQueueURL(sess, queue) - if err != nil { - fmt.Println("Got an error getting the queue URL:") - fmt.Println(err) - return - } - - queueURL := result.QueueUrl - - err = DeleteMessage(sess, queueURL, messageHandle) - if err != nil { - fmt.Println("Got an error deleting the message:") - fmt.Println(err) - return - } - - fmt.Println("Deleted message from queue with URL " + *queueURL) + // snippet-start:[sqs.go.delete_message.args] + queue := flag.String("q", "", "The name of the queue") + messageHandle := flag.String("m", "", "The receipt handle of the message") + flag.Parse() + + if *queue == "" || *messageHandle == "" { + fmt.Println("You must supply a queue name (-q QUEUE) and message receipt handle (-m MESSAGE-HANDLE)") + return + } + // snippet-end:[sqs.go.delete_message.args] + + // Create a session that gets credential values from ~/.aws/credentials + // and the default region from ~/.aws/config + // snippet-start:[sqs.go.delete_message.sess] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[sqs.go.delete_message.sess] + + // Get URL of queue + result, err := GetQueueURL(sess, queue) + if err != nil { + fmt.Println("Got an error getting the queue URL:") + fmt.Println(err) + return + } + + queueURL := result.QueueUrl + + err = DeleteMessage(sess, queueURL, messageHandle) + if err != nil { + fmt.Println("Got an error deleting the message:") + fmt.Println(err) + return + } + + fmt.Println("Deleted message from queue with URL " + *queueURL) } + // snippet-end:[sqs.go.delete_message] diff --git a/go/sqs/DeleteMessage/DeleteMessage_test.go b/go/sqs/DeleteMessage/DeleteMessage_test.go index 674d42c79f0..b743ff21d3c 100644 --- a/go/sqs/DeleteMessage/DeleteMessage_test.go +++ b/go/sqs/DeleteMessage/DeleteMessage_test.go @@ -1,36 +1,25 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "testing" - "time" + "encoding/json" + "io/ioutil" + "testing" + "time" - "github.com/google/uuid" + "github.com/google/uuid" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // Config defines a set of configuration values type Config struct { - MsgHandle string `json:"MsgHandle"` - Queue string `json:"Queue"` + MsgHandle string `json:"MsgHandle"` + Queue string `json:"Queue"` } // configFile defines the name of the file containing configuration values @@ -40,162 +29,162 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - // Get configuration from config.json + // Get configuration from config.json - // Get entire file as a JSON string - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + // Get entire file as a JSON string + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - // Convert []byte to string - text := string(content) + // Convert []byte to string + text := string(content) - // Marshall JSON string in text into global struct - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + // Marshall JSON string in text into global struct + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Message handle: " + globalConfig.MsgHandle) - t.Log("Queue: " + globalConfig.Queue) + t.Log("Message handle: " + globalConfig.MsgHandle) + t.Log("Queue: " + globalConfig.Queue) - return nil + return nil } func createQueue(sess *session.Session, queueName string) (string, error) { - // Create an SQS service client - svc := sqs.New(sess) - - result, err := svc.CreateQueue(&sqs.CreateQueueInput{ - QueueName: aws.String(queueName), - Attributes: map[string]*string{ - "DelaySeconds": aws.String("60"), - "MessageRetentionPeriod": aws.String("86400"), - }, - }) - if err != nil { - return "", err - } - - return *result.QueueUrl, nil + // Create an SQS service client + svc := sqs.New(sess) + + result, err := svc.CreateQueue(&sqs.CreateQueueInput{ + QueueName: aws.String(queueName), + Attributes: map[string]*string{ + "DelaySeconds": aws.String("60"), + "MessageRetentionPeriod": aws.String("86400"), + }, + }) + if err != nil { + return "", err + } + + return *result.QueueUrl, nil } func sendMessage(sess *session.Session, queueURL *string) error { - // Create an SQS service client - svc := sqs.New(sess) + // Create an SQS service client + svc := sqs.New(sess) - currentTime := time.Now() + currentTime := time.Now() - _, err := svc.SendMessage(&sqs.SendMessageInput{ - DelaySeconds: aws.Int64(0), - MessageBody: aws.String(currentTime.Format("2006-01-02 15:04:05 Monday")), - QueueUrl: queueURL, - }) - if err != nil { - return err - } + _, err := svc.SendMessage(&sqs.SendMessageInput{ + DelaySeconds: aws.Int64(0), + MessageBody: aws.String(currentTime.Format("2006-01-02 15:04:05 Monday")), + QueueUrl: queueURL, + }) + if err != nil { + return err + } - return nil + return nil } func receiveMessage(sess *session.Session, queueURL *string) (string, error) { - // Create an SQS service client - svc := sqs.New(sess) - - result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{ - AttributeNames: []*string{ - aws.String(sqs.MessageSystemAttributeNameSentTimestamp), - }, - MessageAttributeNames: []*string{ - aws.String(sqs.QueueAttributeNameAll), - }, - QueueUrl: queueURL, - MaxNumberOfMessages: aws.Int64(1), - }) - if err != nil { - return "", err - } - - if len(result.Messages) > 0 { - return *result.Messages[0].ReceiptHandle, nil - } - - return "", nil + // Create an SQS service client + svc := sqs.New(sess) + + result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{ + AttributeNames: []*string{ + aws.String(sqs.MessageSystemAttributeNameSentTimestamp), + }, + MessageAttributeNames: []*string{ + aws.String(sqs.QueueAttributeNameAll), + }, + QueueUrl: queueURL, + MaxNumberOfMessages: aws.Int64(1), + }) + if err != nil { + return "", err + } + + if len(result.Messages) > 0 { + return *result.Messages[0].ReceiptHandle, nil + } + + return "", nil } func deleteQueue(sess *session.Session, queueURL *string) error { - // Create an SQS service client - svc := sqs.New(sess) + // Create an SQS service client + svc := sqs.New(sess) - _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ - QueueUrl: queueURL, - }) - if err != nil { - return err - } + _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ + QueueUrl: queueURL, + }) + if err != nil { + return err + } - return nil + return nil } func TestDeleteMessage(t *testing.T) { - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - // Create a session using credentials from ~/.aws/credentials - // and the Region from ~/.aws/config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - queueCreated := false - queueURL := "" - - if globalConfig.Queue == "" { - // Create a unique, random queue name - id := uuid.New() - globalConfig.Queue = "myqueue-" + id.String() - queueCreated = true - - queueURL, err = createQueue(sess, globalConfig.Queue) - if err != nil { - t.Fatal(err) - } - - t.Log("Created queue " + globalConfig.Queue) - } - - if globalConfig.MsgHandle == "" { - err = sendMessage(sess, &queueURL) - if err != nil { - t.Fatal(err) - } - - t.Log("Sent message to queue " + globalConfig.Queue) - - globalConfig.MsgHandle, err = receiveMessage(sess, &queueURL) - if err != nil { - t.Fatal(err) - } - } - - err = DeleteMessage(sess, &queueURL, &globalConfig.MsgHandle) - if err != nil { - t.Log("Could not delete message. Error:") - t.Log(err) - } - - t.Log("Deleted message") - - if queueCreated { - err = deleteQueue(sess, &queueURL) - if err != nil { - t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") - t.Fatal(err) - } - - t.Log("Deleted queue " + globalConfig.Queue) - } + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + // Create a session using credentials from ~/.aws/credentials + // and the Region from ~/.aws/config + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + queueCreated := false + queueURL := "" + + if globalConfig.Queue == "" { + // Create a unique, random queue name + id := uuid.New() + globalConfig.Queue = "myqueue-" + id.String() + queueCreated = true + + queueURL, err = createQueue(sess, globalConfig.Queue) + if err != nil { + t.Fatal(err) + } + + t.Log("Created queue " + globalConfig.Queue) + } + + if globalConfig.MsgHandle == "" { + err = sendMessage(sess, &queueURL) + if err != nil { + t.Fatal(err) + } + + t.Log("Sent message to queue " + globalConfig.Queue) + + globalConfig.MsgHandle, err = receiveMessage(sess, &queueURL) + if err != nil { + t.Fatal(err) + } + } + + err = DeleteMessage(sess, &queueURL, &globalConfig.MsgHandle) + if err != nil { + t.Log("Could not delete message. Error:") + t.Log(err) + } + + t.Log("Deleted message") + + if queueCreated { + err = deleteQueue(sess, &queueURL) + if err != nil { + t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") + t.Fatal(err) + } + + t.Log("Deleted queue " + globalConfig.Queue) + } } diff --git a/go/sqs/DeleteQueue/DeleteQueue.go b/go/sqs/DeleteQueue/DeleteQueue.go index 3f22a81885e..7e09f2da90e 100644 --- a/go/sqs/DeleteQueue/DeleteQueue.go +++ b/go/sqs/DeleteQueue/DeleteQueue.go @@ -1,113 +1,110 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sqs.go.delete_queue] package main // snippet-start:[sqs.go.delete_queue.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) + // snippet-end:[sqs.go.delete_queue.imports] // GetQueueURL gets the URL of an Amazon SQS queue // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// queueName is the name of the queue +// +// sess is the current session, which provides configuration for the SDK's service clients +// queueName is the name of the queue +// // Output: -// If success, the URL of the queue and nil -// Otherwise, an empty string and an error from the call to +// +// If success, the URL of the queue and nil +// Otherwise, an empty string and an error from the call to func GetQueueURL(sess *session.Session, queueName *string) (*sqs.GetQueueUrlOutput, error) { - // Create an SQS service client - // snippet-start:[sqs.go.delete_queue.get_queue_url] - svc := sqs.New(sess) - - result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ - QueueName: queueName, - }) - // snippet-end:[sqs.go.delete_queue.get_queue_url] - if err != nil { - return nil, err - } - - return result, nil + // Create an SQS service client + // snippet-start:[sqs.go.delete_queue.get_queue_url] + svc := sqs.New(sess) + + result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ + QueueName: queueName, + }) + // snippet-end:[sqs.go.delete_queue.get_queue_url] + if err != nil { + return nil, err + } + + return result, nil } // DeleteQueue deletes an Amazon SQS queue // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// queueURL is the URL of the queue +// +// sess is the current session, which provides configuration for the SDK's service clients +// queueURL is the URL of the queue +// // Output: -// If success, nil -// Otherwise, an error from the call to DeleteQueue +// +// If success, nil +// Otherwise, an error from the call to DeleteQueue func DeleteQueue(sess *session.Session, queueURL *string) error { - // Create an SQS service client - svc := sqs.New(sess) - - // snippet-start:[sqs.go.delete_queue.call] - _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ - QueueUrl: queueURL, - }) - // snippet-end:[sqs.go.delete_queue.call] - if err != nil { - return err - } - - return nil + // Create an SQS service client + svc := sqs.New(sess) + + // snippet-start:[sqs.go.delete_queue.call] + _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ + QueueUrl: queueURL, + }) + // snippet-end:[sqs.go.delete_queue.call] + if err != nil { + return err + } + + return nil } func main() { - // snippet-start:[sqs.go.delete_queue.args] - queue := flag.String("q", "", "The name of the queue") - flag.Parse() - - if *queue == "" { - fmt.Println("You must supply a queue name (-q QUEUE") - return - } - // snippet-end:[sqs.go.delete_queue.args] - - // Create a session that gets credential values from ~/.aws/credentials - // and the default region from ~/.aws/config - // snippet-start:[sqs.go.delete_queue.sess] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[sqs.go.delete_queue.sess] - - // Get the URL for the queue - result, err := GetQueueURL(sess, queue) - if err != nil { - fmt.Println("Got an error getting the queue URL:") - fmt.Println(err) - return - } - - // snippet-start:[sqs.go.delete_queue.get_queue_url.url] - queueURL := result.QueueUrl - // snippet-end:[sqs.go.delete_queue.get_queue_url.url] - - err = DeleteQueue(sess, queueURL) - if err != nil { - fmt.Println("Got an error deleting the queue:") - fmt.Println(err) - return - } - - fmt.Println("Deleted queue with URL " + *queueURL) + // snippet-start:[sqs.go.delete_queue.args] + queue := flag.String("q", "", "The name of the queue") + flag.Parse() + + if *queue == "" { + fmt.Println("You must supply a queue name (-q QUEUE") + return + } + // snippet-end:[sqs.go.delete_queue.args] + + // Create a session that gets credential values from ~/.aws/credentials + // and the default region from ~/.aws/config + // snippet-start:[sqs.go.delete_queue.sess] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[sqs.go.delete_queue.sess] + + // Get the URL for the queue + result, err := GetQueueURL(sess, queue) + if err != nil { + fmt.Println("Got an error getting the queue URL:") + fmt.Println(err) + return + } + + // snippet-start:[sqs.go.delete_queue.get_queue_url.url] + queueURL := result.QueueUrl + // snippet-end:[sqs.go.delete_queue.get_queue_url.url] + + err = DeleteQueue(sess, queueURL) + if err != nil { + fmt.Println("Got an error deleting the queue:") + fmt.Println(err) + return + } + + fmt.Println("Deleted queue with URL " + *queueURL) } + // snippet-end:[sqs.go.delete_queue] diff --git a/go/sqs/DeleteQueue/DeleteQueue_test.go b/go/sqs/DeleteQueue/DeleteQueue_test.go index cb960534016..91be9131336 100644 --- a/go/sqs/DeleteQueue/DeleteQueue_test.go +++ b/go/sqs/DeleteQueue/DeleteQueue_test.go @@ -1,34 +1,23 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "testing" + "encoding/json" + "io/ioutil" + "testing" - "github.com/google/uuid" + "github.com/google/uuid" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // Config defines a set of configuration values type Config struct { - Queue string `json:"Queue"` + Queue string `json:"Queue"` } // configFile defines the name of the file containing configuration values @@ -38,78 +27,78 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - // Get configuration from config.json + // Get configuration from config.json - // Get entire file as a JSON string - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + // Get entire file as a JSON string + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - // Convert []byte to string - text := string(content) + // Convert []byte to string + text := string(content) - // Marshall JSON string in text into global struct - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + // Marshall JSON string in text into global struct + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Queue: " + globalConfig.Queue) + t.Log("Queue: " + globalConfig.Queue) - return nil + return nil } func createQueue(sess *session.Session, queue *string) (string, error) { - // Create an SQS service client - svc := sqs.New(sess) - - result, err := svc.CreateQueue(&sqs.CreateQueueInput{ - QueueName: queue, - Attributes: map[string]*string{ - "DelaySeconds": aws.String("60"), - "MessageRetentionPeriod": aws.String("86400"), - }, - }) - if err != nil { - return "", err - } - - return *result.QueueUrl, nil + // Create an SQS service client + svc := sqs.New(sess) + + result, err := svc.CreateQueue(&sqs.CreateQueueInput{ + QueueName: queue, + Attributes: map[string]*string{ + "DelaySeconds": aws.String("60"), + "MessageRetentionPeriod": aws.String("86400"), + }, + }) + if err != nil { + return "", err + } + + return *result.QueueUrl, nil } func TestDeleteQueue(t *testing.T) { - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - // Create a session using credentials from ~/.aws/credentials - // and the Region from ~/.aws/config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - queueURL := "" - - if globalConfig.Queue == "" { - // Create a unique, random queue name - id := uuid.New() - globalConfig.Queue = "myqueue-" + id.String() - - queueURL, err = createQueue(sess, &globalConfig.Queue) - if err != nil { - t.Fatal(err) - } - - t.Log("Created queue " + globalConfig.Queue) - } - - err = DeleteQueue(sess, &queueURL) - if err != nil { - t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") - t.Fatal(err) - } - - t.Log("Deleted queue " + globalConfig.Queue) + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + // Create a session using credentials from ~/.aws/credentials + // and the Region from ~/.aws/config + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + queueURL := "" + + if globalConfig.Queue == "" { + // Create a unique, random queue name + id := uuid.New() + globalConfig.Queue = "myqueue-" + id.String() + + queueURL, err = createQueue(sess, &globalConfig.Queue) + if err != nil { + t.Fatal(err) + } + + t.Log("Created queue " + globalConfig.Queue) + } + + err = DeleteQueue(sess, &queueURL) + if err != nil { + t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") + t.Fatal(err) + } + + t.Log("Deleted queue " + globalConfig.Queue) } diff --git a/go/sqs/GetQueueURL/GetQueueURL.go b/go/sqs/GetQueueURL/GetQueueURL.go index ce24897b8ba..577a24a7351 100644 --- a/go/sqs/GetQueueURL/GetQueueURL.go +++ b/go/sqs/GetQueueURL/GetQueueURL.go @@ -1,80 +1,74 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sqs.go.get_queue_url] package main // snippet-start:[sqs.go.get_queue_url.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) + // snippet-end:[sqs.go.get_queue_url.imports] // GetQueueURL gets the URL of an Amazon SQS queue // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// queueName is the name of the queue +// +// sess is the current session, which provides configuration for the SDK's service clients +// queueName is the name of the queue +// // Output: -// If success, the URL of the queue and nil -// Otherwise, an empty string and an error from the call to +// +// If success, the URL of the queue and nil +// Otherwise, an empty string and an error from the call to func GetQueueURL(sess *session.Session, queue *string) (*sqs.GetQueueUrlOutput, error) { - // Create an SQS service client - // snippet-start:[sqs.go.get_queue_url.call] - svc := sqs.New(sess) + // Create an SQS service client + // snippet-start:[sqs.go.get_queue_url.call] + svc := sqs.New(sess) - result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ - QueueName: queue, - }) - // snippet-end:[sqs.go.get_queue_url.call] - if err != nil { - return nil, err - } + result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ + QueueName: queue, + }) + // snippet-end:[sqs.go.get_queue_url.call] + if err != nil { + return nil, err + } - return result, nil + return result, nil } func main() { - // snippet-start:[sqs.go.get_queue_url.args] - queue := flag.String("q", "", "The name of the queue") - flag.Parse() + // snippet-start:[sqs.go.get_queue_url.args] + queue := flag.String("q", "", "The name of the queue") + flag.Parse() - if *queue == "" { - fmt.Println("You must supply a queue name (-q QUEUE") - return - } - // snippet-end:[sqs.go.get_queue_url.args] + if *queue == "" { + fmt.Println("You must supply a queue name (-q QUEUE") + return + } + // snippet-end:[sqs.go.get_queue_url.args] - // Create a session that gets credential values from ~/.aws/credentials - // and the default region from ~/.aws/config - // snippet-start:[sqs.go.get_queue_url.sess] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[sqs.go.get_queue_url.sess] + // Create a session that gets credential values from ~/.aws/credentials + // and the default region from ~/.aws/config + // snippet-start:[sqs.go.get_queue_url.sess] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[sqs.go.get_queue_url.sess] - result, err := GetQueueURL(sess, queue) - if err != nil { - fmt.Println("Got an error getting the queue URL:") - fmt.Println(err) - return - } + result, err := GetQueueURL(sess, queue) + if err != nil { + fmt.Println("Got an error getting the queue URL:") + fmt.Println(err) + return + } - // snippet-start:[sqs.go.get_queue_url.print] - fmt.Println("URL: " + *result.QueueUrl) - // snippet-end:[sqs.go.get_queue_url.print] + // snippet-start:[sqs.go.get_queue_url.print] + fmt.Println("URL: " + *result.QueueUrl) + // snippet-end:[sqs.go.get_queue_url.print] } + // snippet-end:[sqs.go.get_queue_url] diff --git a/go/sqs/GetQueueURL/GetQueueURL_test.go b/go/sqs/GetQueueURL/GetQueueURL_test.go index e4343a65c62..0cb6e9e511f 100644 --- a/go/sqs/GetQueueURL/GetQueueURL_test.go +++ b/go/sqs/GetQueueURL/GetQueueURL_test.go @@ -1,35 +1,24 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "testing" + "encoding/json" + "io/ioutil" + "testing" - "github.com/google/uuid" + "github.com/google/uuid" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" - "github.com/aws/aws-sdk-go/service/sts" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/service/sts" ) // Config defines a set of configuration values type Config struct { - Queue string `json:"Queue"` + Queue string `json:"Queue"` } // configFile defines the name of the file containing configuration values @@ -39,131 +28,131 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - // Get configuration from config.json + // Get configuration from config.json - // Get entire file as a JSON string - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + // Get entire file as a JSON string + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - // Convert []byte to string - text := string(content) + // Convert []byte to string + text := string(content) - // Marshall JSON string in text into global struct - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + // Marshall JSON string in text into global struct + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Queue: " + globalConfig.Queue) + t.Log("Queue: " + globalConfig.Queue) - return nil + return nil } func createQueue(sess *session.Session, queueName string) (string, error) { - // Create an SQS service client - svc := sqs.New(sess) - - result, err := svc.CreateQueue(&sqs.CreateQueueInput{ - QueueName: aws.String(queueName), - Attributes: map[string]*string{ - "DelaySeconds": aws.String("60"), - "MessageRetentionPeriod": aws.String("86400"), - }, - }) - if err != nil { - return "", err - } - - return *result.QueueUrl, nil + // Create an SQS service client + svc := sqs.New(sess) + + result, err := svc.CreateQueue(&sqs.CreateQueueInput{ + QueueName: aws.String(queueName), + Attributes: map[string]*string{ + "DelaySeconds": aws.String("60"), + "MessageRetentionPeriod": aws.String("86400"), + }, + }) + if err != nil { + return "", err + } + + return *result.QueueUrl, nil } func getFakeURL(sess *session.Session, queue string) (string, error) { - // Construct URL based on known pattern - // For example, for the queue MyGroovyQueue: - // https://sqs.REGION.amazonaws.com/ACCOUNT-ID/MyGroovyQueue + // Construct URL based on known pattern + // For example, for the queue MyGroovyQueue: + // https://sqs.REGION.amazonaws.com/ACCOUNT-ID/MyGroovyQueue - region := sess.Config.Region + region := sess.Config.Region - svc := sts.New(sess) - input := &sts.GetCallerIdentityInput{} + svc := sts.New(sess) + input := &sts.GetCallerIdentityInput{} - result, err := svc.GetCallerIdentity(input) - if err != nil { - return "", err - } + result, err := svc.GetCallerIdentity(input) + if err != nil { + return "", err + } - accountID := aws.StringValue(result.Account) + accountID := aws.StringValue(result.Account) - return "https://sqs." + *region + ".amazonaws.com/" + accountID + "/" + queue, nil + return "https://sqs." + *region + ".amazonaws.com/" + accountID + "/" + queue, nil } func deleteQueue(sess *session.Session, queueURL string) error { - // Create an SQS service client - svc := sqs.New(sess) + // Create an SQS service client + svc := sqs.New(sess) - _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ - QueueUrl: aws.String(queueURL), - }) - if err != nil { - return err - } + _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ + QueueUrl: aws.String(queueURL), + }) + if err != nil { + return err + } - return nil + return nil } func TestQueue(t *testing.T) { - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - // Create a session using credentials from ~/.aws/credentials - // and the Region from ~/.aws/config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - queueCreated := false - - if globalConfig.Queue == "" { - // Create a unique, random queue name - id := uuid.New() - globalConfig.Queue = "myqueue-" + id.String() - - _, err = createQueue(sess, globalConfig.Queue) - if err != nil { - t.Fatal(err) - } - - queueCreated = true - } - - result, err := GetQueueURL(sess, &globalConfig.Queue) - if err != nil { - t.Fatal(err) - } - - fakeURL, err := getFakeURL(sess, globalConfig.Queue) - if err != nil { - t.Fatal(err) - } - - if *result.QueueUrl != fakeURL { - msg := "The URL returned by GetQueueUrl: " + *result.QueueUrl + " does not match the expected URL: " + fakeURL - t.Fatal(msg) - } - - t.Log("The URL created matched the URL retrieved: " + *result.QueueUrl) - - if queueCreated { - err = deleteQueue(sess, *result.QueueUrl) - if err != nil { - t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") - t.Fatal(err) - } - - t.Log("Deleted queue " + globalConfig.Queue) - } + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + // Create a session using credentials from ~/.aws/credentials + // and the Region from ~/.aws/config + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + queueCreated := false + + if globalConfig.Queue == "" { + // Create a unique, random queue name + id := uuid.New() + globalConfig.Queue = "myqueue-" + id.String() + + _, err = createQueue(sess, globalConfig.Queue) + if err != nil { + t.Fatal(err) + } + + queueCreated = true + } + + result, err := GetQueueURL(sess, &globalConfig.Queue) + if err != nil { + t.Fatal(err) + } + + fakeURL, err := getFakeURL(sess, globalConfig.Queue) + if err != nil { + t.Fatal(err) + } + + if *result.QueueUrl != fakeURL { + msg := "The URL returned by GetQueueUrl: " + *result.QueueUrl + " does not match the expected URL: " + fakeURL + t.Fatal(msg) + } + + t.Log("The URL created matched the URL retrieved: " + *result.QueueUrl) + + if queueCreated { + err = deleteQueue(sess, *result.QueueUrl) + if err != nil { + t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") + t.Fatal(err) + } + + t.Log("Deleted queue " + globalConfig.Queue) + } } diff --git a/go/sqs/ListQueues/ListQueues.go b/go/sqs/ListQueues/ListQueues.go index e46ecaa1f85..4b93ca00575 100644 --- a/go/sqs/ListQueues/ListQueues.go +++ b/go/sqs/ListQueues/ListQueues.go @@ -1,63 +1,54 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sqs.go.list_queues] package main // snippet-start:[sqs.go.list_queues.imports] import ( - "fmt" + "fmt" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) + // snippet-end:[sqs.go.list_queues.imports] // GetQueues returns a list of queue names func GetQueues(sess *session.Session) (*sqs.ListQueuesOutput, error) { - // Create an SQS service client - // snippet-start:[sqs.go.list_queues.call] - svc := sqs.New(sess) + // Create an SQS service client + // snippet-start:[sqs.go.list_queues.call] + svc := sqs.New(sess) - result, err := svc.ListQueues(nil) - // snippet-end:[sqs.go.list_queues.call] - if err != nil { - return nil, err - } + result, err := svc.ListQueues(nil) + // snippet-end:[sqs.go.list_queues.call] + if err != nil { + return nil, err + } - return result, nil + return result, nil } func main() { - // Create a session that gets credential values from ~/.aws/credentials - // and the default region from ~/.aws/config - // snippet-start:[sqs.go.list_queues.sess] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[sqs.go.list_queues.sess] - - result, err := GetQueues(sess) - if err != nil { - fmt.Println("Got an error retrieving queue URLs:") - fmt.Println(err) - return - } - - // snippet-start:[sqs.go.list_queues.display] - for i, url := range result.QueueUrls { - fmt.Printf("%d: %s\n", i, *url) - } - // snippet-end:[sqs.go.list_queues.display] + // Create a session that gets credential values from ~/.aws/credentials + // and the default region from ~/.aws/config + // snippet-start:[sqs.go.list_queues.sess] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[sqs.go.list_queues.sess] + + result, err := GetQueues(sess) + if err != nil { + fmt.Println("Got an error retrieving queue URLs:") + fmt.Println(err) + return + } + + // snippet-start:[sqs.go.list_queues.display] + for i, url := range result.QueueUrls { + fmt.Printf("%d: %s\n", i, *url) + } + // snippet-end:[sqs.go.list_queues.display] } + // snippet-end:[sqs.go.list_queues] diff --git a/go/sqs/ListQueues/ListQueues_test.go b/go/sqs/ListQueues/ListQueues_test.go index 96a074ab0a6..949bdb027d5 100644 --- a/go/sqs/ListQueues/ListQueues_test.go +++ b/go/sqs/ListQueues/ListQueues_test.go @@ -1,39 +1,28 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "strconv" - "testing" - "time" - - "github.com/google/uuid" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" - "github.com/aws/aws-sdk-go/service/sts" + "encoding/json" + "io/ioutil" + "strconv" + "testing" + "time" + + "github.com/google/uuid" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/service/sts" ) type Config struct { - // Set to true to create a new bucket - // and wait SleepSeconds seconds (60 seems to work) for it to appear in the list - Confirm bool `json:"Confirm"` - SleepSeconds int64 `json:"SleepSeconds"` + // Set to true to create a new bucket + // and wait SleepSeconds seconds (60 seems to work) for it to appear in the list + Confirm bool `json:"Confirm"` + SleepSeconds int64 `json:"SleepSeconds"` } var configFileName = "config.json" @@ -41,178 +30,178 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } - - text := string(content) - - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } - - if globalConfig.Confirm { - t.Log("Confirming new bucket will show up in the list") - t.Log("by waiting " + strconv.Itoa(int(globalConfig.SleepSeconds))) - } else { - t.Log("Skipping confirmation") - } - - if globalConfig.SleepSeconds < 0 { - globalConfig.SleepSeconds = 0 - } - - if globalConfig.SleepSeconds > 60 { - globalConfig.SleepSeconds = 60 - } - - return nil + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } + + text := string(content) + + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } + + if globalConfig.Confirm { + t.Log("Confirming new bucket will show up in the list") + t.Log("by waiting " + strconv.Itoa(int(globalConfig.SleepSeconds))) + } else { + t.Log("Skipping confirmation") + } + + if globalConfig.SleepSeconds < 0 { + globalConfig.SleepSeconds = 0 + } + + if globalConfig.SleepSeconds > 60 { + globalConfig.SleepSeconds = 60 + } + + return nil } func createQueue(sess *session.Session, queueName string) (string, error) { - svc := sqs.New(sess) - - result, err := svc.CreateQueue(&sqs.CreateQueueInput{ - QueueName: aws.String(queueName), - Attributes: map[string]*string{ - "DelaySeconds": aws.String("60"), - "MessageRetentionPeriod": aws.String("86400"), - }, - }) - if err != nil { - return "", err - } - - return *result.QueueUrl, nil + svc := sqs.New(sess) + + result, err := svc.CreateQueue(&sqs.CreateQueueInput{ + QueueName: aws.String(queueName), + Attributes: map[string]*string{ + "DelaySeconds": aws.String("60"), + "MessageRetentionPeriod": aws.String("86400"), + }, + }) + if err != nil { + return "", err + } + + return *result.QueueUrl, nil } func getFakeURL(sess *session.Session, queueName string) (string, error) { - // Construct URL based on known pattern - // For example, for the queue MyGroovyQueue: - // https://sqs.REGION.amazonaws.com/ACCOUNT-ID/MyGroovyQueue + // Construct URL based on known pattern + // For example, for the queue MyGroovyQueue: + // https://sqs.REGION.amazonaws.com/ACCOUNT-ID/MyGroovyQueue - region := sess.Config.Region + region := sess.Config.Region - svc := sts.New(sess) - input := &sts.GetCallerIdentityInput{} + svc := sts.New(sess) + input := &sts.GetCallerIdentityInput{} - result, err := svc.GetCallerIdentity(input) - if err != nil { - return "", err - } + result, err := svc.GetCallerIdentity(input) + if err != nil { + return "", err + } - accountID := aws.StringValue(result.Account) + accountID := aws.StringValue(result.Account) - return "https://sqs." + *region + ".amazonaws.com/" + accountID + "/" + queueName, nil + return "https://sqs." + *region + ".amazonaws.com/" + accountID + "/" + queueName, nil } func deleteQueue(sess *session.Session, queueURL string) error { - svc := sqs.New(sess) + svc := sqs.New(sess) - _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ - QueueUrl: aws.String(queueURL), - }) - if err != nil { - return err - } + _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ + QueueUrl: aws.String(queueURL), + }) + if err != nil { + return err + } - return nil + return nil } func multiplyDuration(factor int64, d time.Duration) time.Duration { - return time.Duration(factor) * d + return time.Duration(factor) * d } func TestListQueues60(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("20060102150405") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - queueName := "" - expectedURL := "" - - if globalConfig.Confirm { - id := uuid.New() - queueName = "myqueue-" + id.String() - - expectedURL, err := getFakeURL(sess, queueName) - if err != nil { - t.Fatal(err) - } - - t.Log("Queue should have URL: " + expectedURL) - } - - result, err := GetQueues(sess) - if err != nil { - t.Fatal(err) - } - - t.Log("Queue URLs:") - - for _, url := range result.QueueUrls { - t.Log(" " + *url) - - if globalConfig.Confirm { - // Make sure name is NOT in the list - if expectedURL == *url { - msg := "Got unexpected URL" - t.Fatal(msg) - } - } - } - - if globalConfig.Confirm { - // Now create the queue and make sure it IS in the list - gotURL, err := createQueue(sess, queueName) - if err != nil { - t.Fatal(err) - } - - t.Log("Created queue " + queueName) - - if gotURL == expectedURL { - t.Log("URLs match") - } - - // It takes a while for the queue to appear, so sleep Duration seconds - t.Log("Slept " + strconv.Itoa(int(globalConfig.SleepSeconds)) + " seconds") - - ts := multiplyDuration(globalConfig.SleepSeconds, time.Second) - time.Sleep(ts) - - result, err = GetQueues(sess) - if err != nil { - t.Fatal(err) - } - - t.Log("Queue URLs:") - - for _, url := range result.QueueUrls { - if gotURL == *url { - t.Log(" BINGO!") - } else { - t.Log(" " + *url) - } - } - - err = deleteQueue(sess, gotURL) - if err != nil { - t.Log("You'll have to delete queue " + queueName + " yourself") - t.Fatal(err) - } - - t.Log("Deleted queue " + queueName) - } + thisTime := time.Now() + nowString := thisTime.Format("20060102150405") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + queueName := "" + expectedURL := "" + + if globalConfig.Confirm { + id := uuid.New() + queueName = "myqueue-" + id.String() + + expectedURL, err := getFakeURL(sess, queueName) + if err != nil { + t.Fatal(err) + } + + t.Log("Queue should have URL: " + expectedURL) + } + + result, err := GetQueues(sess) + if err != nil { + t.Fatal(err) + } + + t.Log("Queue URLs:") + + for _, url := range result.QueueUrls { + t.Log(" " + *url) + + if globalConfig.Confirm { + // Make sure name is NOT in the list + if expectedURL == *url { + msg := "Got unexpected URL" + t.Fatal(msg) + } + } + } + + if globalConfig.Confirm { + // Now create the queue and make sure it IS in the list + gotURL, err := createQueue(sess, queueName) + if err != nil { + t.Fatal(err) + } + + t.Log("Created queue " + queueName) + + if gotURL == expectedURL { + t.Log("URLs match") + } + + // It takes a while for the queue to appear, so sleep Duration seconds + t.Log("Slept " + strconv.Itoa(int(globalConfig.SleepSeconds)) + " seconds") + + ts := multiplyDuration(globalConfig.SleepSeconds, time.Second) + time.Sleep(ts) + + result, err = GetQueues(sess) + if err != nil { + t.Fatal(err) + } + + t.Log("Queue URLs:") + + for _, url := range result.QueueUrls { + if gotURL == *url { + t.Log(" BINGO!") + } else { + t.Log(" " + *url) + } + } + + err = deleteQueue(sess, gotURL) + if err != nil { + t.Log("You'll have to delete queue " + queueName + " yourself") + t.Fatal(err) + } + + t.Log("Deleted queue " + queueName) + } } diff --git a/go/sqs/ReceiveLPMessage/ReceiveLPMessage.go b/go/sqs/ReceiveLPMessage/ReceiveLPMessage.go index 773221c90bc..bdcefc34db2 100644 --- a/go/sqs/ReceiveLPMessage/ReceiveLPMessage.go +++ b/go/sqs/ReceiveLPMessage/ReceiveLPMessage.go @@ -1,133 +1,128 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sqs.go.receive_lp_message] package main // snippet-start:[sqs.go.receive_lp_message.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // snippet-end:[sqs.go.receive_lp_message.imports] // GetQueueURL gets the URL of an Amazon SQS queue // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// queueName is the name of the queue +// +// sess is the current session, which provides configuration for the SDK's service clients +// queueName is the name of the queue +// // Output: -// If success, the URL of the queue and nil -// Otherwise, an empty string and an error from the call to +// +// If success, the URL of the queue and nil +// Otherwise, an empty string and an error from the call to func GetQueueURL(sess *session.Session, queue *string) (*sqs.GetQueueUrlOutput, error) { - svc := sqs.New(sess) + svc := sqs.New(sess) - result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ - QueueName: queue, - }) - if err != nil { - return nil, err - } + result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ + QueueName: queue, + }) + if err != nil { + return nil, err + } - return result, nil + return result, nil } // GetLPMessages gets the messages from an Amazon SQS long polling queue // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// queueURL is the URL of the queue +// +// sess is the current session, which provides configuration for the SDK's service clients +// queueURL is the URL of the queue +// // Output: -// If success, nil -// Otherwise, an error from the call to ReceiveMessage +// +// If success, nil +// Otherwise, an error from the call to ReceiveMessage func GetLPMessages(sess *session.Session, queueURL *string, waitTime *int64) ([]*sqs.Message, error) { - var msgs []*sqs.Message - svc := sqs.New(sess) - - // snippet-start:[sqs.go.receive_lp_message.call] - result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{ - QueueUrl: queueURL, - AttributeNames: aws.StringSlice([]string{ - "SentTimestamp", - }), - MaxNumberOfMessages: aws.Int64(1), - MessageAttributeNames: aws.StringSlice([]string{ - "All", - }), - WaitTimeSeconds: waitTime, - }) - // snippet-end:[sqs.go.receive_lp_message.call] - if err != nil { - return msgs, err - } - - return result.Messages, nil + var msgs []*sqs.Message + svc := sqs.New(sess) + + // snippet-start:[sqs.go.receive_lp_message.call] + result, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{ + QueueUrl: queueURL, + AttributeNames: aws.StringSlice([]string{ + "SentTimestamp", + }), + MaxNumberOfMessages: aws.Int64(1), + MessageAttributeNames: aws.StringSlice([]string{ + "All", + }), + WaitTimeSeconds: waitTime, + }) + // snippet-end:[sqs.go.receive_lp_message.call] + if err != nil { + return msgs, err + } + + return result.Messages, nil } func main() { - // snippet-start:[sqs.go.receive_lp_message.args] - queue := flag.String("q", "", "The name of the queue") - waitTime := flag.Int64("w", 10, "How long the queue waits for messages") - flag.Parse() - - if *queue == "" { - fmt.Println("You must supply a queue name (-q QUEUE") - return - } - - if *waitTime < 0 { - *waitTime = 0 - } - - if *waitTime > 20 { - *waitTime = 20 - } - // snippet-end:[sqs.go.receive_lp_message.args] - - // Create a session that gets credential values from ~/.aws/credentials - // and the default region from ~/.aws/config - // snippet-start:[sqs.go.receive_lp_message.sess] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[sqs.go.receive_lp_message.sess] - - result, err := GetQueueURL(sess, queue) - if err != nil { - fmt.Println("Got an error getting the queue URL:") - fmt.Println(err) - return - } - - queueURL := result.QueueUrl - - msgs, err := GetLPMessages(sess, queueURL, waitTime) - if err != nil { - fmt.Println("Got an error receiving messages:") - fmt.Println(err) - return - } - - // snippet-start:[sqs.go.receive_lp_message.display] - fmt.Println("Message IDs:") - - for _, msg := range msgs { - fmt.Println(" " + *msg.MessageId) - } - // snippet-end:[sqs.go.receive_lp_message.display] + // snippet-start:[sqs.go.receive_lp_message.args] + queue := flag.String("q", "", "The name of the queue") + waitTime := flag.Int64("w", 10, "How long the queue waits for messages") + flag.Parse() + + if *queue == "" { + fmt.Println("You must supply a queue name (-q QUEUE") + return + } + + if *waitTime < 0 { + *waitTime = 0 + } + + if *waitTime > 20 { + *waitTime = 20 + } + // snippet-end:[sqs.go.receive_lp_message.args] + + // Create a session that gets credential values from ~/.aws/credentials + // and the default region from ~/.aws/config + // snippet-start:[sqs.go.receive_lp_message.sess] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[sqs.go.receive_lp_message.sess] + + result, err := GetQueueURL(sess, queue) + if err != nil { + fmt.Println("Got an error getting the queue URL:") + fmt.Println(err) + return + } + + queueURL := result.QueueUrl + + msgs, err := GetLPMessages(sess, queueURL, waitTime) + if err != nil { + fmt.Println("Got an error receiving messages:") + fmt.Println(err) + return + } + + // snippet-start:[sqs.go.receive_lp_message.display] + fmt.Println("Message IDs:") + + for _, msg := range msgs { + fmt.Println(" " + *msg.MessageId) + } + // snippet-end:[sqs.go.receive_lp_message.display] } // snippet-end:[sqs.go.receive_lp_message] diff --git a/go/sqs/ReceiveLPMessage/ReceiveLPMessage_test.go b/go/sqs/ReceiveLPMessage/ReceiveLPMessage_test.go index 7ead6a93437..b73409802cb 100644 --- a/go/sqs/ReceiveLPMessage/ReceiveLPMessage_test.go +++ b/go/sqs/ReceiveLPMessage/ReceiveLPMessage_test.go @@ -1,39 +1,28 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "strconv" - "testing" - "time" + "encoding/json" + "io/ioutil" + "strconv" + "testing" + "time" - "github.com/google/uuid" + "github.com/google/uuid" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // Config defines a set of configuration values type Config struct { - Duration int64 `json:"Duration"` - Message string `json:"Message"` - Queue string `json:"Queue"` - WaitTime int64 `json:"WaitTime"` + Duration int64 `json:"Duration"` + Message string `json:"Message"` + Queue string `json:"Queue"` + WaitTime int64 `json:"WaitTime"` } // configFile defines the name of the file containing configuration values @@ -43,223 +32,223 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - // Get configuration from config.json + // Get configuration from config.json - // Get entire file as a JSON string - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + // Get entire file as a JSON string + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - // Convert []byte to string - text := string(content) + // Convert []byte to string + text := string(content) - // Marshall JSON string in text into global struct - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + // Marshall JSON string in text into global struct + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - if globalConfig.Duration < 1 { - globalConfig.Duration = 1 - } + if globalConfig.Duration < 1 { + globalConfig.Duration = 1 + } - if globalConfig.Duration > 12*60*60 { - globalConfig.Duration = 12 * 60 * 60 - } + if globalConfig.Duration > 12*60*60 { + globalConfig.Duration = 12 * 60 * 60 + } - if globalConfig.WaitTime < 0 { - globalConfig.WaitTime = 0 - } + if globalConfig.WaitTime < 0 { + globalConfig.WaitTime = 0 + } - if globalConfig.WaitTime > 20 { - globalConfig.WaitTime = 20 - } + if globalConfig.WaitTime > 20 { + globalConfig.WaitTime = 20 + } - if globalConfig.Message == "" { - globalConfig.Message = "Hello world" - } + if globalConfig.Message == "" { + globalConfig.Message = "Hello world" + } - t.Log("Duration (seconds): " + strconv.Itoa(int(globalConfig.Duration))) - t.Log("Message: " + globalConfig.Message) - t.Log("Queue: " + globalConfig.Queue) - t.Log("WaitTime (seconds): " + strconv.Itoa(int(globalConfig.WaitTime))) + t.Log("Duration (seconds): " + strconv.Itoa(int(globalConfig.Duration))) + t.Log("Message: " + globalConfig.Message) + t.Log("Queue: " + globalConfig.Queue) + t.Log("WaitTime (seconds): " + strconv.Itoa(int(globalConfig.WaitTime))) - return nil + return nil } func createQueue(sess *session.Session, queue *string) (string, error) { - // Create an SQS service client - svc := sqs.New(sess) - - result, err := svc.CreateQueue(&sqs.CreateQueueInput{ - QueueName: queue, - Attributes: map[string]*string{ - "DelaySeconds": aws.String("60"), - "MessageRetentionPeriod": aws.String("86400"), - }, - }) - if err != nil { - return "", err - } - - return *result.QueueUrl, nil + // Create an SQS service client + svc := sqs.New(sess) + + result, err := svc.CreateQueue(&sqs.CreateQueueInput{ + QueueName: queue, + Attributes: map[string]*string{ + "DelaySeconds": aws.String("60"), + "MessageRetentionPeriod": aws.String("86400"), + }, + }) + if err != nil { + return "", err + } + + return *result.QueueUrl, nil } func getQueueURL(sess *session.Session, queue *string) (string, error) { - // Create an SQS service client - svc := sqs.New(sess) + // Create an SQS service client + svc := sqs.New(sess) - result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ - QueueName: queue, - }) - if err != nil { - return "", err - } + result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ + QueueName: queue, + }) + if err != nil { + return "", err + } - return *result.QueueUrl, nil + return *result.QueueUrl, nil } func configureLPQueue(sess *session.Session, queueURL *string, timeout int) error { - // Create an SQS service client - svc := sqs.New(sess) - - _, err := svc.SetQueueAttributes(&sqs.SetQueueAttributesInput{ - QueueUrl: queueURL, - Attributes: aws.StringMap(map[string]string{ - "ReceiveMessageWaitTimeSeconds": strconv.Itoa(timeout), - }), - }) - if err != nil { - return err - } - - return nil + // Create an SQS service client + svc := sqs.New(sess) + + _, err := svc.SetQueueAttributes(&sqs.SetQueueAttributesInput{ + QueueUrl: queueURL, + Attributes: aws.StringMap(map[string]string{ + "ReceiveMessageWaitTimeSeconds": strconv.Itoa(timeout), + }), + }) + if err != nil { + return err + } + + return nil } func sendMessage(sess *session.Session, queueURL *string, message *string) (string, error) { - // Create an SQS service client - svc := sqs.New(sess) - - result, err := svc.SendMessage(&sqs.SendMessageInput{ - DelaySeconds: aws.Int64(10), - MessageBody: message, - QueueUrl: queueURL, - }) - if err != nil { - return "", err - } - - return *result.MessageId, nil + // Create an SQS service client + svc := sqs.New(sess) + + result, err := svc.SendMessage(&sqs.SendMessageInput{ + DelaySeconds: aws.Int64(10), + MessageBody: message, + QueueUrl: queueURL, + }) + if err != nil { + return "", err + } + + return *result.MessageId, nil } func deleteQueue(sess *session.Session, queueURL *string) error { - // Create an SQS service client - svc := sqs.New(sess) + // Create an SQS service client + svc := sqs.New(sess) - _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ - QueueUrl: queueURL, - }) - if err != nil { - return err - } + _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ + QueueUrl: queueURL, + }) + if err != nil { + return err + } - return nil + return nil } func TestReceiveLPMessages(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("20060102150405") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - // Create a session using credentials from ~/.aws/credentials - // and the Region from ~/.aws/config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - if globalConfig.Message == "" { - globalConfig.Message = "Sent " + thisTime.Format("2006-01-02 15:04:05 Monday") - } - - // If we create a queue, we also need to delete it - queueCreated := false - queueURL := "" - - if globalConfig.Queue == "" { - // Create a unique, random queue name - id := uuid.New() - globalConfig.Queue = "myqueue-" + id.String() - - queueURL, err = createQueue(sess, &globalConfig.Queue) - if err != nil { - t.Fatal(err) - } - - t.Log("Created queue " + globalConfig.Queue) - queueCreated = true - } else { - queueURL, err = getQueueURL(sess, &globalConfig.Queue) - if err != nil { - t.Fatal(err) - } - } - - // Make sure it's an LP queue - err = configureLPQueue(sess, &queueURL, int(globalConfig.WaitTime)) - if err != nil { - t.Fatal(err) - } - - msgID, err := sendMessage(sess, &queueURL, &globalConfig.Message) - if err != nil { - t.Fatal(err) - } - - t.Log("Sent message to queue " + globalConfig.Queue) - - msgs, err := GetLPMessages(sess, &queueURL, &globalConfig.WaitTime) - if err != nil { - t.Fatal(err) - } - - numMsgs := len(msgs) - - if numMsgs > 0 { - t.Log("Got " + strconv.Itoa(numMsgs) + " message(s)") - foundMsg := false - - t.Log("Message IDs:") - for _, msg := range msgs { - t.Log(" " + *msg.MessageId) - if msgID == *msg.MessageId { - t.Log("Got message: " + *msg.Body) - foundMsg = true - break - } - } - - if foundMsg { - t.Log("Found sent message") - } else { - t.Log("Did NOT find message") - } - } else { - t.Log("Did not get any messages") - } - - if queueCreated { - err = deleteQueue(sess, &queueURL) - if err != nil { - t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") - t.Fatal(err) - } - - t.Log("Deleted queue " + globalConfig.Queue) - } + thisTime := time.Now() + nowString := thisTime.Format("20060102150405") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + // Create a session using credentials from ~/.aws/credentials + // and the Region from ~/.aws/config + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + if globalConfig.Message == "" { + globalConfig.Message = "Sent " + thisTime.Format("2006-01-02 15:04:05 Monday") + } + + // If we create a queue, we also need to delete it + queueCreated := false + queueURL := "" + + if globalConfig.Queue == "" { + // Create a unique, random queue name + id := uuid.New() + globalConfig.Queue = "myqueue-" + id.String() + + queueURL, err = createQueue(sess, &globalConfig.Queue) + if err != nil { + t.Fatal(err) + } + + t.Log("Created queue " + globalConfig.Queue) + queueCreated = true + } else { + queueURL, err = getQueueURL(sess, &globalConfig.Queue) + if err != nil { + t.Fatal(err) + } + } + + // Make sure it's an LP queue + err = configureLPQueue(sess, &queueURL, int(globalConfig.WaitTime)) + if err != nil { + t.Fatal(err) + } + + msgID, err := sendMessage(sess, &queueURL, &globalConfig.Message) + if err != nil { + t.Fatal(err) + } + + t.Log("Sent message to queue " + globalConfig.Queue) + + msgs, err := GetLPMessages(sess, &queueURL, &globalConfig.WaitTime) + if err != nil { + t.Fatal(err) + } + + numMsgs := len(msgs) + + if numMsgs > 0 { + t.Log("Got " + strconv.Itoa(numMsgs) + " message(s)") + foundMsg := false + + t.Log("Message IDs:") + for _, msg := range msgs { + t.Log(" " + *msg.MessageId) + if msgID == *msg.MessageId { + t.Log("Got message: " + *msg.Body) + foundMsg = true + break + } + } + + if foundMsg { + t.Log("Found sent message") + } else { + t.Log("Did NOT find message") + } + } else { + t.Log("Did not get any messages") + } + + if queueCreated { + err = deleteQueue(sess, &queueURL) + if err != nil { + t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") + t.Fatal(err) + } + + t.Log("Deleted queue " + globalConfig.Queue) + } } diff --git a/go/sqs/ReceiveMessage/ReceiveMessage.go b/go/sqs/ReceiveMessage/ReceiveMessage.go index 9ce5773f2d2..b78ea1f556d 100644 --- a/go/sqs/ReceiveMessage/ReceiveMessage.go +++ b/go/sqs/ReceiveMessage/ReceiveMessage.go @@ -1,135 +1,132 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sqs.go.receive_messages] package main // snippet-start:[sqs.go.receive_messages.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) + // snippet-end:[sqs.go.receive_messages.imports] // GetQueueURL gets the URL of an Amazon SQS queue // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// queueName is the name of the queue +// +// sess is the current session, which provides configuration for the SDK's service clients +// queueName is the name of the queue +// // Output: -// If success, the URL of the queue and nil -// Otherwise, an empty string and an error from the call to +// +// If success, the URL of the queue and nil +// Otherwise, an empty string and an error from the call to func GetQueueURL(sess *session.Session, queue *string) (*sqs.GetQueueUrlOutput, error) { - // snippet-start:[sqs.go.receive_messages.queue_url] - svc := sqs.New(sess) - - urlResult, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ - QueueName: queue, - }) - // snippet-end:[sqs.go.receive_messages.queue_url] - if err != nil { - return nil, err - } - - return urlResult, nil + // snippet-start:[sqs.go.receive_messages.queue_url] + svc := sqs.New(sess) + + urlResult, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ + QueueName: queue, + }) + // snippet-end:[sqs.go.receive_messages.queue_url] + if err != nil { + return nil, err + } + + return urlResult, nil } // GetMessages gets the messages from an Amazon SQS queue // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// queueURL is the URL of the queue -// timeout is how long, in seconds, the message is unavailable to other consumers +// +// sess is the current session, which provides configuration for the SDK's service clients +// queueURL is the URL of the queue +// timeout is how long, in seconds, the message is unavailable to other consumers +// // Output: -// If success, the latest message and nil -// Otherwise, nil and an error from the call to ReceiveMessage +// +// If success, the latest message and nil +// Otherwise, nil and an error from the call to ReceiveMessage func GetMessages(sess *session.Session, queueURL *string, timeout *int64) (*sqs.ReceiveMessageOutput, error) { - // Create an SQS service client - svc := sqs.New(sess) - - // snippet-start:[sqs.go.receive_messages.call] - msgResult, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{ - AttributeNames: []*string{ - aws.String(sqs.MessageSystemAttributeNameSentTimestamp), - }, - MessageAttributeNames: []*string{ - aws.String(sqs.QueueAttributeNameAll), - }, - QueueUrl: queueURL, - MaxNumberOfMessages: aws.Int64(1), - VisibilityTimeout: timeout, - }) - // snippet-end:[sqs.go.receive_messages.call] - if err != nil { - return nil, err - } - - return msgResult, nil + // Create an SQS service client + svc := sqs.New(sess) + + // snippet-start:[sqs.go.receive_messages.call] + msgResult, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{ + AttributeNames: []*string{ + aws.String(sqs.MessageSystemAttributeNameSentTimestamp), + }, + MessageAttributeNames: []*string{ + aws.String(sqs.QueueAttributeNameAll), + }, + QueueUrl: queueURL, + MaxNumberOfMessages: aws.Int64(1), + VisibilityTimeout: timeout, + }) + // snippet-end:[sqs.go.receive_messages.call] + if err != nil { + return nil, err + } + + return msgResult, nil } func main() { - // snippet-start:[sqs.go.receive_messages.args] - queue := flag.String("q", "", "The name of the queue") - timeout := flag.Int64("t", 5, "How long, in seconds, that the message is hidden from others") - flag.Parse() - - if *queue == "" { - fmt.Println("You must supply the name of a queue (-q QUEUE)") - return - } - - if *timeout < 0 { - *timeout = 0 - } - - if *timeout > 12*60*60 { - *timeout = 12 * 60 * 60 - } - // snippet-end:[sqs.go.receive_messages.args] - - // Create a session that gets credential values from ~/.aws/credentials - // and the default region from ~/.aws/config - // snippet-start:[sqs.go.receive_messages.sess] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[sqs.go.receive_messages.sess] - - // Get URL of queue - urlResult, err := GetQueueURL(sess, queue) - if err != nil { - fmt.Println("Got an error getting the queue URL:") - fmt.Println(err) - return - } - - // snippet-start:[sqs.go.receive_message.url] - queueURL := urlResult.QueueUrl - // snippet-end:[sqs.go.receive_message.url] - - msgResult, err := GetMessages(sess, queueURL, timeout) - if err != nil { - fmt.Println("Got an error receiving messages:") - fmt.Println(err) - return - } - - fmt.Println("Message ID: " + *msgResult.Messages[0].MessageId) - - // snippet-start:[sqs.go.receive_messages.print_handle] - fmt.Println("Message Handle: " + *msgResult.Messages[0].ReceiptHandle) - // snippet-end:[sqs.go.receive_messages.print_handle] + // snippet-start:[sqs.go.receive_messages.args] + queue := flag.String("q", "", "The name of the queue") + timeout := flag.Int64("t", 5, "How long, in seconds, that the message is hidden from others") + flag.Parse() + + if *queue == "" { + fmt.Println("You must supply the name of a queue (-q QUEUE)") + return + } + + if *timeout < 0 { + *timeout = 0 + } + + if *timeout > 12*60*60 { + *timeout = 12 * 60 * 60 + } + // snippet-end:[sqs.go.receive_messages.args] + + // Create a session that gets credential values from ~/.aws/credentials + // and the default region from ~/.aws/config + // snippet-start:[sqs.go.receive_messages.sess] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[sqs.go.receive_messages.sess] + + // Get URL of queue + urlResult, err := GetQueueURL(sess, queue) + if err != nil { + fmt.Println("Got an error getting the queue URL:") + fmt.Println(err) + return + } + + // snippet-start:[sqs.go.receive_message.url] + queueURL := urlResult.QueueUrl + // snippet-end:[sqs.go.receive_message.url] + + msgResult, err := GetMessages(sess, queueURL, timeout) + if err != nil { + fmt.Println("Got an error receiving messages:") + fmt.Println(err) + return + } + + fmt.Println("Message ID: " + *msgResult.Messages[0].MessageId) + + // snippet-start:[sqs.go.receive_messages.print_handle] + fmt.Println("Message Handle: " + *msgResult.Messages[0].ReceiptHandle) + // snippet-end:[sqs.go.receive_messages.print_handle] } + // snippet-end:[sqs.go.receive_messages] diff --git a/go/sqs/ReceiveMessage/ReceiveMessage_test.go b/go/sqs/ReceiveMessage/ReceiveMessage_test.go index 59bef0cfea6..3bd3022f1d8 100644 --- a/go/sqs/ReceiveMessage/ReceiveMessage_test.go +++ b/go/sqs/ReceiveMessage/ReceiveMessage_test.go @@ -1,39 +1,28 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "strconv" - "testing" - "time" + "encoding/json" + "io/ioutil" + "strconv" + "testing" + "time" - "github.com/google/uuid" + "github.com/google/uuid" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // Config defines a set of configuration values type Config struct { - Message string `json:"Message"` - Queue string `json:"Queue"` - SleepSeconds int64 `json:"SleepSeconds"` - Timeout int64 `json:"Timeout"` + Message string `json:"Message"` + Queue string `json:"Queue"` + SleepSeconds int64 `json:"SleepSeconds"` + Timeout int64 `json:"Timeout"` } // configFile defines the name of the file containing configuration values @@ -43,158 +32,158 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - // Get configuration from config.json + // Get configuration from config.json - // Get entire file as a JSON string - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + // Get entire file as a JSON string + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - // Convert []byte to string - text := string(content) + // Convert []byte to string + text := string(content) - // Marshall JSON string in text into global struct - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + // Marshall JSON string in text into global struct + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - if globalConfig.Timeout < 0 { - globalConfig.Timeout = 0 - } + if globalConfig.Timeout < 0 { + globalConfig.Timeout = 0 + } - if globalConfig.Timeout > 12*60*60 { - globalConfig.Timeout = 12 * 60 * 60 - } + if globalConfig.Timeout > 12*60*60 { + globalConfig.Timeout = 12 * 60 * 60 + } - t.Log("Message: " + globalConfig.Message) - t.Log("Queue: " + globalConfig.Queue) - t.Log("SleepSeconds: " + strconv.Itoa(int(globalConfig.SleepSeconds))) - t.Log("Timeout (seconds): " + strconv.Itoa(int(globalConfig.Timeout))) + t.Log("Message: " + globalConfig.Message) + t.Log("Queue: " + globalConfig.Queue) + t.Log("SleepSeconds: " + strconv.Itoa(int(globalConfig.SleepSeconds))) + t.Log("Timeout (seconds): " + strconv.Itoa(int(globalConfig.Timeout))) - return nil + return nil } func createQueue(sess *session.Session, queue *string) (string, error) { - // Create an SQS service client - svc := sqs.New(sess) - - result, err := svc.CreateQueue(&sqs.CreateQueueInput{ - QueueName: queue, - Attributes: map[string]*string{ - "DelaySeconds": aws.String("60"), - "MessageRetentionPeriod": aws.String("86400"), - }, - }) - if err != nil { - return "", err - } - - return *result.QueueUrl, nil + // Create an SQS service client + svc := sqs.New(sess) + + result, err := svc.CreateQueue(&sqs.CreateQueueInput{ + QueueName: queue, + Attributes: map[string]*string{ + "DelaySeconds": aws.String("60"), + "MessageRetentionPeriod": aws.String("86400"), + }, + }) + if err != nil { + return "", err + } + + return *result.QueueUrl, nil } func sendMessage(sess *session.Session, queueURL *string, message *string) (string, error) { - // Create an SQS service client - svc := sqs.New(sess) - - result, err := svc.SendMessage(&sqs.SendMessageInput{ - DelaySeconds: aws.Int64(10), - MessageBody: message, - QueueUrl: queueURL, - }) - if err != nil { - return "", err - } - - return *result.MessageId, nil + // Create an SQS service client + svc := sqs.New(sess) + + result, err := svc.SendMessage(&sqs.SendMessageInput{ + DelaySeconds: aws.Int64(10), + MessageBody: message, + QueueUrl: queueURL, + }) + if err != nil { + return "", err + } + + return *result.MessageId, nil } func multiplyDuration(factor int64, d time.Duration) time.Duration { - return time.Duration(factor) * d + return time.Duration(factor) * d } func deleteQueue(sess *session.Session, queueURL *string) error { - // Create an SQS service client - svc := sqs.New(sess) + // Create an SQS service client + svc := sqs.New(sess) - _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ - QueueUrl: queueURL, - }) - if err != nil { - return err - } + _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ + QueueUrl: queueURL, + }) + if err != nil { + return err + } - return nil + return nil } func TestReceiveMessages(t *testing.T) { - thisTime := time.Now() - nowString := thisTime.Format("2006-01-02 15:04:05 Monday") - t.Log("Starting unit test at " + nowString) - - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - // Create a session using credentials from ~/.aws/credentials - // and the Region from ~/.aws/config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - if globalConfig.Message == "" { - globalConfig.Message = "Sent " + thisTime.Format("2006-01-02 15:04:05 Monday") - } - - queueCreated := false - queueURL := "" - - if globalConfig.Queue == "" { - // Create a unique, random queue name - id := uuid.New() - globalConfig.Queue = "myqueue-" + id.String() - - queueURL, err = createQueue(sess, &globalConfig.Queue) - if err != nil { - t.Fatal(err) - } - - queueCreated = true - t.Log("Created queue " + globalConfig.Queue) - } - - msgID, err := sendMessage(sess, &queueURL, &globalConfig.Message) - if err != nil { - t.Fatal(err) - } - - t.Log("Sent message with ID " + msgID + " to queue " + globalConfig.Queue) - - ts := multiplyDuration(globalConfig.SleepSeconds, time.Second) - time.Sleep(ts) - - t.Log("Slept " + strconv.Itoa(int(globalConfig.SleepSeconds)) + " second(s)") - - result, err := GetMessages(sess, &queueURL, &globalConfig.Timeout) - if err != nil { - t.Fatal(err) - } - - if msgID == *result.Messages[0].MessageId { - t.Log("Found sent message") - } else { - t.Log("Did NOT find message") - } - - if queueCreated { - err = deleteQueue(sess, &queueURL) - if err != nil { - t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") - t.Fatal(err) - } - - t.Log("Deleted queue " + globalConfig.Queue) - } + thisTime := time.Now() + nowString := thisTime.Format("2006-01-02 15:04:05 Monday") + t.Log("Starting unit test at " + nowString) + + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + // Create a session using credentials from ~/.aws/credentials + // and the Region from ~/.aws/config + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + if globalConfig.Message == "" { + globalConfig.Message = "Sent " + thisTime.Format("2006-01-02 15:04:05 Monday") + } + + queueCreated := false + queueURL := "" + + if globalConfig.Queue == "" { + // Create a unique, random queue name + id := uuid.New() + globalConfig.Queue = "myqueue-" + id.String() + + queueURL, err = createQueue(sess, &globalConfig.Queue) + if err != nil { + t.Fatal(err) + } + + queueCreated = true + t.Log("Created queue " + globalConfig.Queue) + } + + msgID, err := sendMessage(sess, &queueURL, &globalConfig.Message) + if err != nil { + t.Fatal(err) + } + + t.Log("Sent message with ID " + msgID + " to queue " + globalConfig.Queue) + + ts := multiplyDuration(globalConfig.SleepSeconds, time.Second) + time.Sleep(ts) + + t.Log("Slept " + strconv.Itoa(int(globalConfig.SleepSeconds)) + " second(s)") + + result, err := GetMessages(sess, &queueURL, &globalConfig.Timeout) + if err != nil { + t.Fatal(err) + } + + if msgID == *result.Messages[0].MessageId { + t.Log("Found sent message") + } else { + t.Log("Did NOT find message") + } + + if queueCreated { + err = deleteQueue(sess, &queueURL) + if err != nil { + t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") + t.Fatal(err) + } + + t.Log("Deleted queue " + globalConfig.Queue) + } } diff --git a/go/sqs/SendMessage/SendMessage.go b/go/sqs/SendMessage/SendMessage.go index 505be692e6c..f2af594f70a 100644 --- a/go/sqs/SendMessage/SendMessage.go +++ b/go/sqs/SendMessage/SendMessage.go @@ -1,126 +1,123 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sqs.go.send_message] package main // snippet-start:[sqs.go.send_message.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) + // snippet-end:[sqs.go.send_message.imports] // GetQueueURL gets the URL of an Amazon SQS queue // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// queueName is the name of the queue +// +// sess is the current session, which provides configuration for the SDK's service clients +// queueName is the name of the queue +// // Output: -// If success, the URL of the queue and nil -// Otherwise, an empty string and an error from the call to +// +// If success, the URL of the queue and nil +// Otherwise, an empty string and an error from the call to func GetQueueURL(sess *session.Session, queue *string) (*sqs.GetQueueUrlOutput, error) { - // Create an SQS service client - svc := sqs.New(sess) + // Create an SQS service client + svc := sqs.New(sess) - result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ - QueueName: queue, - }) - if err != nil { - return nil, err - } + result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ + QueueName: queue, + }) + if err != nil { + return nil, err + } - return result, nil + return result, nil } // SendMsg sends a message to an Amazon SQS queue // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// queueURL is the URL of the queue +// +// sess is the current session, which provides configuration for the SDK's service clients +// queueURL is the URL of the queue +// // Output: -// If success, nil -// Otherwise, an error from the call to SendMessage +// +// If success, nil +// Otherwise, an error from the call to SendMessage func SendMsg(sess *session.Session, queueURL *string) error { - // Create an SQS service client - // snippet-start:[sqs.go.send_message.call] - svc := sqs.New(sess) - - _, err := svc.SendMessage(&sqs.SendMessageInput{ - DelaySeconds: aws.Int64(10), - MessageAttributes: map[string]*sqs.MessageAttributeValue{ - "Title": &sqs.MessageAttributeValue{ - DataType: aws.String("String"), - StringValue: aws.String("The Whistler"), - }, - "Author": &sqs.MessageAttributeValue{ - DataType: aws.String("String"), - StringValue: aws.String("John Grisham"), - }, - "WeeksOn": &sqs.MessageAttributeValue{ - DataType: aws.String("Number"), - StringValue: aws.String("6"), - }, - }, - MessageBody: aws.String("Information about current NY Times fiction bestseller for week of 12/11/2016."), - QueueUrl: queueURL, - }) - // snippet-end:[sqs.go.send_message.call] - if err != nil { - return err - } - - return nil + // Create an SQS service client + // snippet-start:[sqs.go.send_message.call] + svc := sqs.New(sess) + + _, err := svc.SendMessage(&sqs.SendMessageInput{ + DelaySeconds: aws.Int64(10), + MessageAttributes: map[string]*sqs.MessageAttributeValue{ + "Title": &sqs.MessageAttributeValue{ + DataType: aws.String("String"), + StringValue: aws.String("The Whistler"), + }, + "Author": &sqs.MessageAttributeValue{ + DataType: aws.String("String"), + StringValue: aws.String("John Grisham"), + }, + "WeeksOn": &sqs.MessageAttributeValue{ + DataType: aws.String("Number"), + StringValue: aws.String("6"), + }, + }, + MessageBody: aws.String("Information about current NY Times fiction bestseller for week of 12/11/2016."), + QueueUrl: queueURL, + }) + // snippet-end:[sqs.go.send_message.call] + if err != nil { + return err + } + + return nil } func main() { - // snippet-start:[sqs.go.send_message.args] - queue := flag.String("q", "", "The name of the queue") - flag.Parse() - - if *queue == "" { - fmt.Println("You must supply the name of a queue (-q QUEUE)") - return - } - // snippet-end:[sqs.go.send_message.args] - - // Create a session that gets credential values from ~/.aws/credentials - // and the default region from ~/.aws/config - // snippet-start:[sqs.go.send_message.sess] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[sqs.go.send_message.sess] - - // Get URL of queue - result, err := GetQueueURL(sess, queue) - if err != nil { - fmt.Println("Got an error getting the queue URL:") - fmt.Println(err) - return - } - - queueURL := result.QueueUrl - - err = SendMsg(sess, queueURL) - if err != nil { - fmt.Println("Got an error sending the message:") - fmt.Println(err) - return - } - - fmt.Println("Sent message to queue ") + // snippet-start:[sqs.go.send_message.args] + queue := flag.String("q", "", "The name of the queue") + flag.Parse() + + if *queue == "" { + fmt.Println("You must supply the name of a queue (-q QUEUE)") + return + } + // snippet-end:[sqs.go.send_message.args] + + // Create a session that gets credential values from ~/.aws/credentials + // and the default region from ~/.aws/config + // snippet-start:[sqs.go.send_message.sess] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[sqs.go.send_message.sess] + + // Get URL of queue + result, err := GetQueueURL(sess, queue) + if err != nil { + fmt.Println("Got an error getting the queue URL:") + fmt.Println(err) + return + } + + queueURL := result.QueueUrl + + err = SendMsg(sess, queueURL) + if err != nil { + fmt.Println("Got an error sending the message:") + fmt.Println(err) + return + } + + fmt.Println("Sent message to queue ") } + // snippet-end:[sqs.go.send_message] diff --git a/go/sqs/SendMessage/SendMessage_test.go b/go/sqs/SendMessage/SendMessage_test.go index 0eb48ebb40e..638ec86e47c 100644 --- a/go/sqs/SendMessage/SendMessage_test.go +++ b/go/sqs/SendMessage/SendMessage_test.go @@ -1,34 +1,23 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "testing" + "encoding/json" + "io/ioutil" + "testing" - "github.com/google/uuid" + "github.com/google/uuid" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // Config defines a set of configuration values type Config struct { - QueueURL string `json:"QueueURL"` + QueueURL string `json:"QueueURL"` } // configFile defines the name of the file containing configuration values @@ -38,104 +27,104 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - // Get configuration from config.json + // Get configuration from config.json - // Get entire file as a JSON string - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + // Get entire file as a JSON string + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - // Convert []byte to string - text := string(content) + // Convert []byte to string + text := string(content) - // Marshall JSON string in text into global struct - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + // Marshall JSON string in text into global struct + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("QueueURL: " + globalConfig.QueueURL) + t.Log("QueueURL: " + globalConfig.QueueURL) - return nil + return nil } func createQueue(sess *session.Session, queueName *string) (string, error) { - // Create an SQS service client - svc := sqs.New(sess) - - result, err := svc.CreateQueue(&sqs.CreateQueueInput{ - QueueName: queueName, - Attributes: map[string]*string{ - "DelaySeconds": aws.String("60"), - "MessageRetentionPeriod": aws.String("86400"), - }, - }) - if err != nil { - return "", err - } - - return *result.QueueUrl, nil + // Create an SQS service client + svc := sqs.New(sess) + + result, err := svc.CreateQueue(&sqs.CreateQueueInput{ + QueueName: queueName, + Attributes: map[string]*string{ + "DelaySeconds": aws.String("60"), + "MessageRetentionPeriod": aws.String("86400"), + }, + }) + if err != nil { + return "", err + } + + return *result.QueueUrl, nil } func deleteQueue(sess *session.Session, queueURL *string) error { - // Create an SQS service client - svc := sqs.New(sess) + // Create an SQS service client + svc := sqs.New(sess) - _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ - QueueUrl: queueURL, - }) - if err != nil { - return err - } + _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ + QueueUrl: queueURL, + }) + if err != nil { + return err + } - return nil + return nil } func TestQueue(t *testing.T) { - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - // Create a session using credentials from ~/.aws/credentials - // and the Region from ~/.aws/config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - url := "" - queueCreated := false - queueName := "" - - if globalConfig.QueueURL == "" { - // Create a unique, random queue name - id := uuid.New() - queueName = "myqueue-" + id.String() - - url, err = createQueue(sess, &queueName) - if err != nil { - t.Fatal(err) - } - - queueCreated = true - t.Log("Created queue " + queueName) - } - - err = SendMsg(sess, &url) - if err != nil { - t.Fatal(err) - } - - t.Log("Sent message to queue " + queueName) - - if queueCreated { - err = deleteQueue(sess, &url) - if err != nil { - t.Log("You'll have to delete queue " + queueName + " yourself") - t.Fatal(err) - } - - t.Log("Deleted queue " + queueName) - } + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + // Create a session using credentials from ~/.aws/credentials + // and the Region from ~/.aws/config + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + url := "" + queueCreated := false + queueName := "" + + if globalConfig.QueueURL == "" { + // Create a unique, random queue name + id := uuid.New() + queueName = "myqueue-" + id.String() + + url, err = createQueue(sess, &queueName) + if err != nil { + t.Fatal(err) + } + + queueCreated = true + t.Log("Created queue " + queueName) + } + + err = SendMsg(sess, &url) + if err != nil { + t.Fatal(err) + } + + t.Log("Sent message to queue " + queueName) + + if queueCreated { + err = deleteQueue(sess, &url) + if err != nil { + t.Log("You'll have to delete queue " + queueName + " yourself") + t.Fatal(err) + } + + t.Log("Deleted queue " + queueName) + } } diff --git a/go/sqs/SendReceiveLongPolling/SendReceiveLongPolling.go b/go/sqs/SendReceiveLongPolling/SendReceiveLongPolling.go index f8593f4445b..6b42db222df 100644 --- a/go/sqs/SendReceiveLongPolling/SendReceiveLongPolling.go +++ b/go/sqs/SendReceiveLongPolling/SendReceiveLongPolling.go @@ -1,183 +1,183 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sqs.go.send_receive_long_polling] package main // snippet-start:[sqs.go.send_receive_long_polling.imports] import ( - "flag" - "fmt" + "flag" + "fmt" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) + // snippet-end:[sqs.go.send_receive_long_polling.imports] // GetQueueURL gets the URL of an Amazon SQS queue // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// queueName is the name of the queue +// +// sess is the current session, which provides configuration for the SDK's service clients +// queueName is the name of the queue +// // Output: -// If success, the URL of the queue and nil -// Otherwise, an empty string and an error from the call to +// +// If success, the URL of the queue and nil +// Otherwise, an empty string and an error from the call to func GetQueueURL(sess *session.Session, queue *string) (*sqs.GetQueueUrlOutput, error) { - // snippet-start:[sqs.go.send_receive_long_polling.get_url] - svc := sqs.New(sess) - - result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ - QueueName: queue, - }) - // snippet-end:[sqs.go.send_receive_long_polling.get_url] - if err != nil { - return nil, err - } - - return result, nil + // snippet-start:[sqs.go.send_receive_long_polling.get_url] + svc := sqs.New(sess) + + result, err := svc.GetQueueUrl(&sqs.GetQueueUrlInput{ + QueueName: queue, + }) + // snippet-end:[sqs.go.send_receive_long_polling.get_url] + if err != nil { + return nil, err + } + + return result, nil } // SendMsg sends a message to an Amazon SQS queue // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// queueURL is the URL of the queue +// +// sess is the current session, which provides configuration for the SDK's service clients +// queueURL is the URL of the queue +// // Output: -// If success, nil -// Otherwise, an error from the call to DeleteQueue +// +// If success, nil +// Otherwise, an error from the call to DeleteQueue func SendMsg(sess *session.Session, queueURL *string) error { - // Create an SQS service client - // snippet-start:[sqs.go.send_receive_long_polling.call] - svc := sqs.New(sess) - - _, err := svc.SendMessage(&sqs.SendMessageInput{ - DelaySeconds: aws.Int64(10), - MessageAttributes: map[string]*sqs.MessageAttributeValue{ - "Title": &sqs.MessageAttributeValue{ - DataType: aws.String("String"), - StringValue: aws.String("The Whistler"), - }, - "Author": &sqs.MessageAttributeValue{ - DataType: aws.String("String"), - StringValue: aws.String("John Grisham"), - }, - "WeeksOn": &sqs.MessageAttributeValue{ - DataType: aws.String("Number"), - StringValue: aws.String("6"), - }, - }, - MessageBody: aws.String("Information about current NY Times fiction bestseller for week of 12/11/2016."), - QueueUrl: queueURL, - }) - // snippet-end:[sqs.go.send_receive_long_polling.call] - if err != nil { - return err - } - - return nil + // Create an SQS service client + // snippet-start:[sqs.go.send_receive_long_polling.call] + svc := sqs.New(sess) + + _, err := svc.SendMessage(&sqs.SendMessageInput{ + DelaySeconds: aws.Int64(10), + MessageAttributes: map[string]*sqs.MessageAttributeValue{ + "Title": &sqs.MessageAttributeValue{ + DataType: aws.String("String"), + StringValue: aws.String("The Whistler"), + }, + "Author": &sqs.MessageAttributeValue{ + DataType: aws.String("String"), + StringValue: aws.String("John Grisham"), + }, + "WeeksOn": &sqs.MessageAttributeValue{ + DataType: aws.String("Number"), + StringValue: aws.String("6"), + }, + }, + MessageBody: aws.String("Information about current NY Times fiction bestseller for week of 12/11/2016."), + QueueUrl: queueURL, + }) + // snippet-end:[sqs.go.send_receive_long_polling.call] + if err != nil { + return err + } + + return nil } // GetLPMessages gets the messages from an Amazon SQS long polling queue // Inputs: -// sess is the current session, which provides configuration for the SDK's service clients -// queueURL is the URL of the queue +// +// sess is the current session, which provides configuration for the SDK's service clients +// queueURL is the URL of the queue +// // Output: -// If success, nil -// Otherwise, an error from the call to ReceiveMessage +// +// If success, nil +// Otherwise, an error from the call to ReceiveMessage func GetLPMessages(sess *session.Session, queueURL *string, waitTime *int64) (*sqs.ReceiveMessageOutput, error) { - // Create an SQS service client - svc := sqs.New(sess) - - // snippet-start:[sqs.go.send_receive_long_polling.call2] - results, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{ - QueueUrl: queueURL, - AttributeNames: aws.StringSlice([]string{ - "SentTimestamp", - }), - MaxNumberOfMessages: aws.Int64(1), - MessageAttributeNames: aws.StringSlice([]string{ - "All", - }), - WaitTimeSeconds: waitTime, - }) - // snippet-end:[sqs.go.send_receive_long_polling.call2] - if err != nil { - return nil, err - } - - return results, nil + // Create an SQS service client + svc := sqs.New(sess) + + // snippet-start:[sqs.go.send_receive_long_polling.call2] + results, err := svc.ReceiveMessage(&sqs.ReceiveMessageInput{ + QueueUrl: queueURL, + AttributeNames: aws.StringSlice([]string{ + "SentTimestamp", + }), + MaxNumberOfMessages: aws.Int64(1), + MessageAttributeNames: aws.StringSlice([]string{ + "All", + }), + WaitTimeSeconds: waitTime, + }) + // snippet-end:[sqs.go.send_receive_long_polling.call2] + if err != nil { + return nil, err + } + + return results, nil } func main() { - // snippet-start:[sqs.go.send_receive_long_polling.args] - queue := flag.String("q", "", "The name of the queue") - waitTime := flag.Int64("w", 0, "How long to wait for messages") - flag.Parse() - - if *queue == "" { - fmt.Println("You must supply a queue name (-q QUEUE") - return - } - - if *waitTime < 0 { - *waitTime = 0 - } - - if *waitTime > 20 { - *waitTime = 20 - } - // snippet-end:[sqs.go.send_receive_long_polling.args] - - // Create a session that gets credential values from ~/.aws/credentials - // and the default region from ~/.aws/config - // snippet-start:[sqs.go.send_receive_long_polling.sess] - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - // snippet-end:[sqs.go.send_receive_long_polling.sess] - - // Get URL of queue - result, err := GetQueueURL(sess, queue) - if err != nil { - fmt.Println("Got an error getting the queue URL:") - fmt.Println(err) - return - } - - queueURL := result.QueueUrl - - err = SendMsg(sess, queueURL) - if err != nil { - fmt.Println("Got an error sending the message:") - fmt.Println(err) - return - } - - fmt.Println("Sent message to queue with URL " + *queueURL) - - // Get messages and show them - results, err := GetLPMessages(sess, queueURL, waitTime) - if err != nil { - fmt.Println("Got error retrieving LP messages:") - fmt.Println(err) - return - } - - // snippet-start:[sqs.go.send_receive_long_polling.print_msgs] - fmt.Println("Message IDs:") - - for _, msg := range results.Messages { - fmt.Println(" " + *msg.MessageId) - } - // snippet-end:[sqs.go.send_receive_long_polling.print_msgs] + // snippet-start:[sqs.go.send_receive_long_polling.args] + queue := flag.String("q", "", "The name of the queue") + waitTime := flag.Int64("w", 0, "How long to wait for messages") + flag.Parse() + + if *queue == "" { + fmt.Println("You must supply a queue name (-q QUEUE") + return + } + + if *waitTime < 0 { + *waitTime = 0 + } + + if *waitTime > 20 { + *waitTime = 20 + } + // snippet-end:[sqs.go.send_receive_long_polling.args] + + // Create a session that gets credential values from ~/.aws/credentials + // and the default region from ~/.aws/config + // snippet-start:[sqs.go.send_receive_long_polling.sess] + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + // snippet-end:[sqs.go.send_receive_long_polling.sess] + + // Get URL of queue + result, err := GetQueueURL(sess, queue) + if err != nil { + fmt.Println("Got an error getting the queue URL:") + fmt.Println(err) + return + } + + queueURL := result.QueueUrl + + err = SendMsg(sess, queueURL) + if err != nil { + fmt.Println("Got an error sending the message:") + fmt.Println(err) + return + } + + fmt.Println("Sent message to queue with URL " + *queueURL) + + // Get messages and show them + results, err := GetLPMessages(sess, queueURL, waitTime) + if err != nil { + fmt.Println("Got error retrieving LP messages:") + fmt.Println(err) + return + } + + // snippet-start:[sqs.go.send_receive_long_polling.print_msgs] + fmt.Println("Message IDs:") + + for _, msg := range results.Messages { + fmt.Println(" " + *msg.MessageId) + } + // snippet-end:[sqs.go.send_receive_long_polling.print_msgs] } + // snippet-end:[sqs.go.send_receive_long_polling] diff --git a/go/sqs/SendReceiveLongPolling/SendReceiveLongPolling_test.go b/go/sqs/SendReceiveLongPolling/SendReceiveLongPolling_test.go index 176d19bf73a..678f1c4bcc9 100644 --- a/go/sqs/SendReceiveLongPolling/SendReceiveLongPolling_test.go +++ b/go/sqs/SendReceiveLongPolling/SendReceiveLongPolling_test.go @@ -1,36 +1,25 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package main import ( - "encoding/json" - "io/ioutil" - "strconv" - "testing" + "encoding/json" + "io/ioutil" + "strconv" + "testing" - "github.com/google/uuid" + "github.com/google/uuid" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/sqs" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sqs" ) // Config defines a set of configuration values type Config struct { - Queue string `json:"Queue"` - WaitTime int `json:"WaitTime"` + Queue string `json:"Queue"` + WaitTime int `json:"WaitTime"` } // configFile defines the name of the file containing configuration values @@ -40,103 +29,103 @@ var configFileName = "config.json" var globalConfig Config func populateConfiguration(t *testing.T) error { - // Get configuration from config.json + // Get configuration from config.json - // Get entire file as a JSON string - content, err := ioutil.ReadFile(configFileName) - if err != nil { - return err - } + // Get entire file as a JSON string + content, err := ioutil.ReadFile(configFileName) + if err != nil { + return err + } - // Convert []byte to string - text := string(content) + // Convert []byte to string + text := string(content) - // Marshall JSON string in text into global struct - err = json.Unmarshal([]byte(text), &globalConfig) - if err != nil { - return err - } + // Marshall JSON string in text into global struct + err = json.Unmarshal([]byte(text), &globalConfig) + if err != nil { + return err + } - t.Log("Queue: " + globalConfig.Queue) - t.Log("WaitTime: " + strconv.Itoa(globalConfig.WaitTime)) + t.Log("Queue: " + globalConfig.Queue) + t.Log("WaitTime: " + strconv.Itoa(globalConfig.WaitTime)) - return nil + return nil } func createLPQueue(sess *session.Session, queue *string, waitTime *int) (string, error) { - // Create an SQS service client - svc := sqs.New(sess) - - result, err := svc.CreateQueue(&sqs.CreateQueueInput{ - QueueName: queue, - Attributes: aws.StringMap(map[string]string{ - "ReceiveMessageWaitTimeSeconds": strconv.Itoa(*waitTime), - }), - }) - if err != nil { - return "", err - } - - return *result.QueueUrl, nil + // Create an SQS service client + svc := sqs.New(sess) + + result, err := svc.CreateQueue(&sqs.CreateQueueInput{ + QueueName: queue, + Attributes: aws.StringMap(map[string]string{ + "ReceiveMessageWaitTimeSeconds": strconv.Itoa(*waitTime), + }), + }) + if err != nil { + return "", err + } + + return *result.QueueUrl, nil } func deleteQueue(sess *session.Session, queueURL *string) error { - // Create an SQS service client - svc := sqs.New(sess) + // Create an SQS service client + svc := sqs.New(sess) - _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ - QueueUrl: queueURL, - }) - if err != nil { - return err - } + _, err := svc.DeleteQueue(&sqs.DeleteQueueInput{ + QueueUrl: queueURL, + }) + if err != nil { + return err + } - return nil + return nil } func TestQueue(t *testing.T) { - err := populateConfiguration(t) - if err != nil { - t.Fatal(err) - } - - // Create a session using credentials from ~/.aws/credentials - // and the Region from ~/.aws/config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - - queueCreated := false - queueURL := "" - - if globalConfig.Queue == "" { - // Create a unique, random queue name - id := uuid.New() - globalConfig.Queue = "myqueue-" + id.String() - - queueURL, err = createLPQueue(sess, &globalConfig.Queue, &globalConfig.WaitTime) - if err != nil { - t.Fatal(err) - } - - t.Log("Created queue " + globalConfig.Queue) - queueCreated = true - } - - err = SendMsg(sess, &queueURL) - if err != nil { - t.Fatal(err) - } - - t.Log("Sent message to queue " + globalConfig.Queue) - - if queueCreated { - err = deleteQueue(sess, &queueURL) - if err != nil { - t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") - t.Fatal(err) - } - - t.Log("Deleted queue " + globalConfig.Queue) - } + err := populateConfiguration(t) + if err != nil { + t.Fatal(err) + } + + // Create a session using credentials from ~/.aws/credentials + // and the Region from ~/.aws/config + sess := session.Must(session.NewSessionWithOptions(session.Options{ + SharedConfigState: session.SharedConfigEnable, + })) + + queueCreated := false + queueURL := "" + + if globalConfig.Queue == "" { + // Create a unique, random queue name + id := uuid.New() + globalConfig.Queue = "myqueue-" + id.String() + + queueURL, err = createLPQueue(sess, &globalConfig.Queue, &globalConfig.WaitTime) + if err != nil { + t.Fatal(err) + } + + t.Log("Created queue " + globalConfig.Queue) + queueCreated = true + } + + err = SendMsg(sess, &queueURL) + if err != nil { + t.Fatal(err) + } + + t.Log("Sent message to queue " + globalConfig.Queue) + + if queueCreated { + err = deleteQueue(sess, &queueURL) + if err != nil { + t.Log("You'll have to delete queue " + globalConfig.Queue + " yourself") + t.Fatal(err) + } + + t.Log("Deleted queue " + globalConfig.Queue) + } } diff --git a/gov2/aurora/actions/clusters.go b/gov2/aurora/actions/clusters.go index 1f9cb46d443..b3cde5cfb09 100644 --- a/gov2/aurora/actions/clusters.go +++ b/gov2/aurora/actions/clusters.go @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package actions import ( diff --git a/gov2/aurora/scenarios/get_started_clusters_integ_test.go b/gov2/aurora/scenarios/get_started_clusters_integ_test.go index 00094ca8477..6a544003751 100644 --- a/gov2/aurora/scenarios/get_started_clusters_integ_test.go +++ b/gov2/aurora/scenarios/get_started_clusters_integ_test.go @@ -1,7 +1,8 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 //go:build integration // +build integration -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package scenarios diff --git a/gov2/aurora/scenarios/get_started_clusters_test.go b/gov2/aurora/scenarios/get_started_clusters_test.go index bf3e771d601..659e152177b 100644 --- a/gov2/aurora/scenarios/get_started_clusters_test.go +++ b/gov2/aurora/scenarios/get_started_clusters_test.go @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package scenarios import ( diff --git a/gov2/cloudfront/CreateDistribution/CreateDistribution_test.go b/gov2/cloudfront/CreateDistribution/CreateDistribution_test.go index ace2234bf8b..a755c8e010f 100644 --- a/gov2/cloudfront/CreateDistribution/CreateDistribution_test.go +++ b/gov2/cloudfront/CreateDistribution/CreateDistribution_test.go @@ -1,5 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 + package main import ( diff --git a/gov2/dynamodb/scenarios/scenario_movie_table_integ_test.go b/gov2/dynamodb/scenarios/scenario_movie_table_integ_test.go index fe36ac4edd8..eae28cff91f 100644 --- a/gov2/dynamodb/scenarios/scenario_movie_table_integ_test.go +++ b/gov2/dynamodb/scenarios/scenario_movie_table_integ_test.go @@ -1,7 +1,8 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 //go:build integration // +build integration -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Integration test for the movie table scenario. diff --git a/gov2/dynamodb/scenarios/scenario_partiql_batch_integ_test.go b/gov2/dynamodb/scenarios/scenario_partiql_batch_integ_test.go index cfc31b5756f..0cda5d5f22e 100644 --- a/gov2/dynamodb/scenarios/scenario_partiql_batch_integ_test.go +++ b/gov2/dynamodb/scenarios/scenario_partiql_batch_integ_test.go @@ -1,7 +1,8 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 //go:build integration // +build integration -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Integration test for the PartiQL batch scenario. diff --git a/gov2/dynamodb/scenarios/scenario_partiql_single_integ_test.go b/gov2/dynamodb/scenarios/scenario_partiql_single_integ_test.go index 8996f519184..16accb880f4 100644 --- a/gov2/dynamodb/scenarios/scenario_partiql_single_integ_test.go +++ b/gov2/dynamodb/scenarios/scenario_partiql_single_integ_test.go @@ -1,7 +1,8 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 //go:build integration // +build integration -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Integration test for the PartiQL single action scenario. diff --git a/gov2/iam/actions/non_scenario_action_integ_test.go b/gov2/iam/actions/non_scenario_action_integ_test.go index 541fcffbac4..25ff3e05e49 100644 --- a/gov2/iam/actions/non_scenario_action_integ_test.go +++ b/gov2/iam/actions/non_scenario_action_integ_test.go @@ -1,7 +1,8 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 //go:build integration // +build integration -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package actions @@ -36,4 +37,4 @@ func TestCallNonScenarioActions_Integration(t *testing.T) { if !strings.Contains(buf.String(), "Thanks for watching") { t.Errorf("didn't run to successful completion. Here's the log:\n%v", buf.String()) } -} \ No newline at end of file +} diff --git a/gov2/iam/scenarios/scenario_assume_role_integ_test.go b/gov2/iam/scenarios/scenario_assume_role_integ_test.go index f7685118cac..02537a97a28 100644 --- a/gov2/iam/scenarios/scenario_assume_role_integ_test.go +++ b/gov2/iam/scenarios/scenario_assume_role_integ_test.go @@ -1,7 +1,8 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 //go:build integration // +build integration -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Integration test for the assume role scenario. @@ -30,7 +31,7 @@ type IntegHelper struct { // Pause increases all pause durations by 5 seconds. This is needed during integration // testing to make sure that AWS has enough time to create all resources. func (helper IntegHelper) Pause(secs int) { - time.Sleep(time.Duration(secs + 5) * time.Second) + time.Sleep(time.Duration(secs+5) * time.Second) } func TestRunAssumeRoleScenario_Integration(t *testing.T) { diff --git a/gov2/lambda/scenarios/scenario_get_started_functions_integ_test.go b/gov2/lambda/scenarios/scenario_get_started_functions_integ_test.go index d5b8cad312f..faf3f81aa25 100644 --- a/gov2/lambda/scenarios/scenario_get_started_functions_integ_test.go +++ b/gov2/lambda/scenarios/scenario_get_started_functions_integ_test.go @@ -1,7 +1,8 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 //go:build integration // +build integration -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package scenarios diff --git a/gov2/lint_all_go.sh b/gov2/lint_all_go.sh index 468d4cc82cc..e4f466638a1 100755 --- a/gov2/lint_all_go.sh +++ b/gov2/lint_all_go.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 function runCommand() { echo Linting Go files... diff --git a/gov2/rds/scenarios/get_started_instances_integ_test.go b/gov2/rds/scenarios/get_started_instances_integ_test.go index a497aea8ada..c44d30f9cc7 100644 --- a/gov2/rds/scenarios/get_started_instances_integ_test.go +++ b/gov2/rds/scenarios/get_started_instances_integ_test.go @@ -1,7 +1,8 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 //go:build integration // +build integration -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package scenarios diff --git a/gov2/rds/scenarios/get_started_instances_test.go b/gov2/rds/scenarios/get_started_instances_test.go index b79c6a74beb..ec3cc4ca347 100644 --- a/gov2/rds/scenarios/get_started_instances_test.go +++ b/gov2/rds/scenarios/get_started_instances_test.go @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package scenarios import ( diff --git a/gov2/run_all_tests.sh b/gov2/run_all_tests.sh index e59ab3941a1..7da35915d11 100755 --- a/gov2/run_all_tests.sh +++ b/gov2/run_all_tests.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 function runCommand() { if [ "$1" ] && [ "$1" == 'integration' ]; then diff --git a/gov2/s3/scenarios/scenario_get_started_integ_test.go b/gov2/s3/scenarios/scenario_get_started_integ_test.go index ad15e838e97..39426531d24 100644 --- a/gov2/s3/scenarios/scenario_get_started_integ_test.go +++ b/gov2/s3/scenarios/scenario_get_started_integ_test.go @@ -1,7 +1,8 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 //go:build integration // +build integration -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Integration test for the Amazon S3 get started scenario. diff --git a/gov2/s3/scenarios/scenario_presigning_integ_test.go b/gov2/s3/scenarios/scenario_presigning_integ_test.go index a961850f5eb..19f04104fd6 100644 --- a/gov2/s3/scenarios/scenario_presigning_integ_test.go +++ b/gov2/s3/scenarios/scenario_presigning_integ_test.go @@ -1,7 +1,8 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 //go:build integration // +build integration -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Integration test for the Amazon S3 presigning scenario. diff --git a/java/example_code/athena/run_example.sh b/java/example_code/athena/run_example.sh index 1e0dad43bc7..59144db5b3a 100755 --- a/java/example_code/athena/run_example.sh +++ b/java/example_code/athena/run_example.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 if [[ -z $* ]] ; then echo 'Supply the name of one of the example classes as an argument.' echo 'If there are arguments to the class, put them in quotes after the class name.' diff --git a/java/example_code/athena/src/main/java/aws/example/athena/AthenaClientFactory.java b/java/example_code/athena/src/main/java/aws/example/athena/AthenaClientFactory.java index 5b257e5bb9f..37e56787d0d 100644 --- a/java/example_code/athena/src/main/java/aws/example/athena/AthenaClientFactory.java +++ b/java/example_code/athena/src/main/java/aws/example/athena/AthenaClientFactory.java @@ -1,40 +1,32 @@ -//snippet-sourcedescription:[AthenaClientFactory.java demonstrates how to create and configure an Amazon Athena client] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Athena] -//snippet-service:[athena] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-25] -//snippet-sourceauthor:[soo-aws] -package aws.example.athena; - -import com.amazonaws.ClientConfiguration; -import com.amazonaws.auth.InstanceProfileCredentialsProvider; -import com.amazonaws.regions.Regions; -import com.amazonaws.services.athena.AmazonAthena; -import com.amazonaws.services.athena.AmazonAthenaClientBuilder; - -/** -* AthenaClientFactory -* ------------------------------------- -* This code shows how to create and configure an Amazon Athena client. -*/ -public class AthenaClientFactory -{ -/** - * AmazonAthenaClientBuilder to build Athena with the following properties: - * - Set the region of the client - * - Use the instance profile from the EC2 instance as the credentials provider - * - Configure the client to increase the execution timeout. - */ - private final AmazonAthenaClientBuilder builder = AmazonAthenaClientBuilder.standard() - .withRegion(Regions.US_WEST_2) - .withCredentials(InstanceProfileCredentialsProvider.getInstance()) - .withClientConfiguration(new ClientConfiguration().withClientExecutionTimeout(ExampleConstants.CLIENT_EXECUTION_TIMEOUT)); - - public AmazonAthena createClient() - { - return builder.build(); - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package aws.example.athena; + +import com.amazonaws.ClientConfiguration; +import com.amazonaws.auth.InstanceProfileCredentialsProvider; +import com.amazonaws.regions.Regions; +import com.amazonaws.services.athena.AmazonAthena; +import com.amazonaws.services.athena.AmazonAthenaClientBuilder; + +/** + * AthenaClientFactory + * ------------------------------------- + * This code shows how to create and configure an Amazon Athena client. + */ +public class AthenaClientFactory { + /** + * AmazonAthenaClientBuilder to build Athena with the following properties: + * - Set the region of the client + * - Use the instance profile from the EC2 instance as the credentials provider + * - Configure the client to increase the execution timeout. + */ + private final AmazonAthenaClientBuilder builder = AmazonAthenaClientBuilder.standard() + .withRegion(Regions.US_WEST_2) + .withCredentials(InstanceProfileCredentialsProvider.getInstance()) + .withClientConfiguration( + new ClientConfiguration().withClientExecutionTimeout(ExampleConstants.CLIENT_EXECUTION_TIMEOUT)); + + public AmazonAthena createClient() { + return builder.build(); + } +} diff --git a/java/example_code/athena/src/main/java/aws/example/athena/CreateNamedQueryExample.java b/java/example_code/athena/src/main/java/aws/example/athena/CreateNamedQueryExample.java index b3eae6b13cb..f5c7bdb455f 100644 --- a/java/example_code/athena/src/main/java/aws/example/athena/CreateNamedQueryExample.java +++ b/java/example_code/athena/src/main/java/aws/example/athena/CreateNamedQueryExample.java @@ -1,39 +1,30 @@ -//snippet-sourcedescription:[CreateNamedQueryExample.java demonstrates how to create a named query] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Athena] -//snippet-service:[athena] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-25] -//snippet-sourceauthor:[soo-aws] -package aws.example.athena; - -import com.amazonaws.services.athena.AmazonAthena; -import com.amazonaws.services.athena.model.CreateNamedQueryRequest; -import com.amazonaws.services.athena.model.CreateNamedQueryResult; - -/** -* CreateNamedQueryExample -* ------------------------------------- -* This code shows how to create a named query. -*/ -public class CreateNamedQueryExample -{ - public static void main(String[] args) throws Exception - { - // Build an Athena client - AthenaClientFactory factory = new AthenaClientFactory(); - AmazonAthena athenaClient = factory.createClient(); - - // Create the named query request. - CreateNamedQueryRequest createNamedQueryRequest = new CreateNamedQueryRequest() - .withDatabase(ExampleConstants.ATHENA_DEFAULT_DATABASE) - .withQueryString(ExampleConstants.ATHENA_SAMPLE_QUERY) - .withDescription("Sample Description") - .withName("SampleQuery2"); - - // Call Athena to create the named query. If it fails, an exception is thrown. - CreateNamedQueryResult createNamedQueryResult = athenaClient.createNamedQuery(createNamedQueryRequest); - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package aws.example.athena; + +import com.amazonaws.services.athena.AmazonAthena; +import com.amazonaws.services.athena.model.CreateNamedQueryRequest; +import com.amazonaws.services.athena.model.CreateNamedQueryResult; + +/** + * CreateNamedQueryExample + * ------------------------------------- + * This code shows how to create a named query. + */ +public class CreateNamedQueryExample { + public static void main(String[] args) throws Exception { + // Build an Athena client + AthenaClientFactory factory = new AthenaClientFactory(); + AmazonAthena athenaClient = factory.createClient(); + + // Create the named query request. + CreateNamedQueryRequest createNamedQueryRequest = new CreateNamedQueryRequest() + .withDatabase(ExampleConstants.ATHENA_DEFAULT_DATABASE) + .withQueryString(ExampleConstants.ATHENA_SAMPLE_QUERY) + .withDescription("Sample Description") + .withName("SampleQuery2"); + + // Call Athena to create the named query. If it fails, an exception is thrown. + CreateNamedQueryResult createNamedQueryResult = athenaClient.createNamedQuery(createNamedQueryRequest); + } +} diff --git a/java/example_code/athena/src/main/java/aws/example/athena/DeleteNamedQueryExample.java b/java/example_code/athena/src/main/java/aws/example/athena/DeleteNamedQueryExample.java index a7bacb3b64c..e9283a97a01 100644 --- a/java/example_code/athena/src/main/java/aws/example/athena/DeleteNamedQueryExample.java +++ b/java/example_code/athena/src/main/java/aws/example/athena/DeleteNamedQueryExample.java @@ -1,54 +1,44 @@ -//snippet-sourcedescription:[DeleteNamedQueryExample.java demonstrates how to delete a named query by using the named query ID.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Athena] -//snippet-service:[athena] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-25] -//snippet-sourceauthor:[soo-aws] -package aws.example.athena; - -import com.amazonaws.services.athena.AmazonAthena; -import com.amazonaws.services.athena.model.CreateNamedQueryRequest; -import com.amazonaws.services.athena.model.CreateNamedQueryResult; -import com.amazonaws.services.athena.model.DeleteNamedQueryRequest; -import com.amazonaws.services.athena.model.DeleteNamedQueryResult; - -/** - * DeleteNamedQueryExample - * ------------------------------------- - * This code shows how to delete a named query by using the named query ID. - */ -public class DeleteNamedQueryExample -{ - private static String getNamedQueryId(AmazonAthena athenaClient) - { - // Create the NameQuery Request. - CreateNamedQueryRequest createNamedQueryRequest = new CreateNamedQueryRequest() - .withDatabase(ExampleConstants.ATHENA_DEFAULT_DATABASE) - .withQueryString(ExampleConstants.ATHENA_SAMPLE_QUERY) - .withName("SampleQueryName") - .withDescription("Sample Description"); - - // Create the named query. If it fails, an exception is thrown. - CreateNamedQueryResult createNamedQueryResult = athenaClient.createNamedQuery(createNamedQueryRequest); - return createNamedQueryResult.getNamedQueryId(); - } - - public static void main(String[] args) throws Exception - { - // Build an Athena client - AthenaClientFactory factory = new AthenaClientFactory(); - AmazonAthena athenaClient = factory.createClient(); - - String sampleNamedQueryId = getNamedQueryId(athenaClient); - - // Create the delete named query request - DeleteNamedQueryRequest deleteNamedQueryRequest = new DeleteNamedQueryRequest() - .withNamedQueryId(sampleNamedQueryId); - - // Delete the named query - DeleteNamedQueryResult deleteNamedQueryResult = athenaClient.deleteNamedQuery(deleteNamedQueryRequest); - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package aws.example.athena; + +import com.amazonaws.services.athena.AmazonAthena; +import com.amazonaws.services.athena.model.CreateNamedQueryRequest; +import com.amazonaws.services.athena.model.CreateNamedQueryResult; +import com.amazonaws.services.athena.model.DeleteNamedQueryRequest; +import com.amazonaws.services.athena.model.DeleteNamedQueryResult; + +/** + * DeleteNamedQueryExample + * ------------------------------------- + * This code shows how to delete a named query by using the named query ID. + */ +public class DeleteNamedQueryExample { + private static String getNamedQueryId(AmazonAthena athenaClient) { + // Create the NameQuery Request. + CreateNamedQueryRequest createNamedQueryRequest = new CreateNamedQueryRequest() + .withDatabase(ExampleConstants.ATHENA_DEFAULT_DATABASE) + .withQueryString(ExampleConstants.ATHENA_SAMPLE_QUERY) + .withName("SampleQueryName") + .withDescription("Sample Description"); + + // Create the named query. If it fails, an exception is thrown. + CreateNamedQueryResult createNamedQueryResult = athenaClient.createNamedQuery(createNamedQueryRequest); + return createNamedQueryResult.getNamedQueryId(); + } + + public static void main(String[] args) throws Exception { + // Build an Athena client + AthenaClientFactory factory = new AthenaClientFactory(); + AmazonAthena athenaClient = factory.createClient(); + + String sampleNamedQueryId = getNamedQueryId(athenaClient); + + // Create the delete named query request + DeleteNamedQueryRequest deleteNamedQueryRequest = new DeleteNamedQueryRequest() + .withNamedQueryId(sampleNamedQueryId); + + // Delete the named query + DeleteNamedQueryResult deleteNamedQueryResult = athenaClient.deleteNamedQuery(deleteNamedQueryRequest); + } +} diff --git a/java/example_code/athena/src/main/java/aws/example/athena/ExampleConstants.java b/java/example_code/athena/src/main/java/aws/example/athena/ExampleConstants.java index 3a4d38c7df3..2130d96a8d5 100644 --- a/java/example_code/athena/src/main/java/aws/example/athena/ExampleConstants.java +++ b/java/example_code/athena/src/main/java/aws/example/athena/ExampleConstants.java @@ -1,26 +1,19 @@ -//snippet-sourcedescription:[ExampleConstants.java demonstrates how to query a table created by the getting started tutorial in Athena] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Athena] -//snippet-service:[athena] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-25] -//snippet-sourceauthor:[soo-aws] -package aws.example.athena; - -public class ExampleConstants { - - public static final int CLIENT_EXECUTION_TIMEOUT = 100000; - public static final String ATHENA_OUTPUT_BUCKET = "s3://my-athena-bucket"; - // This is querying a table created by the getting started tutorial in Athena - public static final String ATHENA_SAMPLE_QUERY = "SELECT elb_name, " - + " count(1)" - + " FROM elb_logs" - + " Where elb_response_code = '200'" - + " GROUP BY elb_name" - + " ORDER BY 2 DESC limit 10;"; - public static final long SLEEP_AMOUNT_IN_MS = 1000; - public static final String ATHENA_DEFAULT_DATABASE = "default"; - -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package aws.example.athena; + +public class ExampleConstants { + + public static final int CLIENT_EXECUTION_TIMEOUT = 100000; + public static final String ATHENA_OUTPUT_BUCKET = "s3://my-athena-bucket"; + // This is querying a table created by the getting started tutorial in Athena + public static final String ATHENA_SAMPLE_QUERY = "SELECT elb_name, " + + " count(1)" + + " FROM elb_logs" + + " Where elb_response_code = '200'" + + " GROUP BY elb_name" + + " ORDER BY 2 DESC limit 10;"; + public static final long SLEEP_AMOUNT_IN_MS = 1000; + public static final String ATHENA_DEFAULT_DATABASE = "default"; + +} diff --git a/java/example_code/athena/src/main/java/aws/example/athena/ListNamedQueryExample.java b/java/example_code/athena/src/main/java/aws/example/athena/ListNamedQueryExample.java index 1fe38116148..09b2c4d1772 100644 --- a/java/example_code/athena/src/main/java/aws/example/athena/ListNamedQueryExample.java +++ b/java/example_code/athena/src/main/java/aws/example/athena/ListNamedQueryExample.java @@ -1,54 +1,45 @@ -//snippet-sourcedescription:[ListNamedQueryExample.java demonstrates how to obtain a list of named query IDs.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Athena] -//snippet-service:[athena] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-25] -//snippet-sourceauthor:[soo-aws] -package aws.example.athena; - -import com.amazonaws.services.athena.AmazonAthena; -import com.amazonaws.services.athena.model.ListNamedQueriesRequest; -import com.amazonaws.services.athena.model.ListNamedQueriesResult; - -import java.util.List; - -/** - * ListNamedQueryExample - * ------------------------------------- - * This code shows how to obtain a list of named query IDs. - */ -public class ListNamedQueryExample -{ - public static void main(String[] args) throws Exception - { - // Build an Athena client - AthenaClientFactory factory = new AthenaClientFactory(); - AmazonAthena athenaClient = factory.createClient(); - - // Build the request - ListNamedQueriesRequest listNamedQueriesRequest = new ListNamedQueriesRequest(); - - // Get the list results. - ListNamedQueriesResult listNamedQueriesResult = athenaClient.listNamedQueries(listNamedQueriesRequest); - - // Process the results. - boolean hasMoreResults = true; - - while (hasMoreResults) { - List namedQueryIds = listNamedQueriesResult.getNamedQueryIds(); - // process named query IDs - - // If nextToken is not null, there are more results. Get the next page of results. - if (listNamedQueriesResult.getNextToken() != null) { - listNamedQueriesResult = athenaClient.listNamedQueries( - listNamedQueriesRequest.withNextToken(listNamedQueriesResult.getNextToken())); - } - else { - hasMoreResults = false; - } - } - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package aws.example.athena; + +import com.amazonaws.services.athena.AmazonAthena; +import com.amazonaws.services.athena.model.ListNamedQueriesRequest; +import com.amazonaws.services.athena.model.ListNamedQueriesResult; + +import java.util.List; + +/** + * ListNamedQueryExample + * ------------------------------------- + * This code shows how to obtain a list of named query IDs. + */ +public class ListNamedQueryExample { + public static void main(String[] args) throws Exception { + // Build an Athena client + AthenaClientFactory factory = new AthenaClientFactory(); + AmazonAthena athenaClient = factory.createClient(); + + // Build the request + ListNamedQueriesRequest listNamedQueriesRequest = new ListNamedQueriesRequest(); + + // Get the list results. + ListNamedQueriesResult listNamedQueriesResult = athenaClient.listNamedQueries(listNamedQueriesRequest); + + // Process the results. + boolean hasMoreResults = true; + + while (hasMoreResults) { + List namedQueryIds = listNamedQueriesResult.getNamedQueryIds(); + // process named query IDs + + // If nextToken is not null, there are more results. Get the next page of + // results. + if (listNamedQueriesResult.getNextToken() != null) { + listNamedQueriesResult = athenaClient.listNamedQueries( + listNamedQueriesRequest.withNextToken(listNamedQueriesResult.getNextToken())); + } else { + hasMoreResults = false; + } + } + } +} diff --git a/java/example_code/athena/src/main/java/aws/example/athena/ListQueryExecutionsExample.java b/java/example_code/athena/src/main/java/aws/example/athena/ListQueryExecutionsExample.java index f72ade6d209..09b66065b02 100644 --- a/java/example_code/athena/src/main/java/aws/example/athena/ListQueryExecutionsExample.java +++ b/java/example_code/athena/src/main/java/aws/example/athena/ListQueryExecutionsExample.java @@ -1,55 +1,47 @@ -//snippet-sourcedescription:[ListQueryExecutionsExample.java demonstrates how to obtain a list of query execution IDs.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Athena] -//snippet-service:[athena] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-25] -//snippet-sourceauthor:[soo-aws] -package aws.example.athena; - -import com.amazonaws.services.athena.AmazonAthena; -import com.amazonaws.services.athena.model.ListQueryExecutionsRequest; -import com.amazonaws.services.athena.model.ListQueryExecutionsResult; - -import java.util.List; - -/** -* ListQueryExecutionsExample -* ------------------------------------- -* This code shows how to obtain a list of query execution IDs. -*/ -public class ListQueryExecutionsExample -{ - public static void main(String[] args) throws Exception - { - // Build an Athena client - AthenaClientFactory factory = new AthenaClientFactory(); - AmazonAthena athenaClient = factory.createClient(); - - // Build the request - ListQueryExecutionsRequest listQueryExecutionsRequest = new ListQueryExecutionsRequest(); - - // Get the list results. - ListQueryExecutionsResult listQueryExecutionsResult = athenaClient.listQueryExecutions(listQueryExecutionsRequest); - - // Process the results. - boolean hasMoreResults = true; - while (hasMoreResults) { - List queryExecutionIds = listQueryExecutionsResult.getQueryExecutionIds(); - // process queryExecutionIds. - - System.out.println(queryExecutionIds); - - //If nextToken is not null, then there are more results. Get the next page of results. - if (listQueryExecutionsResult.getNextToken() != null) { - listQueryExecutionsResult = athenaClient.listQueryExecutions( - listQueryExecutionsRequest.withNextToken(listQueryExecutionsResult.getNextToken())); - } - else { - hasMoreResults = false; - } - } - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package aws.example.athena; + +import com.amazonaws.services.athena.AmazonAthena; +import com.amazonaws.services.athena.model.ListQueryExecutionsRequest; +import com.amazonaws.services.athena.model.ListQueryExecutionsResult; + +import java.util.List; + +/** + * ListQueryExecutionsExample + * ------------------------------------- + * This code shows how to obtain a list of query execution IDs. + */ +public class ListQueryExecutionsExample { + public static void main(String[] args) throws Exception { + // Build an Athena client + AthenaClientFactory factory = new AthenaClientFactory(); + AmazonAthena athenaClient = factory.createClient(); + + // Build the request + ListQueryExecutionsRequest listQueryExecutionsRequest = new ListQueryExecutionsRequest(); + + // Get the list results. + ListQueryExecutionsResult listQueryExecutionsResult = athenaClient + .listQueryExecutions(listQueryExecutionsRequest); + + // Process the results. + boolean hasMoreResults = true; + while (hasMoreResults) { + List queryExecutionIds = listQueryExecutionsResult.getQueryExecutionIds(); + // process queryExecutionIds. + + System.out.println(queryExecutionIds); + + // If nextToken is not null, then there are more results. Get the next page of + // results. + if (listQueryExecutionsResult.getNextToken() != null) { + listQueryExecutionsResult = athenaClient.listQueryExecutions( + listQueryExecutionsRequest.withNextToken(listQueryExecutionsResult.getNextToken())); + } else { + hasMoreResults = false; + } + } + } +} diff --git a/java/example_code/athena/src/main/java/aws/example/athena/StartQueryExample.java b/java/example_code/athena/src/main/java/aws/example/athena/StartQueryExample.java index 8ba651c260c..1dd30c4639f 100644 --- a/java/example_code/athena/src/main/java/aws/example/athena/StartQueryExample.java +++ b/java/example_code/athena/src/main/java/aws/example/athena/StartQueryExample.java @@ -1,172 +1,166 @@ -//snippet-sourcedescription:[StartQueryExample.java demonstrates how to submit a query to Athena for execution, wait till results are available, and then process the results.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Athena] -//snippet-service:[athena] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-25] -//snippet-sourceauthor:[soo-aws] -package aws.example.athena; - -import com.amazonaws.services.athena.AmazonAthena; -import com.amazonaws.services.athena.model.ColumnInfo; -import com.amazonaws.services.athena.model.GetQueryExecutionRequest; -import com.amazonaws.services.athena.model.GetQueryExecutionResult; -import com.amazonaws.services.athena.model.GetQueryResultsRequest; -import com.amazonaws.services.athena.model.GetQueryResultsResult; -import com.amazonaws.services.athena.model.QueryExecutionContext; -import com.amazonaws.services.athena.model.QueryExecutionState; -import com.amazonaws.services.athena.model.ResultConfiguration; -import com.amazonaws.services.athena.model.Row; -import com.amazonaws.services.athena.model.StartQueryExecutionRequest; -import com.amazonaws.services.athena.model.StartQueryExecutionResult; - -import java.util.List; - -/** -* StartQueryExample -* ------------------------------------- -* This code shows how to submit a query to Athena for execution, wait till results -* are available, and then process the results. -*/ -public class StartQueryExample -{ - public static void main(String[] args) throws InterruptedException - { - // Build an AmazonAthena client - AthenaClientFactory factory = new AthenaClientFactory(); - AmazonAthena athenaClient = factory.createClient(); - - String queryExecutionId = submitAthenaQuery(athenaClient); - - waitForQueryToComplete(athenaClient, queryExecutionId); - - processResultRows(athenaClient, queryExecutionId); - } - - /** - * Submits a sample query to Athena and returns the execution ID of the query. - */ - private static String submitAthenaQuery(AmazonAthena athenaClient) - { - // The QueryExecutionContext allows us to set the Database. - QueryExecutionContext queryExecutionContext = new QueryExecutionContext().withDatabase(ExampleConstants.ATHENA_DEFAULT_DATABASE); - - // The result configuration specifies where the results of the query should go in S3 and encryption options - ResultConfiguration resultConfiguration = new ResultConfiguration() - // You can provide encryption options for the output that is written. - // .withEncryptionConfiguration(encryptionConfiguration) - .withOutputLocation(ExampleConstants.ATHENA_OUTPUT_BUCKET); - - // Create the StartQueryExecutionRequest to send to Athena which will start the query. - StartQueryExecutionRequest startQueryExecutionRequest = new StartQueryExecutionRequest() - .withQueryString(ExampleConstants.ATHENA_SAMPLE_QUERY) - .withQueryExecutionContext(queryExecutionContext) - .withResultConfiguration(resultConfiguration); - - StartQueryExecutionResult startQueryExecutionResult = athenaClient.startQueryExecution(startQueryExecutionRequest); - return startQueryExecutionResult.getQueryExecutionId(); - } - - /** - * Wait for an Athena query to complete, fail or to be cancelled. This is done by polling Athena over an - * interval of time. If a query fails or is cancelled, then it will throw an exception. - */ - - private static void waitForQueryToComplete(AmazonAthena athenaClient, String queryExecutionId) throws InterruptedException - { - GetQueryExecutionRequest getQueryExecutionRequest = new GetQueryExecutionRequest() - .withQueryExecutionId(queryExecutionId); - - GetQueryExecutionResult getQueryExecutionResult = null; - boolean isQueryStillRunning = true; - while (isQueryStillRunning) { - getQueryExecutionResult = athenaClient.getQueryExecution(getQueryExecutionRequest); - String queryState = getQueryExecutionResult.getQueryExecution().getStatus().getState(); - if (queryState.equals(QueryExecutionState.FAILED.toString())) { - throw new RuntimeException("Query Failed to run with Error Message: " + getQueryExecutionResult.getQueryExecution().getStatus().getStateChangeReason()); - } - else if (queryState.equals(QueryExecutionState.CANCELLED.toString())) { - throw new RuntimeException("Query was cancelled."); - } - else if (queryState.equals(QueryExecutionState.SUCCEEDED.toString())) { - isQueryStillRunning = false; - } - else { - // Sleep an amount of time before retrying again. - Thread.sleep(ExampleConstants.SLEEP_AMOUNT_IN_MS); - } - System.out.println("Current Status is: " + queryState); - } - } - - /** - * This code calls Athena and retrieves the results of a query. - * The query must be in a completed state before the results can be retrieved and - * paginated. The first row of results are the column headers. - */ - private static void processResultRows(AmazonAthena athenaClient, String queryExecutionId) - { - GetQueryResultsRequest getQueryResultsRequest = new GetQueryResultsRequest() - // Max Results can be set but if its not set, - // it will choose the maximum page size - // As of the writing of this code, the maximum value is 1000 - // .withMaxResults(1000) - .withQueryExecutionId(queryExecutionId); - - GetQueryResultsResult getQueryResultsResult = athenaClient.getQueryResults(getQueryResultsRequest); - List columnInfoList = getQueryResultsResult.getResultSet().getResultSetMetadata().getColumnInfo(); - - while (true) { - List results = getQueryResultsResult.getResultSet().getRows(); - for (Row row : results) { - // Process the row. The first row of the first page holds the column names. - processRow(row, columnInfoList); - } - // If nextToken is null, there are no more pages to read. Break out of the loop. - if (getQueryResultsResult.getNextToken() == null) { - break; - } - getQueryResultsResult = athenaClient.getQueryResults( - getQueryResultsRequest.withNextToken(getQueryResultsResult.getNextToken())); - } - } - - private static void processRow(Row row, List columnInfoList) - { - for (int i = 0; i < columnInfoList.size(); ++i) { - switch (columnInfoList.get(i).getType()) { - case "varchar": - // Convert and Process as String - break; - case "tinyint": - // Convert and Process as tinyint - break; - case "smallint": - // Convert and Process as smallint - break; - case "integer": - // Convert and Process as integer - break; - case "bigint": - // Convert and Process as bigint - break; - case "double": - // Convert and Process as double - break; - case "boolean": - // Convert and Process as boolean - break; - case "date": - // Convert and Process as date - break; - case "timestamp": - // Convert and Process as timestamp - break; - default: - throw new RuntimeException("Unexpected Type is not expected" + columnInfoList.get(i).getType()); - } - } - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package aws.example.athena; + +import com.amazonaws.services.athena.AmazonAthena; +import com.amazonaws.services.athena.model.ColumnInfo; +import com.amazonaws.services.athena.model.GetQueryExecutionRequest; +import com.amazonaws.services.athena.model.GetQueryExecutionResult; +import com.amazonaws.services.athena.model.GetQueryResultsRequest; +import com.amazonaws.services.athena.model.GetQueryResultsResult; +import com.amazonaws.services.athena.model.QueryExecutionContext; +import com.amazonaws.services.athena.model.QueryExecutionState; +import com.amazonaws.services.athena.model.ResultConfiguration; +import com.amazonaws.services.athena.model.Row; +import com.amazonaws.services.athena.model.StartQueryExecutionRequest; +import com.amazonaws.services.athena.model.StartQueryExecutionResult; + +import java.util.List; + +/** + * StartQueryExample + * ------------------------------------- + * This code shows how to submit a query to Athena for execution, wait till + * results + * are available, and then process the results. + */ +public class StartQueryExample { + public static void main(String[] args) throws InterruptedException { + // Build an AmazonAthena client + AthenaClientFactory factory = new AthenaClientFactory(); + AmazonAthena athenaClient = factory.createClient(); + + String queryExecutionId = submitAthenaQuery(athenaClient); + + waitForQueryToComplete(athenaClient, queryExecutionId); + + processResultRows(athenaClient, queryExecutionId); + } + + /** + * Submits a sample query to Athena and returns the execution ID of the query. + */ + private static String submitAthenaQuery(AmazonAthena athenaClient) { + // The QueryExecutionContext allows us to set the Database. + QueryExecutionContext queryExecutionContext = new QueryExecutionContext() + .withDatabase(ExampleConstants.ATHENA_DEFAULT_DATABASE); + + // The result configuration specifies where the results of the query should go + // in S3 and encryption options + ResultConfiguration resultConfiguration = new ResultConfiguration() + // You can provide encryption options for the output that is written. + // .withEncryptionConfiguration(encryptionConfiguration) + .withOutputLocation(ExampleConstants.ATHENA_OUTPUT_BUCKET); + + // Create the StartQueryExecutionRequest to send to Athena which will start the + // query. + StartQueryExecutionRequest startQueryExecutionRequest = new StartQueryExecutionRequest() + .withQueryString(ExampleConstants.ATHENA_SAMPLE_QUERY) + .withQueryExecutionContext(queryExecutionContext) + .withResultConfiguration(resultConfiguration); + + StartQueryExecutionResult startQueryExecutionResult = athenaClient + .startQueryExecution(startQueryExecutionRequest); + return startQueryExecutionResult.getQueryExecutionId(); + } + + /** + * Wait for an Athena query to complete, fail or to be cancelled. This is done + * by polling Athena over an + * interval of time. If a query fails or is cancelled, then it will throw an + * exception. + */ + + private static void waitForQueryToComplete(AmazonAthena athenaClient, String queryExecutionId) + throws InterruptedException { + GetQueryExecutionRequest getQueryExecutionRequest = new GetQueryExecutionRequest() + .withQueryExecutionId(queryExecutionId); + + GetQueryExecutionResult getQueryExecutionResult = null; + boolean isQueryStillRunning = true; + while (isQueryStillRunning) { + getQueryExecutionResult = athenaClient.getQueryExecution(getQueryExecutionRequest); + String queryState = getQueryExecutionResult.getQueryExecution().getStatus().getState(); + if (queryState.equals(QueryExecutionState.FAILED.toString())) { + throw new RuntimeException("Query Failed to run with Error Message: " + + getQueryExecutionResult.getQueryExecution().getStatus().getStateChangeReason()); + } else if (queryState.equals(QueryExecutionState.CANCELLED.toString())) { + throw new RuntimeException("Query was cancelled."); + } else if (queryState.equals(QueryExecutionState.SUCCEEDED.toString())) { + isQueryStillRunning = false; + } else { + // Sleep an amount of time before retrying again. + Thread.sleep(ExampleConstants.SLEEP_AMOUNT_IN_MS); + } + System.out.println("Current Status is: " + queryState); + } + } + + /** + * This code calls Athena and retrieves the results of a query. + * The query must be in a completed state before the results can be retrieved + * and + * paginated. The first row of results are the column headers. + */ + private static void processResultRows(AmazonAthena athenaClient, String queryExecutionId) { + GetQueryResultsRequest getQueryResultsRequest = new GetQueryResultsRequest() + // Max Results can be set but if its not set, + // it will choose the maximum page size + // As of the writing of this code, the maximum value is 1000 + // .withMaxResults(1000) + .withQueryExecutionId(queryExecutionId); + + GetQueryResultsResult getQueryResultsResult = athenaClient.getQueryResults(getQueryResultsRequest); + List columnInfoList = getQueryResultsResult.getResultSet().getResultSetMetadata().getColumnInfo(); + + while (true) { + List results = getQueryResultsResult.getResultSet().getRows(); + for (Row row : results) { + // Process the row. The first row of the first page holds the column names. + processRow(row, columnInfoList); + } + // If nextToken is null, there are no more pages to read. Break out of the loop. + if (getQueryResultsResult.getNextToken() == null) { + break; + } + getQueryResultsResult = athenaClient.getQueryResults( + getQueryResultsRequest.withNextToken(getQueryResultsResult.getNextToken())); + } + } + + private static void processRow(Row row, List columnInfoList) { + for (int i = 0; i < columnInfoList.size(); ++i) { + switch (columnInfoList.get(i).getType()) { + case "varchar": + // Convert and Process as String + break; + case "tinyint": + // Convert and Process as tinyint + break; + case "smallint": + // Convert and Process as smallint + break; + case "integer": + // Convert and Process as integer + break; + case "bigint": + // Convert and Process as bigint + break; + case "double": + // Convert and Process as double + break; + case "boolean": + // Convert and Process as boolean + break; + case "date": + // Convert and Process as date + break; + case "timestamp": + // Convert and Process as timestamp + break; + default: + throw new RuntimeException("Unexpected Type is not expected" + columnInfoList.get(i).getType()); + } + } + } +} diff --git a/java/example_code/athena/src/main/java/aws/example/athena/StopQueryExecutionExample.java b/java/example_code/athena/src/main/java/aws/example/athena/StopQueryExecutionExample.java index 9a3dbf32eb6..4790b4bb544 100644 --- a/java/example_code/athena/src/main/java/aws/example/athena/StopQueryExecutionExample.java +++ b/java/example_code/athena/src/main/java/aws/example/athena/StopQueryExecutionExample.java @@ -1,75 +1,72 @@ -//snippet-sourcedescription:[StopQueryExecutionExample.java demonstrates how to stop a query and check its status.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Athena] -//snippet-service:[athena] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-25] -//snippet-sourceauthor:[soo-aws] -package aws.example.athena; - -import com.amazonaws.services.athena.AmazonAthena; -import com.amazonaws.services.athena.model.GetQueryExecutionRequest; -import com.amazonaws.services.athena.model.GetQueryExecutionResult; -import com.amazonaws.services.athena.model.QueryExecutionContext; -import com.amazonaws.services.athena.model.QueryExecutionState; -import com.amazonaws.services.athena.model.ResultConfiguration; -import com.amazonaws.services.athena.model.StartQueryExecutionRequest; -import com.amazonaws.services.athena.model.StartQueryExecutionResult; -import com.amazonaws.services.athena.model.StopQueryExecutionRequest; -import com.amazonaws.services.athena.model.StopQueryExecutionResult; - -/** -* StopQueryExecutionExample -* ------------------------------------- -* This code runs an example query, immediately stops the query, and checks the status of the query to -* ensure that it was cancelled. -*/ -public class StopQueryExecutionExample -{ - public static void main(String[] args) throws Exception - { - // Build an Athena client - AthenaClientFactory factory = new AthenaClientFactory(); - AmazonAthena athenaClient = factory.createClient(); - - String sampleQueryExecutionId = submitAthenaQuery(athenaClient); - - // Submit the stop query Request - StopQueryExecutionRequest stopQueryExecutionRequest = new StopQueryExecutionRequest() - .withQueryExecutionId(sampleQueryExecutionId); - - StopQueryExecutionResult stopQueryExecutionResult = athenaClient.stopQueryExecution(stopQueryExecutionRequest); - - // Ensure that the query was stopped - GetQueryExecutionRequest getQueryExecutionRequest = new GetQueryExecutionRequest() - .withQueryExecutionId(sampleQueryExecutionId); - - GetQueryExecutionResult getQueryExecutionResult = athenaClient.getQueryExecution(getQueryExecutionRequest); - if (getQueryExecutionResult.getQueryExecution().getStatus().getState().equals(QueryExecutionState.CANCELLED)) { - // Query was cancelled. - System.out.println("Query has been cancelled"); - } - } - - /** - * Submits an example query and returns a query execution ID of a running query to stop. - */ - public static String submitAthenaQuery(AmazonAthena athenaClient) - { - QueryExecutionContext queryExecutionContext = new QueryExecutionContext().withDatabase(ExampleConstants.ATHENA_DEFAULT_DATABASE); - - ResultConfiguration resultConfiguration = new ResultConfiguration() - .withOutputLocation(ExampleConstants.ATHENA_OUTPUT_BUCKET); - - StartQueryExecutionRequest startQueryExecutionRequest = new StartQueryExecutionRequest() - .withQueryString(ExampleConstants.ATHENA_SAMPLE_QUERY) - .withQueryExecutionContext(queryExecutionContext) - .withResultConfiguration(resultConfiguration); - - StartQueryExecutionResult startQueryExecutionResult = athenaClient.startQueryExecution(startQueryExecutionRequest); - - return startQueryExecutionResult.getQueryExecutionId(); - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package aws.example.athena; + +import com.amazonaws.services.athena.AmazonAthena; +import com.amazonaws.services.athena.model.GetQueryExecutionRequest; +import com.amazonaws.services.athena.model.GetQueryExecutionResult; +import com.amazonaws.services.athena.model.QueryExecutionContext; +import com.amazonaws.services.athena.model.QueryExecutionState; +import com.amazonaws.services.athena.model.ResultConfiguration; +import com.amazonaws.services.athena.model.StartQueryExecutionRequest; +import com.amazonaws.services.athena.model.StartQueryExecutionResult; +import com.amazonaws.services.athena.model.StopQueryExecutionRequest; +import com.amazonaws.services.athena.model.StopQueryExecutionResult; + +/** + * StopQueryExecutionExample + * ------------------------------------- + * This code runs an example query, immediately stops the query, and checks the + * status of the query to + * ensure that it was cancelled. + */ +public class StopQueryExecutionExample { + public static void main(String[] args) throws Exception { + // Build an Athena client + AthenaClientFactory factory = new AthenaClientFactory(); + AmazonAthena athenaClient = factory.createClient(); + + String sampleQueryExecutionId = submitAthenaQuery(athenaClient); + + // Submit the stop query Request + StopQueryExecutionRequest stopQueryExecutionRequest = new StopQueryExecutionRequest() + .withQueryExecutionId(sampleQueryExecutionId); + + StopQueryExecutionResult stopQueryExecutionResult = athenaClient + .stopQueryExecution(stopQueryExecutionRequest); + + // Ensure that the query was stopped + GetQueryExecutionRequest getQueryExecutionRequest = new GetQueryExecutionRequest() + .withQueryExecutionId(sampleQueryExecutionId); + + GetQueryExecutionResult getQueryExecutionResult = athenaClient + .getQueryExecution(getQueryExecutionRequest); + if (getQueryExecutionResult.getQueryExecution().getStatus().getState() + .equals(QueryExecutionState.CANCELLED)) { + // Query was cancelled. + System.out.println("Query has been cancelled"); + } + } + + /** + * Submits an example query and returns a query execution ID of a running query + * to stop. + */ + public static String submitAthenaQuery(AmazonAthena athenaClient) { + QueryExecutionContext queryExecutionContext = new QueryExecutionContext() + .withDatabase(ExampleConstants.ATHENA_DEFAULT_DATABASE); + + ResultConfiguration resultConfiguration = new ResultConfiguration() + .withOutputLocation(ExampleConstants.ATHENA_OUTPUT_BUCKET); + + StartQueryExecutionRequest startQueryExecutionRequest = new StartQueryExecutionRequest() + .withQueryString(ExampleConstants.ATHENA_SAMPLE_QUERY) + .withQueryExecutionContext(queryExecutionContext) + .withResultConfiguration(resultConfiguration); + + StartQueryExecutionResult startQueryExecutionResult = athenaClient + .startQueryExecution(startQueryExecutionRequest); + + return startQueryExecutionResult.getQueryExecutionId(); + } +} diff --git a/java/example_code/cloudmap/src/main/java/aws/example/cloudmap/CreateService.java b/java/example_code/cloudmap/src/main/java/aws/example/cloudmap/CreateService.java index 6aa52d5a755..6545eea552b 100644 --- a/java/example_code/cloudmap/src/main/java/aws/example/cloudmap/CreateService.java +++ b/java/example_code/cloudmap/src/main/java/aws/example/cloudmap/CreateService.java @@ -1,23 +1,6 @@ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[CreateService.java creates a service in the given namespace in AWS Cloud Map] -// snippet-service:[cloudmap] -// snippet-keyword:[java] -// snippet-keyword:[AWS Cloud Map] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-04-19] -// snippet-sourceauthor:[rajib76] // snippet-start:[cloudmap.java.create_service_request.complete] package aws.example.cloudmap; @@ -31,29 +14,26 @@ import com.amazonaws.services.servicediscovery.model.CreateServiceRequest; public class CreateService { - public static void main(String args[]) throws Exception - { + public static void main(String args[]) throws Exception { AWSCredentials credentials = null; - try - { + try { credentials = new ProfileCredentialsProvider().getCredentials(); - }catch(Exception e) - { + } catch (Exception e) { throw new AmazonClientException("Cannot Load credentials"); } - + AWSServiceDiscovery client = AWSServiceDiscoveryClientBuilder - .standard() - .withCredentials(new AWSStaticCredentialsProvider(credentials)) - .withRegion("us-east-1") - .build(); - + .standard() + .withCredentials(new AWSStaticCredentialsProvider(credentials)) + .withRegion("us-east-1") + .build(); + CreateServiceRequest crequest = new CreateServiceRequest(); crequest.setName("example-service-01"); crequest.setDescription("This is an example service request"); - crequest.setNamespaceId("ns-ldmexc5fqajjnhco");//Replace with the namespaceID + crequest.setNamespaceId("ns-ldmexc5fqajjnhco");// Replace with the namespaceID System.out.println(client.createService(crequest)); } } -//snippet-end:[cloudmap.java.create_service_request.complete] \ No newline at end of file +// snippet-end:[cloudmap.java.create_service_request.complete] \ No newline at end of file diff --git a/java/example_code/cloudmap/src/main/java/aws/example/cloudmap/DiscoverInstances.java b/java/example_code/cloudmap/src/main/java/aws/example/cloudmap/DiscoverInstances.java index 1e8b530f4bb..5e8d1bd3dbe 100644 --- a/java/example_code/cloudmap/src/main/java/aws/example/cloudmap/DiscoverInstances.java +++ b/java/example_code/cloudmap/src/main/java/aws/example/cloudmap/DiscoverInstances.java @@ -1,30 +1,10 @@ -/* - * Author : Prakash.Ramesh - */ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[DiscoverInstances.java demonstrates how to discover instances configured in AWS Cloud Map] -// snippet-service:[cloudmap] -// snippet-keyword:[java] -// snippet-keyword:[AWS Cloud Map] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-04-19] -// snippet-sourceauthor:[prakashramesh] // snippet-start:[cloudmap.java.discover_instance_request.complete] - package aws.example.cloudmap; + import com.amazonaws.AmazonClientException; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSStaticCredentialsProvider; @@ -40,14 +20,12 @@ * This code expects that you have AWS credentials and region set up per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ -public class DiscoverInstances -{ - public static void main(String[] args) - { +public class DiscoverInstances { + public static void main(String[] args) { final String USAGE = "\n" + - "To run this example, supply the Namespacename , ServiceName of aws cloud map!\n" + - "\n" + - "Ex: DiscoverInstances \n"; + "To run this example, supply the Namespacename , ServiceName of aws cloud map!\n" + + "\n" + + "Ex: DiscoverInstances \n"; if (args.length < 2) { System.out.println(USAGE); @@ -57,14 +35,13 @@ public static void main(String[] args) String namespace_name = args[0]; String service_name = args[1]; - AWSCredentials credentials =null; + AWSCredentials credentials = null; try { - credentials= new EnvironmentVariableCredentialsProvider().getCredentials(); - }catch (Exception e) { + credentials = new EnvironmentVariableCredentialsProvider().getCredentials(); + } catch (Exception e) { throw new AmazonClientException("Cannot Load Credentials"); } - System.out.format("Instances in AWS cloud map %s:\n", namespace_name); AWSServiceDiscovery client = AWSServiceDiscoveryClientBuilder @@ -77,11 +54,10 @@ public static void main(String[] args) request.setNamespaceName(namespace_name); request.setServiceName(service_name); - DiscoverInstancesResult result=client.discoverInstances(request); + DiscoverInstancesResult result = client.discoverInstances(request); System.out.println(result.toString()); - } + } } -//snippet-end:[cloudmap.java.discover_instance_request.complete] - +// snippet-end:[cloudmap.java.discover_instance_request.complete] diff --git a/java/example_code/cloudmap/src/main/java/aws/example/cloudmap/ListInstances.java b/java/example_code/cloudmap/src/main/java/aws/example/cloudmap/ListInstances.java index bd141090300..13eaf8b143e 100644 --- a/java/example_code/cloudmap/src/main/java/aws/example/cloudmap/ListInstances.java +++ b/java/example_code/cloudmap/src/main/java/aws/example/cloudmap/ListInstances.java @@ -1,26 +1,11 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Author : Rajib Deb */ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -// snippet-sourcedescription:[ListInstances.java demonstrates how to ....] -// snippet-service:[cloudmap] -// snippet-keyword:[java] -// snippet-keyword:[AWS Cloud Map] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-04-18] -// snippet-sourceauthor:[rajib76] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[cloudmap.java.list_instances.complete] package aws.example.cloudmap; @@ -34,28 +19,25 @@ import com.amazonaws.services.servicediscovery.model.ListInstancesRequest; public class ListInstances { - public static void main(String args[]) throws Exception - { + public static void main(String args[]) throws Exception { AWSCredentials credentials = null; - try - { + try { credentials = new ProfileCredentialsProvider().getCredentials(); - }catch(Exception e) - { + } catch (Exception e) { throw new AmazonClientException("Cannot Load credentials"); } - + AWSServiceDiscovery client = AWSServiceDiscoveryClientBuilder - .standard() - .withCredentials(new AWSStaticCredentialsProvider(credentials)) - .withRegion("us-east-1") - .build(); - + .standard() + .withCredentials(new AWSStaticCredentialsProvider(credentials)) + .withRegion("us-east-1") + .build(); + ListInstancesRequest lreq = new ListInstancesRequest(); - lreq.setServiceId("srv-l7gkxmjapm5givba"); //Replace with service id - + lreq.setServiceId("srv-l7gkxmjapm5givba"); // Replace with service id + System.out.println(client.listInstances(lreq)); } } -//snippet-end:[cloudmap.java.list_instances.complete] \ No newline at end of file +// snippet-end:[cloudmap.java.list_instances.complete] \ No newline at end of file diff --git a/java/example_code/cloudmap/src/main/java/aws/example/cloudmap/LookUpServicewithFilter.java b/java/example_code/cloudmap/src/main/java/aws/example/cloudmap/LookUpServicewithFilter.java index 7777f403107..b1e6d0ee2ba 100644 --- a/java/example_code/cloudmap/src/main/java/aws/example/cloudmap/LookUpServicewithFilter.java +++ b/java/example_code/cloudmap/src/main/java/aws/example/cloudmap/LookUpServicewithFilter.java @@ -1,23 +1,6 @@ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[LookUpServiceFilter.java helps to lookup a service with filter from AWS Cloud Map] -// snippet-service:[cloudmap] -// snippet-keyword:[java] -// snippet-keyword:[AWS Cloud Map] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-04-19] -// snippet-sourceauthor:[rajib76] // snippet-start:[cloudmap.java.lookup_servicewithfilter_request.complete] package aws.example.cloudmap; @@ -34,34 +17,31 @@ import com.amazonaws.services.servicediscovery.model.DiscoverInstancesRequest; public class LookUpServicewithFilter { - public static void main(String args[]) throws Exception - { + public static void main(String args[]) throws Exception { AWSCredentials credentials = null; - try - { + try { credentials = new ProfileCredentialsProvider().getCredentials(); - }catch(Exception e) - { + } catch (Exception e) { throw new AmazonClientException("Cannot Load credentials"); } - + AWSServiceDiscovery client = AWSServiceDiscoveryClientBuilder - .standard() - .withCredentials(new AWSStaticCredentialsProvider(credentials)) - .withRegion("us-east-1") - .build(); - + .standard() + .withCredentials(new AWSStaticCredentialsProvider(credentials)) + .withRegion("us-east-1") + .build(); + DiscoverInstancesRequest direquest = new DiscoverInstancesRequest(); direquest.setNamespaceName("my-apps"); direquest.setServiceName("frontend"); - - //Use a filter to retrieve the service based on environment and version - Map filtermap = new HashMap(); - filtermap.put("Stage", "Dev"); //Stage - key of the custom attribute, Dev - value of the custom attribute - filtermap.put("Version", "01");//Version - key of the custom attribute, 01 - value of the custom attribute + + // Use a filter to retrieve the service based on environment and version + Map filtermap = new HashMap(); + filtermap.put("Stage", "Dev"); // Stage - key of the custom attribute, Dev - value of the custom attribute + filtermap.put("Version", "01");// Version - key of the custom attribute, 01 - value of the custom attribute direquest.setQueryParameters(filtermap); System.out.println(client.discoverInstances(direquest)); } } -//snippet-end:[cloudmap.java.lookup_servicewithfilter_request.complete] \ No newline at end of file +// snippet-end:[cloudmap.java.lookup_servicewithfilter_request.complete] \ No newline at end of file diff --git a/java/example_code/cloudtrail/cloudtrail.java.log-and-digest-file-validation.java b/java/example_code/cloudtrail/cloudtrail.java.log-and-digest-file-validation.java index 03659c26a08..48439ecfaf5 100644 --- a/java/example_code/cloudtrail/cloudtrail.java.log-and-digest-file-validation.java +++ b/java/example_code/cloudtrail/cloudtrail.java.log-and-digest-file-validation.java @@ -1,24 +1,6 @@ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[cloudtrail.java.log-and-digest-file-validation demonstrates how to validate CloudTrail log and digest files.] -// snippet-service:[cloudtrail] -// snippet-keyword:[java] -// snippet-keyword:[AWS CloudTrail] -// snippet-keyword:[Code Sample] -// snippet-keyword:[none] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2015-10-01] -// snippet-sourceauthor:[AWS] // snippet-start:[cloudtrail.java.log-and-digest-file-validation.complete] import java.util.Arrays; @@ -31,9 +13,9 @@ import org.json.JSONObject; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.apache.commons.codec.binary.Hex; - + public class DigestFileValidator { - + public void validateDigestFile(String digestS3Bucket, String digestS3Object, String digestSignature) { // Using the Bouncy Castle provider as a JCE security provider - http://www.bouncycastle.org/ diff --git a/java/example_code/cloudwatch/run_example.sh b/java/example_code/cloudwatch/run_example.sh index 25d960e153a..11304a063fd 100755 --- a/java/example_code/cloudwatch/run_example.sh +++ b/java/example_code/cloudwatch/run_example.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 if [[ -z $* ]] ; then echo 'Supply the name of one of the example classes as an argument.' echo 'If there are arguments to the class, put them in quotes after the class name.' diff --git a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/DeleteAlarm.java b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/DeleteAlarm.java index 66849efad95..a2b34f2ff3e 100644 --- a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/DeleteAlarm.java +++ b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/DeleteAlarm.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[DeleteAlarm.java demonstrates how to delete a CloudWatch alarm.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Cloudwatch] -//snippet-service:[cloudwatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.cloudwatch; + import com.amazonaws.services.cloudwatch.AmazonCloudWatch; import com.amazonaws.services.cloudwatch.AmazonCloudWatchClientBuilder; import com.amazonaws.services.cloudwatch.model.DeleteAlarmsRequest; @@ -33,9 +13,8 @@ public class DeleteAlarm { public static void main(String[] args) { - final String USAGE = - "To run this example, supply an alarm name\n" + - "Ex: DeleteAlarm \n"; + final String USAGE = "To run this example, supply an alarm name\n" + + "Ex: DeleteAlarm \n"; if (args.length != 1) { System.out.println(USAGE); @@ -44,11 +23,10 @@ public static void main(String[] args) { String alarm_name = args[0]; - final AmazonCloudWatch cw = - AmazonCloudWatchClientBuilder.defaultClient(); + final AmazonCloudWatch cw = AmazonCloudWatchClientBuilder.defaultClient(); DeleteAlarmsRequest request = new DeleteAlarmsRequest() - .withAlarmNames(alarm_name); + .withAlarmNames(alarm_name); DeleteAlarmsResult response = cw.deleteAlarms(request); diff --git a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/DeleteSubscriptionFilter.java b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/DeleteSubscriptionFilter.java index 7a0cf7e0bcc..ab35bc973c2 100644 --- a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/DeleteSubscriptionFilter.java +++ b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/DeleteSubscriptionFilter.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[DeleteSubscriptionFilter.java demonstrates how to delete a CloudWatch subscription filter.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Cloudwatch] -//snippet-service:[cloudwatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.cloudwatch; + import com.amazonaws.services.logs.AWSLogs; import com.amazonaws.services.logs.AWSLogsClientBuilder; import com.amazonaws.services.logs.model.DeleteSubscriptionFilterRequest; @@ -33,9 +13,8 @@ public class DeleteSubscriptionFilter { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a filter name and log group name\n" + - "Ex: DeleteSubscriptionFilter \n"; + final String USAGE = "To run this example, supply a filter name and log group name\n" + + "Ex: DeleteSubscriptionFilter \n"; if (args.length != 2) { System.out.println(USAGE); @@ -47,16 +26,14 @@ public static void main(String[] args) { final AWSLogs logs = AWSLogsClientBuilder.defaultClient(); - DeleteSubscriptionFilterRequest request = - new DeleteSubscriptionFilterRequest() + DeleteSubscriptionFilterRequest request = new DeleteSubscriptionFilterRequest() .withFilterName(filter) .withLogGroupName(log_group); - DeleteSubscriptionFilterResult response = - logs.deleteSubscriptionFilter(request); + DeleteSubscriptionFilterResult response = logs.deleteSubscriptionFilter(request); System.out.printf( - "Successfully deleted CloudWatch logs subscription filter %s", - filter); + "Successfully deleted CloudWatch logs subscription filter %s", + filter); } } diff --git a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/DescribeAlarms.java b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/DescribeAlarms.java index ca69f9cf2d6..76e12633adf 100644 --- a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/DescribeAlarms.java +++ b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/DescribeAlarms.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[DescribeAlarms.java demonstrates how to list all CloudWatch alarms.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Cloudwatch] -//snippet-service:[cloudwatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.cloudwatch; + import com.amazonaws.services.cloudwatch.AmazonCloudWatch; import com.amazonaws.services.cloudwatch.AmazonCloudWatchClientBuilder; import com.amazonaws.services.cloudwatch.model.DescribeAlarmsRequest; @@ -35,23 +15,22 @@ public class DescribeAlarms { public static void main(String[] args) { - final AmazonCloudWatch cw = - AmazonCloudWatchClientBuilder.defaultClient(); + final AmazonCloudWatch cw = AmazonCloudWatchClientBuilder.defaultClient(); boolean done = false; DescribeAlarmsRequest request = new DescribeAlarmsRequest(); - while(!done) { + while (!done) { DescribeAlarmsResult response = cw.describeAlarms(request); - for(MetricAlarm alarm : response.getMetricAlarms()) { + for (MetricAlarm alarm : response.getMetricAlarms()) { System.out.printf("Retrieved alarm %s", alarm.getAlarmName()); } request.setNextToken(response.getNextToken()); - if(response.getNextToken() == null) { + if (response.getNextToken() == null) { done = true; } } diff --git a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/DescribeSubscriptionFilters.java b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/DescribeSubscriptionFilters.java index 7b9341f9d2d..7acab3df80c 100644 --- a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/DescribeSubscriptionFilters.java +++ b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/DescribeSubscriptionFilters.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[DescribeSubscriptionFilters.java demonstrates how to list CloudWatch subscription filters associated with a log group.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Cloudwatch] -//snippet-service:[cloudwatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.cloudwatch; + import com.amazonaws.services.logs.AWSLogs; import com.amazonaws.services.logs.AWSLogsClientBuilder; import com.amazonaws.services.logs.model.DescribeSubscriptionFiltersRequest; @@ -35,9 +15,8 @@ public class DescribeSubscriptionFilters { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a log group name\n" + - "Ex: DescribeSubscriptionFilters \n"; + final String USAGE = "To run this example, supply a log group name\n" + + "Ex: DescribeSubscriptionFilters \n"; if (args.length != 1) { System.out.println(USAGE); @@ -49,29 +28,27 @@ public static void main(String[] args) { final AWSLogs logs = AWSLogsClientBuilder.defaultClient(); boolean done = false; - DescribeSubscriptionFiltersRequest request = - new DescribeSubscriptionFiltersRequest() - .withLogGroupName(log_group) - .withLimit(1); + DescribeSubscriptionFiltersRequest request = new DescribeSubscriptionFiltersRequest() + .withLogGroupName(log_group) + .withLimit(1); - while(!done) { + while (!done) { - DescribeSubscriptionFiltersResult response = - logs.describeSubscriptionFilters(request); + DescribeSubscriptionFiltersResult response = logs.describeSubscriptionFilters(request); - for(SubscriptionFilter filter : response.getSubscriptionFilters()) { + for (SubscriptionFilter filter : response.getSubscriptionFilters()) { System.out.printf( - "Retrieved filter with name %s, " + - "pattern %s " + - "and destination arn %s", - filter.getFilterName(), - filter.getFilterPattern(), - filter.getDestinationArn()); + "Retrieved filter with name %s, " + + "pattern %s " + + "and destination arn %s", + filter.getFilterName(), + filter.getFilterPattern(), + filter.getDestinationArn()); } request.setNextToken(response.getNextToken()); - if(response.getNextToken() == null) { + if (response.getNextToken() == null) { done = true; } } diff --git a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/DisableAlarmActions.java b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/DisableAlarmActions.java index aa3c3d3339c..7345acb2321 100644 --- a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/DisableAlarmActions.java +++ b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/DisableAlarmActions.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[DisableAlarmActions.java demonstrates how to disables actions on a CloudWatch alarm.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Cloudwatch] -//snippet-service:[cloudwatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.cloudwatch; + import com.amazonaws.services.cloudwatch.AmazonCloudWatch; import com.amazonaws.services.cloudwatch.AmazonCloudWatchClientBuilder; import com.amazonaws.services.cloudwatch.model.DisableAlarmActionsRequest; @@ -34,9 +14,8 @@ public class DisableAlarmActions { public static void main(String[] args) { - final String USAGE = - "To run this example, supply an alarm name\n" + - "Ex: DisableAlarmActions \n"; + final String USAGE = "To run this example, supply an alarm name\n" + + "Ex: DisableAlarmActions \n"; if (args.length != 1) { System.out.println(USAGE); @@ -45,15 +24,14 @@ public static void main(String[] args) { String alarmName = args[0]; - final AmazonCloudWatch cw = - AmazonCloudWatchClientBuilder.defaultClient(); + final AmazonCloudWatch cw = AmazonCloudWatchClientBuilder.defaultClient(); DisableAlarmActionsRequest request = new DisableAlarmActionsRequest() - .withAlarmNames(alarmName); + .withAlarmNames(alarmName); DisableAlarmActionsResult response = cw.disableAlarmActions(request); System.out.printf( - "Successfully disabled actions on alarm %s", alarmName); + "Successfully disabled actions on alarm %s", alarmName); } } diff --git a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/EnableAlarmActions.java b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/EnableAlarmActions.java index b695c4274fa..a7620a0db4c 100644 --- a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/EnableAlarmActions.java +++ b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/EnableAlarmActions.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[EnableAlarmActions.java demonstrates how to enables actions on a CloudWatch alarm.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Cloudwatch] -//snippet-service:[cloudwatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.cloudwatch; + import com.amazonaws.services.cloudwatch.AmazonCloudWatch; import com.amazonaws.services.cloudwatch.AmazonCloudWatchClientBuilder; import com.amazonaws.services.cloudwatch.model.EnableAlarmActionsRequest; @@ -34,9 +14,8 @@ public class EnableAlarmActions { public static void main(String[] args) { - final String USAGE = - "To run this example, supply an alarm name\n" + - "Ex: EnableAlarmActions \n"; + final String USAGE = "To run this example, supply an alarm name\n" + + "Ex: EnableAlarmActions \n"; if (args.length != 1) { System.out.println(USAGE); @@ -45,15 +24,14 @@ public static void main(String[] args) { String alarm = args[0]; - final AmazonCloudWatch cw = - AmazonCloudWatchClientBuilder.defaultClient(); + final AmazonCloudWatch cw = AmazonCloudWatchClientBuilder.defaultClient(); EnableAlarmActionsRequest request = new EnableAlarmActionsRequest() - .withAlarmNames(alarm); + .withAlarmNames(alarm); EnableAlarmActionsResult response = cw.enableAlarmActions(request); System.out.printf( - "Successfully enabled actions on alarm %s", alarm); + "Successfully enabled actions on alarm %s", alarm); } } diff --git a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/ListMetrics.java b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/ListMetrics.java index 0fc1b5d8035..96096c44dd4 100644 --- a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/ListMetrics.java +++ b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/ListMetrics.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[ListMetrics.java demonstrates how to list CloudWatch metrics.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Cloudwatch] -//snippet-service:[cloudwatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.cloudwatch; + import com.amazonaws.services.cloudwatch.AmazonCloudWatch; import com.amazonaws.services.cloudwatch.AmazonCloudWatchClientBuilder; import com.amazonaws.services.cloudwatch.model.ListMetricsRequest; @@ -35,9 +15,8 @@ public class ListMetrics { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a metric name and metric namespace\n" + - "Ex: ListMetrics \n"; + final String USAGE = "To run this example, supply a metric name and metric namespace\n" + + "Ex: ListMetrics \n"; if (args.length != 2) { System.out.println(USAGE); @@ -47,8 +26,7 @@ public static void main(String[] args) { String name = args[0]; String namespace = args[1]; - final AmazonCloudWatch cw = - AmazonCloudWatchClientBuilder.defaultClient(); + final AmazonCloudWatch cw = AmazonCloudWatchClientBuilder.defaultClient(); ListMetricsRequest request = new ListMetricsRequest() .withMetricName(name) @@ -56,17 +34,17 @@ public static void main(String[] args) { boolean done = false; - while(!done) { + while (!done) { ListMetricsResult response = cw.listMetrics(request); - for(Metric metric : response.getMetrics()) { + for (Metric metric : response.getMetrics()) { System.out.printf( - "Retrieved metric %s", metric.getMetricName()); + "Retrieved metric %s", metric.getMetricName()); } request.setNextToken(response.getNextToken()); - if(response.getNextToken() == null) { + if (response.getNextToken() == null) { done = true; } } diff --git a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutEvents.java b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutEvents.java index 9785aa52cbe..f7d9feba337 100644 --- a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutEvents.java +++ b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutEvents.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[PutEvents.java demonstrates how to put a sample CloudWatch event.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Cloudwatch] -//snippet-service:[cloudwatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.cloudwatch; + import com.amazonaws.services.cloudwatchevents.AmazonCloudWatchEvents; import com.amazonaws.services.cloudwatchevents.AmazonCloudWatchEventsClientBuilder; import com.amazonaws.services.cloudwatchevents.model.PutEventsRequest; @@ -31,13 +11,10 @@ /** * Puts a sample CloudWatch event */ -public class PutEvents -{ - public static void main(String[] args) - { - final String USAGE = - "To run this example, supply a resource arn\n" + - "Ex: PutEvents \n"; +public class PutEvents { + public static void main(String[] args) { + final String USAGE = "To run this example, supply a resource arn\n" + + "Ex: PutEvents \n"; if (args.length != 1) { System.out.println(USAGE); @@ -46,20 +23,18 @@ public static void main(String[] args) String resource_arn = args[0]; - final AmazonCloudWatchEvents cwe = - AmazonCloudWatchEventsClientBuilder.defaultClient(); + final AmazonCloudWatchEvents cwe = AmazonCloudWatchEventsClientBuilder.defaultClient(); - final String EVENT_DETAILS = - "{ \"key1\": \"value1\", \"key2\": \"value2\" }"; + final String EVENT_DETAILS = "{ \"key1\": \"value1\", \"key2\": \"value2\" }"; PutEventsRequestEntry request_entry = new PutEventsRequestEntry() - .withDetail(EVENT_DETAILS) - .withDetailType("sampleSubmitted") - .withResources(resource_arn) - .withSource("aws-sdk-java-cloudwatch-example"); + .withDetail(EVENT_DETAILS) + .withDetailType("sampleSubmitted") + .withResources(resource_arn) + .withSource("aws-sdk-java-cloudwatch-example"); PutEventsRequest request = new PutEventsRequest() - .withEntries(request_entry); + .withEntries(request_entry); PutEventsResult response = cwe.putEvents(request); diff --git a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutMetricAlarm.java b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutMetricAlarm.java index 9cbbce03870..4b73ee10ed7 100644 --- a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutMetricAlarm.java +++ b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutMetricAlarm.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[PutMetricAlarm.java demonstrates how to create a new CloudWatch alarm based on CPU utilization for an instance.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Cloudwatch] -//snippet-service:[cloudwatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.cloudwatch; + import com.amazonaws.services.cloudwatch.AmazonCloudWatch; import com.amazonaws.services.cloudwatch.AmazonCloudWatchClientBuilder; import com.amazonaws.services.cloudwatch.model.ComparisonOperator; @@ -35,47 +15,45 @@ * Creates a new CloudWatch alarm based on CPU utilization for an instance */ public class PutMetricAlarm { - public static void main(String[] args) { - - final String USAGE = - "To run this example, supply an alarm name and instance id\n" + - "Ex: DeleteAlarm \n"; + public static void main(String[] args) { + + final String USAGE = "To run this example, supply an alarm name and instance id\n" + + "Ex: DeleteAlarm \n"; + + if (args.length != 2) { + System.out.println(USAGE); + System.exit(1); + } + + String alarmName = args[0]; + String instanceId = args[1]; + + final AmazonCloudWatch cw = AmazonCloudWatchClientBuilder.defaultClient(); + + Dimension dimension = new Dimension() + .withName("InstanceId") + .withValue(instanceId); + + PutMetricAlarmRequest request = new PutMetricAlarmRequest() + .withAlarmName(alarmName) + .withComparisonOperator( + ComparisonOperator.GreaterThanThreshold) + .withEvaluationPeriods(1) + .withMetricName("CPUUtilization") + .withNamespace("AWS/EC2") + .withPeriod(60) + .withStatistic(Statistic.Average) + .withThreshold(70.0) + .withActionsEnabled(false) + .withAlarmDescription( + "Alarm when server CPU utilization exceeds 70%") + .withUnit(StandardUnit.Seconds) + .withDimensions(dimension); + + PutMetricAlarmResult response = cw.putMetricAlarm(request); + + System.out.printf( + "Successfully created alarm with name %s", alarmName); - if (args.length != 2) { - System.out.println(USAGE); - System.exit(1); } - - String alarmName = args[0]; - String instanceId = args[1]; - - final AmazonCloudWatch cw = - AmazonCloudWatchClientBuilder.defaultClient(); - - Dimension dimension = new Dimension() - .withName("InstanceId") - .withValue(instanceId); - - PutMetricAlarmRequest request = new PutMetricAlarmRequest() - .withAlarmName(alarmName) - .withComparisonOperator( - ComparisonOperator.GreaterThanThreshold) - .withEvaluationPeriods(1) - .withMetricName("CPUUtilization") - .withNamespace("AWS/EC2") - .withPeriod(60) - .withStatistic(Statistic.Average) - .withThreshold(70.0) - .withActionsEnabled(false) - .withAlarmDescription( - "Alarm when server CPU utilization exceeds 70%") - .withUnit(StandardUnit.Seconds) - .withDimensions(dimension); - - PutMetricAlarmResult response = cw.putMetricAlarm(request); - - System.out.printf( - "Successfully created alarm with name %s", alarmName); - - } } diff --git a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutMetricData.java b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutMetricData.java index 3fd9095572a..03bc2a8ed3d 100644 --- a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutMetricData.java +++ b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutMetricData.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[PutMetricData.java demonstrates how to put a sample metric data point.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Cloudwatch] -//snippet-service:[cloudwatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.cloudwatch; + import com.amazonaws.services.cloudwatch.AmazonCloudWatch; import com.amazonaws.services.cloudwatch.AmazonCloudWatchClientBuilder; import com.amazonaws.services.cloudwatch.model.Dimension; @@ -34,38 +14,36 @@ * Puts a sample metric data point */ public class PutMetricData { - public static void main(String[] args) { + public static void main(String[] args) { - final String USAGE = - "To run this example, supply a data point:\n" + - "Ex: PutMetricData \n"; + final String USAGE = "To run this example, supply a data point:\n" + + "Ex: PutMetricData \n"; - if (args.length != 1) { - System.out.println(USAGE); - System.exit(1); - } + if (args.length != 1) { + System.out.println(USAGE); + System.exit(1); + } - Double data_point = Double.parseDouble(args[0]); + Double data_point = Double.parseDouble(args[0]); - final AmazonCloudWatch cw = - AmazonCloudWatchClientBuilder.defaultClient(); + final AmazonCloudWatch cw = AmazonCloudWatchClientBuilder.defaultClient(); - Dimension dimension = new Dimension() - .withName("UNIQUE_PAGES") - .withValue("URLS"); + Dimension dimension = new Dimension() + .withName("UNIQUE_PAGES") + .withValue("URLS"); - MetricDatum datum = new MetricDatum() - .withMetricName("PAGES_VISITED") - .withUnit(StandardUnit.None) - .withValue(data_point) - .withDimensions(dimension); + MetricDatum datum = new MetricDatum() + .withMetricName("PAGES_VISITED") + .withUnit(StandardUnit.None) + .withValue(data_point) + .withDimensions(dimension); - PutMetricDataRequest request = new PutMetricDataRequest() - .withNamespace("SITE/TRAFFIC") - .withMetricData(datum); + PutMetricDataRequest request = new PutMetricDataRequest() + .withNamespace("SITE/TRAFFIC") + .withMetricData(datum); - PutMetricDataResult response = cw.putMetricData(request); + PutMetricDataResult response = cw.putMetricData(request); - System.out.printf("Successfully put data point %f", data_point); - } + System.out.printf("Successfully put data point %f", data_point); + } } diff --git a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutRule.java b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutRule.java index 5928cb54428..7b3230913bf 100644 --- a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutRule.java +++ b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutRule.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[PutRule.java demonstrates how to create a CloudWatch event-routing rule.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Cloudwatch] -//snippet-service:[cloudwatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.cloudwatch; + import com.amazonaws.services.cloudwatchevents.AmazonCloudWatchEvents; import com.amazonaws.services.cloudwatchevents.AmazonCloudWatchEventsClientBuilder; import com.amazonaws.services.cloudwatchevents.model.PutRuleRequest; @@ -35,9 +15,8 @@ public class PutRule { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a rule name and role arn\n" + - "Ex: PutRule \n"; + final String USAGE = "To run this example, supply a rule name and role arn\n" + + "Ex: PutRule \n"; if (args.length != 2) { System.out.println(USAGE); @@ -47,19 +26,18 @@ public static void main(String[] args) { String rule_name = args[0]; String role_arn = args[1]; - final AmazonCloudWatchEvents cwe = - AmazonCloudWatchEventsClientBuilder.defaultClient(); + final AmazonCloudWatchEvents cwe = AmazonCloudWatchEventsClientBuilder.defaultClient(); PutRuleRequest request = new PutRuleRequest() - .withName(rule_name) - .withRoleArn(role_arn) - .withScheduleExpression("rate(5 minutes)") - .withState(RuleState.ENABLED); + .withName(rule_name) + .withRoleArn(role_arn) + .withScheduleExpression("rate(5 minutes)") + .withState(RuleState.ENABLED); PutRuleResult response = cwe.putRule(request); System.out.printf( - "Successfully created CloudWatch events rule %s with arn %s", - rule_name, response.getRuleArn()); + "Successfully created CloudWatch events rule %s with arn %s", + rule_name, response.getRuleArn()); } } diff --git a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutSubscriptionFilter.java b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutSubscriptionFilter.java index 5a6aef7dc7d..5cf8d415123 100644 --- a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutSubscriptionFilter.java +++ b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutSubscriptionFilter.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[PutSubscriptionFilter.java demonstrates how to create a CloudWatch Logs subscription filter.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Cloudwatch] -//snippet-service:[cloudwatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.cloudwatch; + import com.amazonaws.services.logs.AWSLogs; import com.amazonaws.services.logs.AWSLogsClientBuilder; import com.amazonaws.services.logs.model.PutSubscriptionFilterRequest; @@ -33,16 +13,15 @@ public class PutSubscriptionFilter { public static void main(String[] args) { - final String USAGE = - "To run this example, supply:\n" + - "* a filter name\n" + - "* filter pattern\n" + - "* log group name\n" + - "* lambda function arn\n\n" + - "Ex: PutSubscriptionFilter \\\n" + - " \\\n" + - " \\\n" + - " \n"; + final String USAGE = "To run this example, supply:\n" + + "* a filter name\n" + + "* filter pattern\n" + + "* log group name\n" + + "* lambda function arn\n\n" + + "Ex: PutSubscriptionFilter \\\n" + + " \\\n" + + " \\\n" + + " \n"; if (args.length != 4) { System.out.println(USAGE); @@ -56,18 +35,16 @@ public static void main(String[] args) { final AWSLogs cwl = AWSLogsClientBuilder.defaultClient(); - PutSubscriptionFilterRequest request = - new PutSubscriptionFilterRequest() + PutSubscriptionFilterRequest request = new PutSubscriptionFilterRequest() .withFilterName(filter) .withFilterPattern(pattern) .withLogGroupName(log_group) .withDestinationArn(function_arn); - PutSubscriptionFilterResult response = - cwl.putSubscriptionFilter(request); + PutSubscriptionFilterResult response = cwl.putSubscriptionFilter(request); System.out.printf( - "Successfully created CloudWatch logs subscription filter %s", - filter); + "Successfully created CloudWatch logs subscription filter %s", + filter); } } diff --git a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutTargets.java b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutTargets.java index 5b777e8421d..bb9cede75a5 100644 --- a/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutTargets.java +++ b/java/example_code/cloudwatch/src/main/java/aws/example/cloudwatch/PutTargets.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[PutTargets.java demonstrates how to create a CloudWatch event-routing rule target.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Cloudwatch] -//snippet-service:[cloudwatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.cloudwatch; + import com.amazonaws.services.cloudwatchevents.AmazonCloudWatchEvents; import com.amazonaws.services.cloudwatchevents.AmazonCloudWatchEventsClientBuilder; import com.amazonaws.services.cloudwatchevents.model.PutTargetsRequest; @@ -33,39 +13,37 @@ */ public class PutTargets { - public static void main(String[] args) { + public static void main(String[] args) { - final String USAGE = - "To run this example, supply:\n" + - "* a rule name\n" + - "* lambda function arn\n" + - "* target id\n\n" + - "Ex: PutTargets \n"; + final String USAGE = "To run this example, supply:\n" + + "* a rule name\n" + + "* lambda function arn\n" + + "* target id\n\n" + + "Ex: PutTargets \n"; - if (args.length != 3) { - System.out.println(USAGE); - System.exit(1); - } + if (args.length != 3) { + System.out.println(USAGE); + System.exit(1); + } - String rule_name = args[0]; - String function_arn = args[1]; - String target_id = args[2]; + String rule_name = args[0]; + String function_arn = args[1]; + String target_id = args[2]; - final AmazonCloudWatchEvents cwe = - AmazonCloudWatchEventsClientBuilder.defaultClient(); + final AmazonCloudWatchEvents cwe = AmazonCloudWatchEventsClientBuilder.defaultClient(); - Target target = new Target() - .withArn(function_arn) - .withId(target_id); + Target target = new Target() + .withArn(function_arn) + .withId(target_id); - PutTargetsRequest request = new PutTargetsRequest() - .withTargets(target) - .withRule(rule_name); + PutTargetsRequest request = new PutTargetsRequest() + .withTargets(target) + .withRule(rule_name); - PutTargetsResult response = cwe.putTargets(request); + PutTargetsResult response = cwe.putTargets(request); - System.out.printf( - "Successfully created CloudWatch events target for rule %s", - rule_name); - } + System.out.printf( + "Successfully created CloudWatch events target for rule %s", + rule_name); + } } diff --git a/java/example_code/cognito/src/main/java/aws/example/cognito/EnableMFAForCognitoUser.java b/java/example_code/cognito/src/main/java/aws/example/cognito/EnableMFAForCognitoUser.java index fb429f9c22d..2e8296331c3 100644 --- a/java/example_code/cognito/src/main/java/aws/example/cognito/EnableMFAForCognitoUser.java +++ b/java/example_code/cognito/src/main/java/aws/example/cognito/EnableMFAForCognitoUser.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[EnableMFAForCognitoUser.java demonstrates how to enable MFA in Cognito Userpool which MFA is optional to users] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Cognito] -//snippet-service:[cognito] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-06-20] -//snippet-sourceauthor:[wenzaca] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). @@ -20,7 +13,7 @@ * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ -//snippet-start:[cognito.java.mfa.complete] +// snippet-start:[cognito.java.mfa.complete] package aws.example.cognito; import com.amazonaws.services.cognitoidp.AWSCognitoIdentityProvider; @@ -31,67 +24,71 @@ public class EnableMFAForCognitoUser { - // TODO - Add your data here! - static String USERNAME = ""; // Input an unique username for the UserPool - static String PHONE_NUMBER = ""; // Input the user phone number for the user Attribute - static String USERPOOL_ID = ""; // Input the UserPool Id, e.g. us-east-1_xxxxxxxx - static String USER_TEMP_PASSWORD = ""; // Input the temporary password for the user - static String USER_EMAIL = ""; // Input the email for the user attribute + // TODO - Add your data here! + static String USERNAME = ""; // Input an unique username for the UserPool + static String PHONE_NUMBER = ""; // Input the user phone number for the user Attribute + static String USERPOOL_ID = ""; // Input the UserPool Id, e.g. us-east-1_xxxxxxxx + static String USER_TEMP_PASSWORD = ""; // Input the temporary password for the user + static String USER_EMAIL = ""; // Input the email for the user attribute - public static void main(String[] args) { + public static void main(String[] args) { - AWSCognitoIdentityProvider cognitoIdentityProvider = AWSCognitoIdentityProviderClientBuilder.defaultClient(); + AWSCognitoIdentityProvider cognitoIdentityProvider = AWSCognitoIdentityProviderClientBuilder + .defaultClient(); - // Create User in UserPool using AdminCreateUser - // @see label - cognitoIdentityProvider.adminCreateUser( - new AdminCreateUserRequest() - .withUserPoolId(USERPOOL_ID) - .withUsername(USERNAME) - .withTemporaryPassword(USER_TEMP_PASSWORD) - .withUserAttributes( - new AttributeType() - .withName("phone_number") - .withValue(PHONE_NUMBER), - new AttributeType() - .withName("phone_number_verified") - .withValue("true"), - new AttributeType() - .withName("email") - .withValue(USER_EMAIL))); + // Create User in UserPool using AdminCreateUser + // @see label + cognitoIdentityProvider.adminCreateUser( + new AdminCreateUserRequest() + .withUserPoolId(USERPOOL_ID) + .withUsername(USERNAME) + .withTemporaryPassword(USER_TEMP_PASSWORD) + .withUserAttributes( + new AttributeType() + .withName("phone_number") + .withValue(PHONE_NUMBER), + new AttributeType() + .withName("phone_number_verified") + .withValue("true"), + new AttributeType() + .withName("email") + .withValue(USER_EMAIL))); - SMSMfaSettingsType sMSMfaSettings = new SMSMfaSettingsType().withPreferredMfa(Boolean.TRUE).withEnabled(Boolean.TRUE); + SMSMfaSettingsType sMSMfaSettings = new SMSMfaSettingsType().withPreferredMfa(Boolean.TRUE) + .withEnabled(Boolean.TRUE); - // Set MFA preferred type for the User using AdminSetUserMFAPreference - // @see label - cognitoIdentityProvider.adminSetUserMFAPreference( - new AdminSetUserMFAPreferenceRequest() - .withSMSMfaSettings(sMSMfaSettings) - .withUserPoolId(USERPOOL_ID) - .withUsername(USERNAME)); + // Set MFA preferred type for the User using AdminSetUserMFAPreference + // @see label + cognitoIdentityProvider.adminSetUserMFAPreference( + new AdminSetUserMFAPreferenceRequest() + .withSMSMfaSettings(sMSMfaSettings) + .withUserPoolId(USERPOOL_ID) + .withUsername(USERNAME)); - // Add MFA Options type for the User using AdminSetUserSettings - // @see label - cognitoIdentityProvider.adminSetUserSettings( - new AdminSetUserSettingsRequest() - .withUserPoolId(USERPOOL_ID) - .withUsername(USERNAME) - .withMFAOptions(Arrays.asList( - new MFAOptionType() - .withDeliveryMedium("SMS") - .withAttributeName("phone_number")))); + // Add MFA Options type for the User using AdminSetUserSettings + // @see label + cognitoIdentityProvider.adminSetUserSettings( + new AdminSetUserSettingsRequest() + .withUserPoolId(USERPOOL_ID) + .withUsername(USERNAME) + .withMFAOptions(Arrays.asList( + new MFAOptionType() + .withDeliveryMedium("SMS") + .withAttributeName("phone_number")))); - - // Validate the data created/updated in this class. - AdminGetUserResult user = cognitoIdentityProvider.adminGetUser( - new AdminGetUserRequest() - .withUserPoolId(USERPOOL_ID) - .withUsername(USERNAME)); - assert (user.getUsername().equals(USERNAME)); - assert (!user.getMFAOptions().isEmpty()); - assert (user.getMFAOptions().get(0).getDeliveryMedium().equals("SMS")); - assert (user.getPreferredMfaSetting().equals("SMS_MFA")); - assert (user.getEnabled()); - } + // Validate the data created/updated in this class. + AdminGetUserResult user = cognitoIdentityProvider.adminGetUser( + new AdminGetUserRequest() + .withUserPoolId(USERPOOL_ID) + .withUsername(USERNAME)); + assert (user.getUsername().equals(USERNAME)); + assert (!user.getMFAOptions().isEmpty()); + assert (user.getMFAOptions().get(0).getDeliveryMedium().equals("SMS")); + assert (user.getPreferredMfaSetting().equals("SMS_MFA")); + assert (user.getEnabled()); + } } -//snippet-end:[cognito.java.mfa.complete] +// snippet-end:[cognito.java.mfa.complete] diff --git a/java/example_code/comprehend/BatchProcessing.java b/java/example_code/comprehend/BatchProcessing.java index 9ff25ad7f79..299518cafdc 100644 --- a/java/example_code/comprehend/BatchProcessing.java +++ b/java/example_code/comprehend/BatchProcessing.java @@ -1,24 +1,4 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[DeleteDominantLanguage demonstrates how to determine the dominant language used in a text.] -// snippet-service:[comprehend] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon comprehend] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DetectDominantLanguage] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] +/*/ diff --git a/java/example_code/comprehend/ComprehendMedicalSample.java b/java/example_code/comprehend/ComprehendMedicalSample.java index 14d27ddf428..846b0551417 100644 --- a/java/example_code/comprehend/ComprehendMedicalSample.java +++ b/java/example_code/comprehend/ComprehendMedicalSample.java @@ -1,61 +1,50 @@ -// snippet-sourcedescription:[ComprehendMedicalSample.java demonstrates getting medical entities from text.] -// snippet-service:[comprehend] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Comprehend Medical] -// snippet-keyword:[Code Sample] -// snippet-keyword:[AWSComprehendMedical] -// snippet-keyword:[DetectEntitiesRequest] -// snippet-keyword:[DetectEntitiesResult] -// snippet-keyword:[detectEntities] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2019-01-10] -// snippet-sourceauthor:[AWS] -/** - * COPYRIGHT: - * - * Copyright 2018-2019 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://www.apache.org/licenses/LICENSE-2.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. - */ -// snippet-start:[comprehend-medical.java-detect-entities] -import com.amazonaws.auth.AWSCredentials; -import com.amazonaws.auth.AWSCredentialsProvider; -import com.amazonaws.auth.AWSStaticCredentialsProvider; -import com.amazonaws.auth.BasicAWSCredentials; -import com.amazonaws.client.builder.AwsClientBuilder; -import com.amazonaws.services.comprehendmedical.AWSComprehendMedical; -import com.amazonaws.services.comprehendmedical.AWSComprehendMedicalClient; -import com.amazonaws.services.comprehendmedical.model.DetectEntitiesRequest; -import com.amazonaws.services.comprehendmedical.model.DetectEntitiesResult; - -public class SampleAPICall { - - public static void main() { - - AWSCredentialsProvider credentials - = new AWSStaticCredentialsProvider(new BasicAWSCredentials("YOUR AWS ACCESS KEY", "YOUR AWS SECRET")); - - AWSComprehendMedical client = AWSComprehendMedicalClient.builder() - .withCredentials(credentials) - .withRegion("YOUR REGION") - .build(); - - - DetectEntitiesRequest request = new DetectEntitiesRequest(); - request.setText("cerealx 84 mg daily"); - - DetectEntitiesResult result = client.detectEntities(request); - result.getEntities().forEach(System.out::println); - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/** + * COPYRIGHT: + * + * Copyright 2018-2019 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://www.apache.org/licenses/LICENSE-2.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. + */ +// snippet-start:[comprehend-medical.java-detect-entities] +import com.amazonaws.auth.AWSCredentials; +import com.amazonaws.auth.AWSCredentialsProvider; +import com.amazonaws.auth.AWSStaticCredentialsProvider; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.client.builder.AwsClientBuilder; +import com.amazonaws.services.comprehendmedical.AWSComprehendMedical; +import com.amazonaws.services.comprehendmedical.AWSComprehendMedicalClient; +import com.amazonaws.services.comprehendmedical.model.DetectEntitiesRequest; +import com.amazonaws.services.comprehendmedical.model.DetectEntitiesResult; + +public class SampleAPICall { + + public static void main() { + + AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider( + new BasicAWSCredentials("YOUR AWS ACCESS KEY", "YOUR AWS SECRET")); + + AWSComprehendMedical client = AWSComprehendMedicalClient.builder() + .withCredentials(credentials) + .withRegion("YOUR REGION") + .build(); + + DetectEntitiesRequest request = new DetectEntitiesRequest(); + request.setText("cerealx 84 mg daily"); + + DetectEntitiesResult result = client.detectEntities(request); + result.getEntities().forEach(System.out::println); + } +} // snippet-end:[comprehend-medical.java-detect-entities] \ No newline at end of file diff --git a/java/example_code/comprehend/CreateTrainandRunCustomEntityDetector.java b/java/example_code/comprehend/CreateTrainandRunCustomEntityDetector.java index 9ff25ad7f79..299518cafdc 100644 --- a/java/example_code/comprehend/CreateTrainandRunCustomEntityDetector.java +++ b/java/example_code/comprehend/CreateTrainandRunCustomEntityDetector.java @@ -1,24 +1,4 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[DeleteDominantLanguage demonstrates how to determine the dominant language used in a text.] -// snippet-service:[comprehend] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon comprehend] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DetectDominantLanguage] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] +/*/ diff --git a/java/example_code/comprehend/CreateandTrainCustomClassifier.java b/java/example_code/comprehend/CreateandTrainCustomClassifier.java index 9ff25ad7f79..299518cafdc 100644 --- a/java/example_code/comprehend/CreateandTrainCustomClassifier.java +++ b/java/example_code/comprehend/CreateandTrainCustomClassifier.java @@ -1,24 +1,4 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[DeleteDominantLanguage demonstrates how to determine the dominant language used in a text.] -// snippet-service:[comprehend] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon comprehend] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DetectDominantLanguage] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] +/*/ diff --git a/java/example_code/comprehend/DetectDominantLanguage.java b/java/example_code/comprehend/DetectDominantLanguage.java index 1b888ed79a7..a1fcb84225c 100644 --- a/java/example_code/comprehend/DetectDominantLanguage.java +++ b/java/example_code/comprehend/DetectDominantLanguage.java @@ -1,59 +1,37 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[DeleteLexicon demonstrates how to delete Amazon Polly lexicons.] -// snippet-service:[polly] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Polly] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DeleteLexicon] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] // snippet-start:[polly.java.DeleteLexicon.complete] - package com.amazonaws.polly.samples; - + import com.amazonaws.services.polly.AmazonPolly; import com.amazonaws.services.polly.AmazonPollyClientBuilder; import com.amazonaws.services.polly.model.DescribeVoicesRequest; import com.amazonaws.services.polly.model.DescribeVoicesResult; - + public class DescribeVoicesSample { AmazonPolly client = AmazonPollyClientBuilder.defaultClient(); - + public void describeVoices() { DescribeVoicesRequest allVoicesRequest = new DescribeVoicesRequest(); DescribeVoicesRequest enUsVoicesRequest = new DescribeVoicesRequest().withLanguageCode("en-US"); - + try { String nextToken; do { DescribeVoicesResult allVoicesResult = client.describeVoices(allVoicesRequest); nextToken = allVoicesResult.getNextToken(); allVoicesRequest.setNextToken(nextToken); - + System.out.println("All voices: " + allVoicesResult.getVoices()); } while (nextToken != null); - + do { DescribeVoicesResult enUsVoicesResult = client.describeVoices(enUsVoicesRequest); nextToken = enUsVoicesResult.getNextToken(); enUsVoicesRequest.setNextToken(nextToken); - + System.out.println("en-US voices: " + enUsVoicesResult.getVoices()); } while (nextToken != null); } catch (Exception e) { @@ -62,7 +40,4 @@ public void describeVoices() { } } - - - // snippet-end:[polly.java.DeleteLexicon.complete] \ No newline at end of file diff --git a/java/example_code/comprehend/DetectEntities.java b/java/example_code/comprehend/DetectEntities.java index 9ff25ad7f79..aaffa664f2f 100644 --- a/java/example_code/comprehend/DetectEntities.java +++ b/java/example_code/comprehend/DetectEntities.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * @@ -10,15 +12,4 @@ * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[DeleteDominantLanguage demonstrates how to determine the dominant language used in a text.] -// snippet-service:[comprehend] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon comprehend] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DetectDominantLanguage] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] + */ diff --git a/java/example_code/comprehend/DetectKeyPhrases.java b/java/example_code/comprehend/DetectKeyPhrases.java index 9ff25ad7f79..299518cafdc 100644 --- a/java/example_code/comprehend/DetectKeyPhrases.java +++ b/java/example_code/comprehend/DetectKeyPhrases.java @@ -1,24 +1,4 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[DeleteDominantLanguage demonstrates how to determine the dominant language used in a text.] -// snippet-service:[comprehend] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon comprehend] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DetectDominantLanguage] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] +/*/ diff --git a/java/example_code/comprehend/DetectSentiment.java b/java/example_code/comprehend/DetectSentiment.java index 9ff25ad7f79..299518cafdc 100644 --- a/java/example_code/comprehend/DetectSentiment.java +++ b/java/example_code/comprehend/DetectSentiment.java @@ -1,24 +1,4 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[DeleteDominantLanguage demonstrates how to determine the dominant language used in a text.] -// snippet-service:[comprehend] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon comprehend] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DetectDominantLanguage] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] +/*/ diff --git a/java/example_code/comprehend/DetectSyntax.java b/java/example_code/comprehend/DetectSyntax.java index 9ff25ad7f79..299518cafdc 100644 --- a/java/example_code/comprehend/DetectSyntax.java +++ b/java/example_code/comprehend/DetectSyntax.java @@ -1,24 +1,4 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[DeleteDominantLanguage demonstrates how to determine the dominant language used in a text.] -// snippet-service:[comprehend] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon comprehend] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DetectDominantLanguage] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] +/*/ diff --git a/java/example_code/comprehend/TopicModeling.java b/java/example_code/comprehend/TopicModeling.java index 9ff25ad7f79..299518cafdc 100644 --- a/java/example_code/comprehend/TopicModeling.java +++ b/java/example_code/comprehend/TopicModeling.java @@ -1,24 +1,4 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[DeleteDominantLanguage demonstrates how to determine the dominant language used in a text.] -// snippet-service:[comprehend] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon comprehend] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DetectDominantLanguage] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] +/*/ diff --git a/java/example_code/dynamodb/TryDax/DaxAsyncClientDemo.java b/java/example_code/dynamodb/TryDax/DaxAsyncClientDemo.java index 5f59e0d168f..05552b9ec8f 100644 --- a/java/example_code/dynamodb/TryDax/DaxAsyncClientDemo.java +++ b/java/example_code/dynamodb/TryDax/DaxAsyncClientDemo.java @@ -1,29 +1,10 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.trydax.DaxAsyncClientDemo] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ -import java.util.HashMap; +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[dynamodb.java.trydax.DaxAsyncClientDemo] import java.util.HashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; @@ -37,61 +18,61 @@ import com.amazonaws.services.dynamodbv2.model.GetItemResult; public class DaxAsyncClientDemo { - public static void main(String[] args) throws Exception { + public static void main(String[] args) throws Exception { - ClientConfig daxConfig = new ClientConfig().withCredentialsProvider(new ProfileCredentialsProvider()) - .withEndpoints("mydaxcluster.2cmrwl.clustercfg.dax.use1.cache.amazonaws.com:8111"); + ClientConfig daxConfig = new ClientConfig().withCredentialsProvider(new ProfileCredentialsProvider()) + .withEndpoints("mydaxcluster.2cmrwl.clustercfg.dax.use1.cache.amazonaws.com:8111"); - AmazonDynamoDBAsync client = new ClusterDaxAsyncClient(daxConfig); + AmazonDynamoDBAsync client = new ClusterDaxAsyncClient(daxConfig); - HashMap key = new HashMap(); - key.put("Artist", new AttributeValue().withS("No One You Know")); - key.put("SongTitle", new AttributeValue().withS("Scared of My Shadow")); + HashMap key = new HashMap(); + key.put("Artist", new AttributeValue().withS("No One You Know")); + key.put("SongTitle", new AttributeValue().withS("Scared of My Shadow")); - GetItemRequest request = new GetItemRequest() - .withTableName("Music").withKey(key); + GetItemRequest request = new GetItemRequest() + .withTableName("Music").withKey(key); - // Java Futures - Future call = client.getItemAsync(request); - while (!call.isDone()) { - // Do other processing while you're waiting for the response - System.out.println("Doing something else for a few seconds..."); - Thread.sleep(3000); - } - // The results should be ready by now - - try { - call.get(); - - } catch (ExecutionException ee) { - // Futures always wrap errors as an ExecutionException. - // The *real* exception is stored as the cause of the - // ExecutionException - Throwable exception = ee.getCause(); - System.out.println("Error getting item: " + exception.getMessage()); - } + // Java Futures + Future call = client.getItemAsync(request); + while (!call.isDone()) { + // Do other processing while you're waiting for the response + System.out.println("Doing something else for a few seconds..."); + Thread.sleep(3000); + } + // The results should be ready by now + + try { + call.get(); + + } catch (ExecutionException ee) { + // Futures always wrap errors as an ExecutionException. + // The *real* exception is stored as the cause of the + // ExecutionException + Throwable exception = ee.getCause(); + System.out.println("Error getting item: " + exception.getMessage()); + } - // Async callbacks - call = client.getItemAsync(request, new AsyncHandler() { - - @Override - public void onSuccess(GetItemRequest request, GetItemResult getItemResult) { - System.out.println("Result: " + getItemResult); - } - - @Override - public void onError(Exception e) { - System.out.println("Unable to read item"); - System.err.println(e.getMessage()); - // Callers can also test if exception is an instance of - // AmazonServiceException or AmazonClientException and cast - // it to get additional information - } - - }); - call.get(); - - } + // Async callbacks + call = client.getItemAsync(request, new AsyncHandler() { + + @Override + public void onSuccess(GetItemRequest request, GetItemResult getItemResult) { + System.out.println("Result: " + getItemResult); + } + + @Override + public void onError(Exception e) { + System.out.println("Unable to read item"); + System.err.println(e.getMessage()); + // Callers can also test if exception is an instance of + // AmazonServiceException or AmazonClientException and cast + // it to get additional information + } + + }); + call.get(); + + } } -// snippet-end:[dynamodb.java.trydax.DaxAsyncClientDemo] \ No newline at end of file +// snippet-end:[dynamodb.java.trydax.DaxAsyncClientDemo] \ No newline at end of file diff --git a/java/example_code/dynamodb/TryDax/TryDax.java b/java/example_code/dynamodb/TryDax/TryDax.java index d5ef7843361..d8f1d60d535 100644 --- a/java/example_code/dynamodb/TryDax/TryDax.java +++ b/java/example_code/dynamodb/TryDax/TryDax.java @@ -1,34 +1,12 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.trydax.TryDax] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ -import com.amazonaws.services.dynamodbv2.document.DynamoDB; +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[dynamodb.java.trydax.TryDax] import com.amazonaws.services.dynamodbv2.document.DynamoDB; public class TryDax { public static void main(String[] args) throws Exception { - + TryDaxHelper helper = new TryDaxHelper(); TryDaxTests tests = new TryDaxTests(); @@ -70,4 +48,4 @@ public static void main(String[] args) throws Exception { } -// snippet-end:[dynamodb.java.trydax.TryDax] \ No newline at end of file +// snippet-end:[dynamodb.java.trydax.TryDax] \ No newline at end of file diff --git a/java/example_code/dynamodb/TryDax/TryDaxHelper.java b/java/example_code/dynamodb/TryDax/TryDaxHelper.java index 078468c3166..f4a3d762f2f 100644 --- a/java/example_code/dynamodb/TryDax/TryDaxHelper.java +++ b/java/example_code/dynamodb/TryDax/TryDaxHelper.java @@ -1,29 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.trydax.TryDaxHelper] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ -import java.util.Arrays; +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[dynamodb.java.trydax.TryDaxHelper] import java.util.Arrays; import com.amazon.dax.client.dynamodbv2.AmazonDaxClientBuilder; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; @@ -38,7 +16,7 @@ import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import com.amazonaws.util.EC2MetadataUtils; - public class TryDaxHelper { +public class TryDaxHelper { private static final String region = EC2MetadataUtils.getEC2InstanceRegion(); @@ -48,7 +26,7 @@ DynamoDB getDynamoDBClient() { .withRegion(region) .build(); return new DynamoDB(client); - } + } DynamoDB getDaxClient(String daxEndpoint) { System.out.println("Creating a DAX client with cluster endpoint " + daxEndpoint); @@ -56,16 +34,16 @@ DynamoDB getDaxClient(String daxEndpoint) { daxClientBuilder.withRegion(region).withEndpointConfiguration(daxEndpoint); AmazonDynamoDB client = daxClientBuilder.build(); return new DynamoDB(client); - } + } - void createTable(String tableName, DynamoDB client) { + void createTable(String tableName, DynamoDB client) { Table table = client.getTable(tableName); try { System.out.println("Attempting to create table; please wait..."); table = client.createTable(tableName, Arrays.asList( - new KeySchemaElement("pk", KeyType.HASH), // Partition key + new KeySchemaElement("pk", KeyType.HASH), // Partition key new KeySchemaElement("sk", KeyType.RANGE)), // Sort key Arrays.asList( new AttributeDefinition("pk", ScalarAttributeType.N), @@ -96,9 +74,9 @@ void writeData(String tableName, DynamoDB client, int pkmax, int skmax) { for (Integer ipk = 1; ipk <= pkmax; ipk++) { System.out.println(("Writing " + skmax + " items for partition key: " + ipk)); for (Integer isk = 1; isk <= skmax; isk++) { - table.putItem(new Item() - .withPrimaryKey("pk", ipk, "sk", isk) - .withString("someData", someData)); + table.putItem(new Item() + .withPrimaryKey("pk", ipk, "sk", isk) + .withString("someData", someData)); } } } catch (Exception e) { @@ -123,4 +101,4 @@ void deleteTable(String tableName, DynamoDB client) { } -// snippet-end:[dynamodb.java.trydax.TryDaxHelper] \ No newline at end of file +// snippet-end:[dynamodb.java.trydax.TryDaxHelper] \ No newline at end of file diff --git a/java/example_code/dynamodb/TryDax/TryDaxTests.java b/java/example_code/dynamodb/TryDax/TryDaxTests.java index e6f9dfb4fe8..0190d55cf42 100644 --- a/java/example_code/dynamodb/TryDax/TryDaxTests.java +++ b/java/example_code/dynamodb/TryDax/TryDaxTests.java @@ -1,29 +1,10 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.trydax.TryDaxTests] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ -import java.util.HashMap; +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[dynamodb.java.trydax.TryDaxTests] import java.util.HashMap; import java.util.Iterator; import com.amazonaws.services.dynamodbv2.document.DynamoDB; @@ -119,4 +100,4 @@ public void printTime(long startTime, long endTime, int iterations) { } } -// snippet-end:[dynamodb.java.trydax.TryDaxTests] \ No newline at end of file +// snippet-end:[dynamodb.java.trydax.TryDaxTests] \ No newline at end of file diff --git a/java/example_code/dynamodb/autoscaling/DisableDynamoDBAutoscaling.java b/java/example_code/dynamodb/autoscaling/DisableDynamoDBAutoscaling.java index cff8180b89d..5f9c1595f3f 100644 --- a/java/example_code/dynamodb/autoscaling/DisableDynamoDBAutoscaling.java +++ b/java/example_code/dynamodb/autoscaling/DisableDynamoDBAutoscaling.java @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[dynamodb.java.codeexample.DisableDynamoDBAutoscaling] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ package com.amazonaws.codesamples.autoscaling; import com.amazonaws.services.applicationautoscaling.AWSApplicationAutoScalingClient; @@ -36,77 +16,77 @@ public class DisableDynamoDBAutoscaling { - static AWSApplicationAutoScalingClient aaClient = new AWSApplicationAutoScalingClient(); - - public static void main(String args[]) { - - ServiceNamespace ns = ServiceNamespace.Dynamodb; - ScalableDimension tableWCUs = ScalableDimension.DynamodbTableWriteCapacityUnits; - String resourceID = "table/TestTable"; - - // Delete the scaling policy - DeleteScalingPolicyRequest delSPRequest = new DeleteScalingPolicyRequest() - .withServiceNamespace(ns) - .withScalableDimension(tableWCUs) - .withResourceId(resourceID) - .withPolicyName("MyScalingPolicy"); - - try { - aaClient.deleteScalingPolicy(delSPRequest); - } catch (Exception e) { - System.err.println("Unable to delete scaling policy: "); - System.err.println(e.getMessage()); - } + static AWSApplicationAutoScalingClient aaClient = new AWSApplicationAutoScalingClient(); - // Verify that the scaling policy was deleted - DescribeScalingPoliciesRequest descSPRequest = new DescribeScalingPoliciesRequest() - .withServiceNamespace(ns) - .withScalableDimension(tableWCUs) - .withResourceId(resourceID); - - try { - DescribeScalingPoliciesResult dspResult = aaClient.describeScalingPolicies(descSPRequest); - System.out.println("DescribeScalingPolicies result: "); - System.out.println(dspResult); - } catch (Exception e) { - e.printStackTrace(); - System.err.println("Unable to describe scaling policy: "); - System.err.println(e.getMessage()); - } - - System.out.println(); - - // Remove the scalable target - DeregisterScalableTargetRequest delSTRequest = new DeregisterScalableTargetRequest() - .withServiceNamespace(ns) - .withScalableDimension(tableWCUs) - .withResourceId(resourceID); - - try { - aaClient.deregisterScalableTarget(delSTRequest); - } catch (Exception e) { - System.err.println("Unable to deregister scalable target: "); - System.err.println(e.getMessage()); - } + public static void main(String args[]) { - // Verify that the scalable target was removed - DescribeScalableTargetsRequest dscRequest = new DescribeScalableTargetsRequest() - .withServiceNamespace(ns) - .withScalableDimension(tableWCUs) - .withResourceIds(resourceID); - - try { - DescribeScalableTargetsResult dsaResult = aaClient.describeScalableTargets(dscRequest); - System.out.println("DescribeScalableTargets result: "); - System.out.println(dsaResult); - System.out.println(); - } catch (Exception e) { - System.err.println("Unable to describe scalable target: "); - System.err.println(e.getMessage()); - } + ServiceNamespace ns = ServiceNamespace.Dynamodb; + ScalableDimension tableWCUs = ScalableDimension.DynamodbTableWriteCapacityUnits; + String resourceID = "table/TestTable"; + + // Delete the scaling policy + DeleteScalingPolicyRequest delSPRequest = new DeleteScalingPolicyRequest() + .withServiceNamespace(ns) + .withScalableDimension(tableWCUs) + .withResourceId(resourceID) + .withPolicyName("MyScalingPolicy"); + + try { + aaClient.deleteScalingPolicy(delSPRequest); + } catch (Exception e) { + System.err.println("Unable to delete scaling policy: "); + System.err.println(e.getMessage()); + } + + // Verify that the scaling policy was deleted + DescribeScalingPoliciesRequest descSPRequest = new DescribeScalingPoliciesRequest() + .withServiceNamespace(ns) + .withScalableDimension(tableWCUs) + .withResourceId(resourceID); - } + try { + DescribeScalingPoliciesResult dspResult = aaClient.describeScalingPolicies(descSPRequest); + System.out.println("DescribeScalingPolicies result: "); + System.out.println(dspResult); + } catch (Exception e) { + e.printStackTrace(); + System.err.println("Unable to describe scaling policy: "); + System.err.println(e.getMessage()); + } + + System.out.println(); + + // Remove the scalable target + DeregisterScalableTargetRequest delSTRequest = new DeregisterScalableTargetRequest() + .withServiceNamespace(ns) + .withScalableDimension(tableWCUs) + .withResourceId(resourceID); + + try { + aaClient.deregisterScalableTarget(delSTRequest); + } catch (Exception e) { + System.err.println("Unable to deregister scalable target: "); + System.err.println(e.getMessage()); + } + + // Verify that the scalable target was removed + DescribeScalableTargetsRequest dscRequest = new DescribeScalableTargetsRequest() + .withServiceNamespace(ns) + .withScalableDimension(tableWCUs) + .withResourceIds(resourceID); + + try { + DescribeScalableTargetsResult dsaResult = aaClient.describeScalableTargets(dscRequest); + System.out.println("DescribeScalableTargets result: "); + System.out.println(dsaResult); + System.out.println(); + } catch (Exception e) { + System.err.println("Unable to describe scalable target: "); + System.err.println(e.getMessage()); + } + + } } -// snippet-end:[dynamodb.java.codeexample.DisableDynamoDBAutoscaling] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.DisableDynamoDBAutoscaling] \ No newline at end of file diff --git a/java/example_code/dynamodb/autoscaling/EnableDynamoDBAutoscaling.java b/java/example_code/dynamodb/autoscaling/EnableDynamoDBAutoscaling.java index 6471e39d356..6bf05e5729d 100644 --- a/java/example_code/dynamodb/autoscaling/EnableDynamoDBAutoscaling.java +++ b/java/example_code/dynamodb/autoscaling/EnableDynamoDBAutoscaling.java @@ -1,27 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[dynamodb.java.codeexample.EnableDynamoDBAutoscaling] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ package com.amazonaws.codesamples.autoscaling; import com.amazonaws.services.applicationautoscaling.AWSApplicationAutoScalingClient; @@ -41,91 +21,91 @@ public class EnableDynamoDBAutoscaling { - static AWSApplicationAutoScalingClient aaClient = (AWSApplicationAutoScalingClient) AWSApplicationAutoScalingClientBuilder.standard().build(); - - public static void main(String args[]) { - - ServiceNamespace ns = ServiceNamespace.Dynamodb; - ScalableDimension tableWCUs = ScalableDimension.DynamodbTableWriteCapacityUnits; - String resourceID = "table/TestTable"; - - // Define the scalable target - RegisterScalableTargetRequest rstRequest = new RegisterScalableTargetRequest() - .withServiceNamespace(ns) - .withResourceId(resourceID) - .withScalableDimension(tableWCUs) - .withMinCapacity(5) - .withMaxCapacity(10) - .withRoleARN("SERVICE_ROLE_ARN_GOES_HERE"); - - try { - aaClient.registerScalableTarget(rstRequest); - } catch (Exception e) { - System.err.println("Unable to register scalable target: "); - System.err.println(e.getMessage()); - } + static AWSApplicationAutoScalingClient aaClient = (AWSApplicationAutoScalingClient) AWSApplicationAutoScalingClientBuilder + .standard().build(); - // Verify that the target was created - DescribeScalableTargetsRequest dscRequest = new DescribeScalableTargetsRequest() - .withServiceNamespace(ns) - .withScalableDimension(tableWCUs) - .withResourceIds(resourceID); - try { - DescribeScalableTargetsResult dsaResult = aaClient.describeScalableTargets(dscRequest); - System.out.println("DescribeScalableTargets result: "); - System.out.println(dsaResult); - System.out.println(); - } catch (Exception e) { - System.err.println("Unable to describe scalable target: "); - System.err.println(e.getMessage()); - } - - System.out.println(); - - // Configure a scaling policy - TargetTrackingScalingPolicyConfiguration targetTrackingScalingPolicyConfiguration = - new TargetTrackingScalingPolicyConfiguration() - .withPredefinedMetricSpecification( - new PredefinedMetricSpecification() - .withPredefinedMetricType(MetricType. DynamoDBWriteCapacityUtilization)) - .withTargetValue(50.0) - .withScaleInCooldown(60) - .withScaleOutCooldown(60); - - // Create the scaling policy, based on your configuration - PutScalingPolicyRequest pspRequest = new PutScalingPolicyRequest() - .withServiceNamespace(ns) - .withScalableDimension(tableWCUs) - .withResourceId(resourceID) - .withPolicyName("MyScalingPolicy") - .withPolicyType(PolicyType.TargetTrackingScaling) - .withTargetTrackingScalingPolicyConfiguration(targetTrackingScalingPolicyConfiguration); - - try { - aaClient.putScalingPolicy(pspRequest); - } catch (Exception e) { - System.err.println("Unable to put scaling policy: "); - System.err.println(e.getMessage()); - } + public static void main(String args[]) { - // Verify that the scaling policy was created - DescribeScalingPoliciesRequest dspRequest = new DescribeScalingPoliciesRequest() - .withServiceNamespace(ns) - .withScalableDimension(tableWCUs) - .withResourceId(resourceID); - - try { - DescribeScalingPoliciesResult dspResult = aaClient.describeScalingPolicies(dspRequest); - System.out.println("DescribeScalingPolicies result: "); - System.out.println(dspResult); - } catch (Exception e) { - e.printStackTrace(); - System.err.println("Unable to describe scaling policy: "); - System.err.println(e.getMessage()); - } + ServiceNamespace ns = ServiceNamespace.Dynamodb; + ScalableDimension tableWCUs = ScalableDimension.DynamodbTableWriteCapacityUnits; + String resourceID = "table/TestTable"; + + // Define the scalable target + RegisterScalableTargetRequest rstRequest = new RegisterScalableTargetRequest() + .withServiceNamespace(ns) + .withResourceId(resourceID) + .withScalableDimension(tableWCUs) + .withMinCapacity(5) + .withMaxCapacity(10) + .withRoleARN("SERVICE_ROLE_ARN_GOES_HERE"); + + try { + aaClient.registerScalableTarget(rstRequest); + } catch (Exception e) { + System.err.println("Unable to register scalable target: "); + System.err.println(e.getMessage()); + } + + // Verify that the target was created + DescribeScalableTargetsRequest dscRequest = new DescribeScalableTargetsRequest() + .withServiceNamespace(ns) + .withScalableDimension(tableWCUs) + .withResourceIds(resourceID); + try { + DescribeScalableTargetsResult dsaResult = aaClient.describeScalableTargets(dscRequest); + System.out.println("DescribeScalableTargets result: "); + System.out.println(dsaResult); + System.out.println(); + } catch (Exception e) { + System.err.println("Unable to describe scalable target: "); + System.err.println(e.getMessage()); + } - } + System.out.println(); + + // Configure a scaling policy + TargetTrackingScalingPolicyConfiguration targetTrackingScalingPolicyConfiguration = new TargetTrackingScalingPolicyConfiguration() + .withPredefinedMetricSpecification( + new PredefinedMetricSpecification() + .withPredefinedMetricType(MetricType.DynamoDBWriteCapacityUtilization)) + .withTargetValue(50.0) + .withScaleInCooldown(60) + .withScaleOutCooldown(60); + + // Create the scaling policy, based on your configuration + PutScalingPolicyRequest pspRequest = new PutScalingPolicyRequest() + .withServiceNamespace(ns) + .withScalableDimension(tableWCUs) + .withResourceId(resourceID) + .withPolicyName("MyScalingPolicy") + .withPolicyType(PolicyType.TargetTrackingScaling) + .withTargetTrackingScalingPolicyConfiguration(targetTrackingScalingPolicyConfiguration); + + try { + aaClient.putScalingPolicy(pspRequest); + } catch (Exception e) { + System.err.println("Unable to put scaling policy: "); + System.err.println(e.getMessage()); + } + + // Verify that the scaling policy was created + DescribeScalingPoliciesRequest dspRequest = new DescribeScalingPoliciesRequest() + .withServiceNamespace(ns) + .withScalableDimension(tableWCUs) + .withResourceId(resourceID); + + try { + DescribeScalingPoliciesResult dspResult = aaClient.describeScalingPolicies(dspRequest); + System.out.println("DescribeScalingPolicies result: "); + System.out.println(dspResult); + } catch (Exception e) { + e.printStackTrace(); + System.err.println("Unable to describe scaling policy: "); + System.err.println(e.getMessage()); + } + + } } -// snippet-end:[dynamodb.java.codeexample.EnableDynamoDBAutoscaling] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.EnableDynamoDBAutoscaling] \ No newline at end of file diff --git a/java/example_code/dynamodb/changelicense.sh b/java/example_code/dynamodb/changelicense.sh index 3e9c63fdfcc..8980ac8795e 100644 --- a/java/example_code/dynamodb/changelicense.sh +++ b/java/example_code/dynamodb/changelicense.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 find src -name "*.java" -print0 | xargs -0 \ sed -i -e '/Copyright/,/Licensed under the Apache License, Version 2.0/c\ diff --git a/java/example_code/dynamodb/run_example.sh b/java/example_code/dynamodb/run_example.sh index df9f4830605..39f06099612 100644 --- a/java/example_code/dynamodb/run_example.sh +++ b/java/example_code/dynamodb/run_example.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 if [[ -z $* ]] ; then echo 'Supply the name of one of the example classes as an argument.' echo 'If there are arguments to the class, put them in quotes after the class name.' diff --git a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/CreateTable.java b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/CreateTable.java index 011d7a04c33..823ae7730f2 100644 --- a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/CreateTable.java +++ b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/CreateTable.java @@ -1,26 +1,7 @@ -//snippet-sourcedescription:[CreateTable.java demonstrates how to create a DynamoDB table a single primary key.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-service:[dynamodb] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.dynamodb; + import com.amazonaws.AmazonServiceException; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; @@ -41,17 +22,15 @@ * This code expects that you have AWS credentials set up per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ -public class CreateTable -{ - public static void main(String[] args) - { +public class CreateTable { + public static void main(String[] args) { final String USAGE = "\n" + - "Usage:\n" + - " CreateTable \n\n" + - "Where:\n" + - " table - the table to create.\n\n" + - "Example:\n" + - " CreateTable HelloTable\n"; + "Usage:\n" + + " CreateTable
\n\n" + + "Where:\n" + + " table - the table to create.\n\n" + + "Example:\n" + + " CreateTable HelloTable\n"; if (args.length < 1) { System.out.println(USAGE); @@ -62,16 +41,16 @@ public static void main(String[] args) String table_name = args[0]; System.out.format( - "Creating table \"%s\" with a simple primary key: \"Name\".\n", - table_name); + "Creating table \"%s\" with a simple primary key: \"Name\".\n", + table_name); CreateTableRequest request = new CreateTableRequest() - .withAttributeDefinitions(new AttributeDefinition( - "Name", ScalarAttributeType.S)) - .withKeySchema(new KeySchemaElement("Name", KeyType.HASH)) - .withProvisionedThroughput(new ProvisionedThroughput( - new Long(10), new Long(10))) - .withTableName(table_name); + .withAttributeDefinitions(new AttributeDefinition( + "Name", ScalarAttributeType.S)) + .withKeySchema(new KeySchemaElement("Name", KeyType.HASH)) + .withProvisionedThroughput(new ProvisionedThroughput( + new Long(10), new Long(10))) + .withTableName(table_name); final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient(); diff --git a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/CreateTableCompositeKey.java b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/CreateTableCompositeKey.java index a7df61c7112..64fd0174370 100644 --- a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/CreateTableCompositeKey.java +++ b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/CreateTableCompositeKey.java @@ -1,26 +1,7 @@ -//snippet-sourcedescription:[CreateTableCompositeKey.java demonstrates how to create a DynamoDB table with a composite key.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-service:[dynamodb] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.dynamodb; + import com.amazonaws.AmazonServiceException; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; @@ -41,17 +22,15 @@ * This code expects that you have AWS credentials set up per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ -public class CreateTableCompositeKey -{ - public static void main(String[] args) - { +public class CreateTableCompositeKey { + public static void main(String[] args) { final String USAGE = "\n" + - "Usage:\n" + - " CreateTable
\n\n" + - "Where:\n" + - " table - the table to create.\n\n" + - "Example:\n" + - " CreateTable GreetingsTable\n"; + "Usage:\n" + + " CreateTable
\n\n" + + "Where:\n" + + " table - the table to create.\n\n" + + "Example:\n" + + " CreateTable GreetingsTable\n"; if (args.length < 1) { System.out.println(USAGE); @@ -66,15 +45,15 @@ public static void main(String[] args) System.out.format("* Greeting - sort key\n"); CreateTableRequest request = new CreateTableRequest() - .withAttributeDefinitions( - new AttributeDefinition("Language", ScalarAttributeType.S), - new AttributeDefinition("Greeting", ScalarAttributeType.S)) - .withKeySchema( - new KeySchemaElement("Language", KeyType.HASH), - new KeySchemaElement("Greeting", KeyType.RANGE)) - .withProvisionedThroughput( - new ProvisionedThroughput(new Long(10), new Long(10))) - .withTableName(table_name); + .withAttributeDefinitions( + new AttributeDefinition("Language", ScalarAttributeType.S), + new AttributeDefinition("Greeting", ScalarAttributeType.S)) + .withKeySchema( + new KeySchemaElement("Language", KeyType.HASH), + new KeySchemaElement("Greeting", KeyType.RANGE)) + .withProvisionedThroughput( + new ProvisionedThroughput(new Long(10), new Long(10))) + .withTableName(table_name); final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient(); diff --git a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/DeleteItem.java b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/DeleteItem.java index e9c115ed9ad..98c05b97355 100644 --- a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/DeleteItem.java +++ b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/DeleteItem.java @@ -1,26 +1,7 @@ -//snippet-sourcedescription:[DeleteItem.java demonstrates how to delete an item from a table in DynamoDB.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-service:[dynamodb] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.dynamodb; + import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.model.AttributeValue; @@ -37,21 +18,19 @@ * This code expects that you have AWS credentials set up per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ -public class DeleteItem -{ - public static void main(String[] args) - { +public class DeleteItem { + public static void main(String[] args) { final String USAGE = "\n" + - "Usage:\n" + - " DeleteItem
\n\n" + - "Where:\n" + - " table - the table to delete the item from.\n" + - " name - the item to delete from the table,\n" + - " using the primary key \"Name\"\n\n" + - "Example:\n" + - " DeleteItem HelloTable World\n\n" + - "**Warning** This program will actually delete the item\n" + - " that you specify!\n"; + "Usage:\n" + + " DeleteItem
\n\n" + + "Where:\n" + + " table - the table to delete the item from.\n" + + " name - the item to delete from the table,\n" + + " using the primary key \"Name\"\n\n" + + "Example:\n" + + " DeleteItem HelloTable World\n\n" + + "**Warning** This program will actually delete the item\n" + + " that you specify!\n"; if (args.length < 2) { System.out.println(USAGE); @@ -63,8 +42,7 @@ public static void main(String[] args) System.out.format("Deleting item \"%s\" from %s\n", name, table_name); - HashMap key_to_get = - new HashMap(); + HashMap key_to_get = new HashMap(); key_to_get.put("Name", new AttributeValue(name)); diff --git a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/DeleteTable.java b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/DeleteTable.java index b6cd7628384..86bee9c1e71 100644 --- a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/DeleteTable.java +++ b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/DeleteTable.java @@ -1,26 +1,7 @@ -//snippet-sourcedescription:[DeleteTable.java demonstrates how to delete a DynamoDB table.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-service:[dynamodb] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.dynamodb; + import com.amazonaws.AmazonServiceException; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; @@ -35,19 +16,17 @@ * This code expects that you have AWS credentials set up per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ -public class DeleteTable -{ - public static void main(String[] args) - { +public class DeleteTable { + public static void main(String[] args) { final String USAGE = "\n" + - "Usage:\n" + - " DeleteTable
\n\n" + - "Where:\n" + - " table - the table to delete.\n\n" + - "Example:\n" + - " DeleteTable Greetings\n\n" + - "**Warning** This program will actually delete the table\n" + - " that you specify!\n"; + "Usage:\n" + + " DeleteTable
\n\n" + + "Where:\n" + + " table - the table to delete.\n\n" + + "Example:\n" + + " DeleteTable Greetings\n\n" + + "**Warning** This program will actually delete the table\n" + + " that you specify!\n"; if (args.length < 1) { System.out.println(USAGE); diff --git a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/DescribeTable.java b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/DescribeTable.java index 581b8066134..30f3636d469 100644 --- a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/DescribeTable.java +++ b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/DescribeTable.java @@ -1,26 +1,7 @@ -//snippet-sourcedescription:[DescribeTable.java demonstrates how to get information about (describe) a DynamoDB table.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-service:[dynamodb] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.dynamodb; + import com.amazonaws.AmazonServiceException; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; @@ -37,64 +18,60 @@ * This code expects that you have AWS credentials set up per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ -public class DescribeTable -{ - public static void main(String[] args) - { - final String USAGE = "\n" + - "Usage:\n" + - " DescribeTable
\n\n" + - "Where:\n" + - " table - the table to get information about.\n\n" + - "Example:\n" + - " DescribeTable HelloTable\n"; +public class DescribeTable { + public static void main(String[] args) { + final String USAGE = "\n" + + "Usage:\n" + + " DescribeTable
\n\n" + + "Where:\n" + + " table - the table to get information about.\n\n" + + "Example:\n" + + " DescribeTable HelloTable\n"; - if (args.length < 1) { - System.out.println(USAGE); - System.exit(1); - } + if (args.length < 1) { + System.out.println(USAGE); + System.exit(1); + } - String table_name = args[0]; - System.out.format("Getting description for %s\n\n", table_name); + String table_name = args[0]; + System.out.format("Getting description for %s\n\n", table_name); - final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient(); + final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient(); - try { - TableDescription table_info = - ddb.describeTable(table_name).getTable(); + try { + TableDescription table_info = ddb.describeTable(table_name).getTable(); - if (table_info != null) { - System.out.format("Table name : %s\n", - table_info.getTableName()); - System.out.format("Table ARN : %s\n", - table_info.getTableArn()); - System.out.format("Status : %s\n", - table_info.getTableStatus()); - System.out.format("Item count : %d\n", - table_info.getItemCount().longValue()); - System.out.format("Size (bytes): %d\n", - table_info.getTableSizeBytes().longValue()); + if (table_info != null) { + System.out.format("Table name : %s\n", + table_info.getTableName()); + System.out.format("Table ARN : %s\n", + table_info.getTableArn()); + System.out.format("Status : %s\n", + table_info.getTableStatus()); + System.out.format("Item count : %d\n", + table_info.getItemCount().longValue()); + System.out.format("Size (bytes): %d\n", + table_info.getTableSizeBytes().longValue()); - ProvisionedThroughputDescription throughput_info = - table_info.getProvisionedThroughput(); - System.out.println("Throughput"); - System.out.format(" Read Capacity : %d\n", - throughput_info.getReadCapacityUnits().longValue()); - System.out.format(" Write Capacity: %d\n", - throughput_info.getWriteCapacityUnits().longValue()); + ProvisionedThroughputDescription throughput_info = table_info + .getProvisionedThroughput(); + System.out.println("Throughput"); + System.out.format(" Read Capacity : %d\n", + throughput_info.getReadCapacityUnits().longValue()); + System.out.format(" Write Capacity: %d\n", + throughput_info.getWriteCapacityUnits().longValue()); - List attributes = - table_info.getAttributeDefinitions(); - System.out.println("Attributes"); - for (AttributeDefinition a : attributes) { - System.out.format(" %s (%s)\n", - a.getAttributeName(), a.getAttributeType()); + List attributes = table_info.getAttributeDefinitions(); + System.out.println("Attributes"); + for (AttributeDefinition a : attributes) { + System.out.format(" %s (%s)\n", + a.getAttributeName(), a.getAttributeType()); + } + } + } catch (AmazonServiceException e) { + System.err.println(e.getErrorMessage()); + System.exit(1); } - } - } catch (AmazonServiceException e) { - System.err.println(e.getErrorMessage()); - System.exit(1); + System.out.println("\nDone!"); } - System.out.println("\nDone!"); - } } diff --git a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/DynamoDBScanItems.java b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/DynamoDBScanItems.java index 088c57c1810..6961a5e3c0b 100644 --- a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/DynamoDBScanItems.java +++ b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/DynamoDBScanItems.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Copyright 2018-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * @@ -12,15 +14,6 @@ * specific language governing permissions and limitations under the License. */ -// snippet-sourcedescription:[DynamoDBScanItems demonstrates how to return one or more items and item attributes by accessing every item in a table.] -// snippet-service:[dynamodb] -// snippet-keyword:[Code Sample]] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-01-27] -// snippet-sourceauthor:[AWS-scmacdon] - // snippet-start:[dynamodb.java.dynamoDB_scan.complete] package aws.example.dynamodb; @@ -35,7 +28,6 @@ import java.util.Set; // snippet-end:[dynamodb.java.dynamoDB_scan.import] - public class DynamoDBScanItems { public static void main(String[] args) { @@ -61,13 +53,12 @@ public static void main(String[] args) { for (String key : keys) { - System.out.println ("The key name is "+key +"\n" ); - System.out.println("The value is "+item.get(key).getS()); + System.out.println("The key name is " + key + "\n"); + System.out.println("The value is " + item.get(key).getS()); } } - } catch (AmazonDynamoDBException e) { e.getStackTrace(); } diff --git a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/GetItem.java b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/GetItem.java index 9bc3a7d74f6..6ea24d04153 100644 --- a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/GetItem.java +++ b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/GetItem.java @@ -1,26 +1,7 @@ -//snippet-sourcedescription:[GetItem.java demonstrates how to get an item from a DynamoDB table.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-service:[dynamodb] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.dynamodb; + import com.amazonaws.AmazonServiceException; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; @@ -35,28 +16,27 @@ * * Takes the name of the table and the name of the item to retrieve from it. * - * The primary key searched is "DATABASE_NAME", and the value contained by the field + * The primary key searched is "DATABASE_NAME", and the value contained by the + * field * "Greeting" will be returned. * * This code expects that you have AWS credentials set up per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ -public class GetItem -{ - public static void main(String[] args) - { +public class GetItem { + public static void main(String[] args) { final String USAGE = "\n" + - "Usage:\n" + - " GetItem
[projection_expression]\n\n" + - "Where:\n" + - " table - the table to get an item from.\n" + - " name - the item to get.\n\n" + - "You can add an optional projection expression (a quote-delimited,\n" + - "comma-separated list of attributes to retrieve) to limit the\n" + - "fields returned from the table.\n\n" + - "Example:\n" + - " GetItem HelloTable World\n" + - " GetItem SiteColors text \"default, bold\"\n"; + "Usage:\n" + + " GetItem
[projection_expression]\n\n" + + "Where:\n" + + " table - the table to get an item from.\n" + + " name - the item to get.\n\n" + + "You can add an optional projection expression (a quote-delimited,\n" + + "comma-separated list of attributes to retrieve) to limit the\n" + + "fields returned from the table.\n\n" + + "Example:\n" + + " GetItem HelloTable World\n" + + " GetItem SiteColors text \"default, bold\"\n"; if (args.length < 2) { System.out.println(USAGE); @@ -75,28 +55,26 @@ public static void main(String[] args) System.out.format("Retrieving item \"%s\" from \"%s\"\n", name, table_name); - HashMap key_to_get = - new HashMap(); + HashMap key_to_get = new HashMap(); key_to_get.put("DATABASE_NAME", new AttributeValue(name)); GetItemRequest request = null; if (projection_expression != null) { request = new GetItemRequest() - .withKey(key_to_get) - .withTableName(table_name) - .withProjectionExpression(projection_expression); + .withKey(key_to_get) + .withTableName(table_name) + .withProjectionExpression(projection_expression); } else { request = new GetItemRequest() - .withKey(key_to_get) - .withTableName(table_name); + .withKey(key_to_get) + .withTableName(table_name); } final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient(); try { - Map returned_item = - ddb.getItem(request).getItem(); + Map returned_item = ddb.getItem(request).getItem(); if (returned_item != null) { Set keys = returned_item.keySet(); for (String key : keys) { diff --git a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/ListTables.java b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/ListTables.java index f8ed5266219..a0a29bac96f 100644 --- a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/ListTables.java +++ b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/ListTables.java @@ -1,26 +1,7 @@ -//snippet-sourcedescription:[ListTables.java demonstrates how to list DynamoDB tables for the current AWS account.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-service:[dynamodb] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.dynamodb; + import com.amazonaws.AmazonServiceException; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; @@ -34,10 +15,8 @@ * This code expects that you have AWS credentials set up per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ -public class ListTables -{ - public static void main(String[] args) - { +public class ListTables { + public static void main(String[] args) { System.out.println("Your DynamoDB tables:\n"); final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient(); @@ -47,15 +26,14 @@ public static void main(String[] args) boolean more_tables = true; String last_name = null; - while(more_tables) { + while (more_tables) { try { if (last_name == null) { - request = new ListTablesRequest().withLimit(10); - } - else { - request = new ListTablesRequest() - .withLimit(10) - .withExclusiveStartTableName(last_name); + request = new ListTablesRequest().withLimit(10); + } else { + request = new ListTablesRequest() + .withLimit(10) + .withExclusiveStartTableName(last_name); } ListTablesResult table_list = ddb.listTables(request); diff --git a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/PutItem.java b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/PutItem.java index 09e1bad4bea..c404c0b72d2 100644 --- a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/PutItem.java +++ b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/PutItem.java @@ -1,26 +1,7 @@ -//snippet-sourcedescription:[PutItem.java demonstrates how to put an item in a DynamoDB table.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-service:[dynamodb] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* -Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -This file is 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/ - -This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -CONDITIONS OF ANY KIND, either express or implied. See the License for the -specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.dynamodb; + import com.amazonaws.AmazonServiceException; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; @@ -30,29 +11,27 @@ import java.util.HashMap; /** -* Put an item in a DynamoDB table. -* -* Takes the name of the table, a name (primary key value) and a greeting -* (associated with the key value). -* -* This code expects that you have AWS credentials set up per: -* http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html -*/ -public class PutItem -{ - public static void main(String[] args) - { + * Put an item in a DynamoDB table. + * + * Takes the name of the table, a name (primary key value) and a greeting + * (associated with the key value). + * + * This code expects that you have AWS credentials set up per: + * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html + */ +public class PutItem { + public static void main(String[] args) { final String USAGE = "\n" + - "Usage:\n" + - " PutItem
[field=value ...]\n\n" + - "Where:\n" + - " table - the table to put the item in.\n" + - " name - a name to add to the table. If the name already\n" + - " exists, its entry will be updated.\n" + - "Additional fields can be added by appending them to the end of the\n" + - "input.\n\n" + - "Example:\n" + - " PutItem Cellists Pau Language=ca Born=1876\n"; + "Usage:\n" + + " PutItem
[field=value ...]\n\n" + + "Where:\n" + + " table - the table to put the item in.\n" + + " name - a name to add to the table. If the name already\n" + + " exists, its entry will be updated.\n" + + "Additional fields can be added by appending them to the end of the\n" + + "input.\n\n" + + "Example:\n" + + " PutItem Cellists Pau Language=ca Born=1876\n"; if (args.length < 2) { System.out.println(USAGE); @@ -83,8 +62,7 @@ public static void main(String[] args) } } - HashMap item_values = - new HashMap(); + HashMap item_values = new HashMap(); item_values.put("Name", new AttributeValue(name)); diff --git a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/Query.java b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/Query.java index e04584fa737..7b9889a2d19 100644 --- a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/Query.java +++ b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/Query.java @@ -1,26 +1,7 @@ -//snippet-sourcedescription:[Query.java demonstrates how to query a DynamoDB table.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-service:[dynamodb] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.dynamodb; + import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.model.AttributeValue; @@ -42,11 +23,9 @@ * This code expects that you have AWS credentials set up per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ -public class Query -{ - public static void main(String[] args) - { - final String USAGE = "\n" + +public class Query { + public static void main(String[] args) { + final String USAGE = "\n" + "Usage:\n" + " Query
\n\n" + "Where:\n" + @@ -71,25 +50,23 @@ public static void main(String[] args) final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient(); - //set up an alias for the partition key name in case it's a reserved word - HashMap attrNameAlias = - new HashMap(); + // set up an alias for the partition key name in case it's a reserved word + HashMap attrNameAlias = new HashMap(); attrNameAlias.put(partition_alias, partition_key_name); - //set up mapping of the partition name with the value - HashMap attrValues = - new HashMap(); - attrValues.put(":"+partition_key_name, new AttributeValue().withS(partition_key_val)); + // set up mapping of the partition name with the value + HashMap attrValues = new HashMap(); + attrValues.put(":" + partition_key_name, new AttributeValue().withS(partition_key_val)); QueryRequest queryReq = new QueryRequest() - .withTableName(table_name) - .withKeyConditionExpression(partition_alias + " = :" + partition_key_name) - .withExpressionAttributeNames(attrNameAlias) - .withExpressionAttributeValues(attrValues); + .withTableName(table_name) + .withKeyConditionExpression(partition_alias + " = :" + partition_key_name) + .withExpressionAttributeNames(attrNameAlias) + .withExpressionAttributeValues(attrValues); try { - QueryResult response = ddb.query(queryReq); - System.out.println(response.getCount()); + QueryResult response = ddb.query(queryReq); + System.out.println(response.getCount()); } catch (AmazonDynamoDBException e) { System.err.println(e.getErrorMessage()); System.exit(1); diff --git a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/UpdateItem.java b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/UpdateItem.java index a79925b80e5..8550186d4d2 100644 --- a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/UpdateItem.java +++ b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/UpdateItem.java @@ -1,26 +1,7 @@ -//snippet-sourcedescription:[UpdateItem.java demonstrates how to update an item in a DynamoDB table.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-service:[dynamodb] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.dynamodb; + import com.amazonaws.AmazonServiceException; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; @@ -43,22 +24,20 @@ * This code expects that you have AWS credentials set up per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ -public class UpdateItem -{ - public static void main(String[] args) - { +public class UpdateItem { + public static void main(String[] args) { final String USAGE = "\n" + - "Usage:\n" + - " UpdateItem
\n\n" + - "Where:\n" + - " table - the table to put the item in.\n" + - " name - a name to update in the table. The name must exist,\n" + - " or an error will result.\n" + - "Additional fields can be specified by appending them to the end of the\n" + - "input.\n\n" + - "Examples:\n" + - " UpdateItem SiteColors text default=000000 bold=b22222\n" + - " UpdateItem SiteColors background default=eeeeee code=d3d3d3\n\n"; + "Usage:\n" + + " UpdateItem
\n\n" + + "Where:\n" + + " table - the table to put the item in.\n" + + " name - a name to update in the table. The name must exist,\n" + + " or an error will result.\n" + + "Additional fields can be specified by appending them to the end of the\n" + + "input.\n\n" + + "Examples:\n" + + " UpdateItem SiteColors text default=000000 bold=b22222\n" + + " UpdateItem SiteColors background default=eeeeee code=d3d3d3\n\n"; if (args.length < 3) { System.out.println(USAGE); @@ -89,17 +68,15 @@ public static void main(String[] args) } } - HashMap item_key = - new HashMap(); + HashMap item_key = new HashMap(); item_key.put("Name", new AttributeValue(name)); - HashMap updated_values = - new HashMap(); + HashMap updated_values = new HashMap(); for (String[] field : extra_fields) { updated_values.put(field[0], new AttributeValueUpdate( - new AttributeValue(field[1]), AttributeAction.PUT)); + new AttributeValue(field[1]), AttributeAction.PUT)); } final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient(); diff --git a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/UpdateTable.java b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/UpdateTable.java index 8318bd57151..ff8b96f4ee2 100644 --- a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/UpdateTable.java +++ b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/UpdateTable.java @@ -1,26 +1,7 @@ -//snippet-sourcedescription:[UpdateTable.java demonstrates how to update a DynamoDB table (change provisioned throughput).] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-service:[dynamodb] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.dynamodb; + import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; @@ -35,19 +16,17 @@ * This code expects that you have AWS credentials set up per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ -public class UpdateTable -{ - public static void main(String[] args) - { +public class UpdateTable { + public static void main(String[] args) { final String USAGE = "\n" + - "Usage:\n" + - " UpdateTable
\n\n" + - "Where:\n" + - " table - the table to put the item in.\n" + - " read - the new read capacity of the table.\n" + - " write - the new write capacity of the table.\n\n" + - "Example:\n" + - " UpdateTable HelloTable 16 10\n"; + "Usage:\n" + + " UpdateTable
\n\n" + + "Where:\n" + + " table - the table to put the item in.\n" + + " read - the new read capacity of the table.\n" + + " write - the new write capacity of the table.\n\n" + + "Example:\n" + + " UpdateTable HelloTable 16 10\n"; if (args.length < 3) { System.out.println(USAGE); @@ -65,7 +44,7 @@ public static void main(String[] args) System.out.format("Write capacity : %d\n", write_capacity); ProvisionedThroughput table_throughput = new ProvisionedThroughput( - read_capacity, write_capacity); + read_capacity, write_capacity); final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient(); diff --git a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/UseDynamoMapping.java b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/UseDynamoMapping.java index 565275e3a58..b8c61fd3cb3 100644 --- a/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/UseDynamoMapping.java +++ b/java/example_code/dynamodb/src/main/java/aws/example/dynamodb/UseDynamoMapping.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. This file is licensed under the Apache License, Version 2.0 (the "License"). @@ -9,16 +11,6 @@ specific language governing permissions and limitations under the License. */ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[UseDynamoMapping.java demonstrates how to use the DynamoDB mapping functionality] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-12-16] -// snippet-sourceauthor:[scmacdon-AWS] - // snippet-start:[dynamodb.java.dynamoDB_mapping.complete] package aws.example.dynamodb; @@ -54,17 +46,16 @@ public static void main(String[] args) { String albumTitle = args[2]; String awards = args[3]; - // snippet-start:[dynamodb.java.dynamoDB_mapping.main] AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build(); MusicItems items = new MusicItems(); - try{ + try { // Add new content to the Music table items.setArtist(artist); items.setSongTitle(songTitle); items.setAlbumTitle(albumTitle); - items.setAwards(Integer.parseInt(awards)); //convert to an int + items.setAwards(Integer.parseInt(awards)); // convert to an int // Save the item DynamoDBMapper mapper = new DynamoDBMapper(client); @@ -92,16 +83,16 @@ public static void main(String[] args) { } } - @DynamoDBTable(tableName="Music") + @DynamoDBTable(tableName = "Music") public static class MusicItems { - //Set up Data Members that correspond to columns in the Music table + // Set up Data Members that correspond to columns in the Music table private String artist; private String songTitle; private String albumTitle; private int awards; - @DynamoDBHashKey(attributeName="Artist") + @DynamoDBHashKey(attributeName = "Artist") public String getArtist() { return this.artist; } @@ -110,7 +101,7 @@ public void setArtist(String artist) { this.artist = artist; } - @DynamoDBRangeKey(attributeName="SongTitle") + @DynamoDBRangeKey(attributeName = "SongTitle") public String getSongTitle() { return this.songTitle; } @@ -119,7 +110,7 @@ public void setSongTitle(String title) { this.songTitle = title; } - @DynamoDBAttribute(attributeName="AlbumTitle") + @DynamoDBAttribute(attributeName = "AlbumTitle") public String getAlbumTitle() { return this.albumTitle; } @@ -128,7 +119,7 @@ public void setAlbumTitle(String title) { this.albumTitle = title; } - @DynamoDBAttribute(attributeName="Awards") + @DynamoDBAttribute(attributeName = "Awards") public int getAwards() { return this.awards; } diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/CreateTablesLoadData.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/CreateTablesLoadData.java index ab1cd0e6dd9..ffa08f1b947 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/CreateTablesLoadData.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/CreateTablesLoadData.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.CreateTablesLoadData] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.CreateTablesLoadData] package com.amazonaws.codesamples; @@ -68,9 +47,9 @@ public static void main(String[] args) throws Exception { deleteTable(threadTableName); deleteTable(replyTableName); - // Parameter1: table name - // Parameter2: reads per second - // Parameter3: writes per second + // Parameter1: table name + // Parameter2: reads per second + // Parameter3: writes per second // Parameter4/5: partition key and data type // Parameter6/7: sort key and data type (if applicable) @@ -84,8 +63,7 @@ public static void main(String[] args) throws Exception { loadSampleThreads(threadTableName); loadSampleReplies(replyTableName); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Program failed:"); System.err.println(e.getMessage()); } @@ -100,21 +78,20 @@ private static void deleteTable(String tableName) { System.out.println("Waiting for " + tableName + " to be deleted...this may take a while..."); table.waitForDelete(); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("DeleteTable request failed for " + tableName); System.err.println(e.getMessage()); } } private static void createTable(String tableName, long readCapacityUnits, long writeCapacityUnits, - String partitionKeyName, String partitionKeyType) { + String partitionKeyName, String partitionKeyType) { createTable(tableName, readCapacityUnits, writeCapacityUnits, partitionKeyName, partitionKeyType, null, null); } private static void createTable(String tableName, long readCapacityUnits, long writeCapacityUnits, - String partitionKeyName, String partitionKeyType, String sortKeyName, String sortKeyType) { + String partitionKeyName, String partitionKeyType, String sortKeyName, String sortKeyType) { try { @@ -124,32 +101,34 @@ private static void createTable(String tableName, long readCapacityUnits, long w ArrayList attributeDefinitions = new ArrayList(); attributeDefinitions - .add(new AttributeDefinition().withAttributeName(partitionKeyName).withAttributeType(partitionKeyType)); + .add(new AttributeDefinition().withAttributeName(partitionKeyName) + .withAttributeType(partitionKeyType)); if (sortKeyName != null) { keySchema.add(new KeySchemaElement().withAttributeName(sortKeyName).withKeyType(KeyType.RANGE)); // Sort // key attributeDefinitions - .add(new AttributeDefinition().withAttributeName(sortKeyName).withAttributeType(sortKeyType)); + .add(new AttributeDefinition().withAttributeName(sortKeyName).withAttributeType(sortKeyType)); } CreateTableRequest request = new CreateTableRequest().withTableName(tableName).withKeySchema(keySchema) - .withProvisionedThroughput(new ProvisionedThroughput().withReadCapacityUnits(readCapacityUnits) - .withWriteCapacityUnits(writeCapacityUnits)); + .withProvisionedThroughput(new ProvisionedThroughput().withReadCapacityUnits(readCapacityUnits) + .withWriteCapacityUnits(writeCapacityUnits)); // If this is the Reply table, define a local secondary index if (replyTableName.equals(tableName)) { attributeDefinitions - .add(new AttributeDefinition().withAttributeName("PostedBy").withAttributeType("S")); + .add(new AttributeDefinition().withAttributeName("PostedBy").withAttributeType("S")); ArrayList localSecondaryIndexes = new ArrayList(); localSecondaryIndexes.add(new LocalSecondaryIndex().withIndexName("PostedBy-Index") - .withKeySchema(new KeySchemaElement().withAttributeName(partitionKeyName).withKeyType(KeyType.HASH), // Partition - // key - new KeySchemaElement().withAttributeName("PostedBy").withKeyType(KeyType.RANGE)) // Sort - // key - .withProjection(new Projection().withProjectionType(ProjectionType.KEYS_ONLY))); + .withKeySchema( + new KeySchemaElement().withAttributeName(partitionKeyName).withKeyType(KeyType.HASH), // Partition + // key + new KeySchemaElement().withAttributeName("PostedBy").withKeyType(KeyType.RANGE)) // Sort + // key + .withProjection(new Projection().withProjectionType(ProjectionType.KEYS_ONLY))); request.setLocalSecondaryIndexes(localSecondaryIndexes); } @@ -161,8 +140,7 @@ private static void createTable(String tableName, long readCapacityUnits, long w System.out.println("Waiting for " + tableName + " to be created...this may take a while..."); table.waitForActive(); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("CreateTable request failed for " + tableName); System.err.println(e.getMessage()); } @@ -177,69 +155,68 @@ private static void loadSampleProducts(String tableName) { System.out.println("Adding data to " + tableName); Item item = new Item().withPrimaryKey("Id", 101).withString("Title", "Book 101 Title") - .withString("ISBN", "111-1111111111") - .withStringSet("Authors", new HashSet(Arrays.asList("Author1"))).withNumber("Price", 2) - .withString("Dimensions", "8.5 x 11.0 x 0.5").withNumber("PageCount", 500) - .withBoolean("InPublication", true).withString("ProductCategory", "Book"); + .withString("ISBN", "111-1111111111") + .withStringSet("Authors", new HashSet(Arrays.asList("Author1"))).withNumber("Price", 2) + .withString("Dimensions", "8.5 x 11.0 x 0.5").withNumber("PageCount", 500) + .withBoolean("InPublication", true).withString("ProductCategory", "Book"); table.putItem(item); item = new Item().withPrimaryKey("Id", 102).withString("Title", "Book 102 Title") - .withString("ISBN", "222-2222222222") - .withStringSet("Authors", new HashSet(Arrays.asList("Author1", "Author2"))) - .withNumber("Price", 20).withString("Dimensions", "8.5 x 11.0 x 0.8").withNumber("PageCount", 600) - .withBoolean("InPublication", true).withString("ProductCategory", "Book"); + .withString("ISBN", "222-2222222222") + .withStringSet("Authors", new HashSet(Arrays.asList("Author1", "Author2"))) + .withNumber("Price", 20).withString("Dimensions", "8.5 x 11.0 x 0.8").withNumber("PageCount", 600) + .withBoolean("InPublication", true).withString("ProductCategory", "Book"); table.putItem(item); item = new Item().withPrimaryKey("Id", 103).withString("Title", "Book 103 Title") - .withString("ISBN", "333-3333333333") - .withStringSet("Authors", new HashSet(Arrays.asList("Author1", "Author2"))) - // Intentional. Later we'll run Scan to find price error. Find - // items > 1000 in price. - .withNumber("Price", 2000).withString("Dimensions", "8.5 x 11.0 x 1.5").withNumber("PageCount", 600) - .withBoolean("InPublication", false).withString("ProductCategory", "Book"); + .withString("ISBN", "333-3333333333") + .withStringSet("Authors", new HashSet(Arrays.asList("Author1", "Author2"))) + // Intentional. Later we'll run Scan to find price error. Find + // items > 1000 in price. + .withNumber("Price", 2000).withString("Dimensions", "8.5 x 11.0 x 1.5").withNumber("PageCount", 600) + .withBoolean("InPublication", false).withString("ProductCategory", "Book"); table.putItem(item); // Add bikes. item = new Item().withPrimaryKey("Id", 201).withString("Title", "18-Bike-201") - // Size, followed by some title. - .withString("Description", "201 Description").withString("BicycleType", "Road") - .withString("Brand", "Mountain A") - // Trek, Specialized. - .withNumber("Price", 100).withStringSet("Color", new HashSet(Arrays.asList("Red", "Black"))) - .withString("ProductCategory", "Bicycle"); + // Size, followed by some title. + .withString("Description", "201 Description").withString("BicycleType", "Road") + .withString("Brand", "Mountain A") + // Trek, Specialized. + .withNumber("Price", 100).withStringSet("Color", new HashSet(Arrays.asList("Red", "Black"))) + .withString("ProductCategory", "Bicycle"); table.putItem(item); item = new Item().withPrimaryKey("Id", 202).withString("Title", "21-Bike-202") - .withString("Description", "202 Description").withString("BicycleType", "Road") - .withString("Brand", "Brand-Company A").withNumber("Price", 200) - .withStringSet("Color", new HashSet(Arrays.asList("Green", "Black"))) - .withString("ProductCategory", "Bicycle"); + .withString("Description", "202 Description").withString("BicycleType", "Road") + .withString("Brand", "Brand-Company A").withNumber("Price", 200) + .withStringSet("Color", new HashSet(Arrays.asList("Green", "Black"))) + .withString("ProductCategory", "Bicycle"); table.putItem(item); item = new Item().withPrimaryKey("Id", 203).withString("Title", "19-Bike-203") - .withString("Description", "203 Description").withString("BicycleType", "Road") - .withString("Brand", "Brand-Company B").withNumber("Price", 300) - .withStringSet("Color", new HashSet(Arrays.asList("Red", "Green", "Black"))) - .withString("ProductCategory", "Bicycle"); + .withString("Description", "203 Description").withString("BicycleType", "Road") + .withString("Brand", "Brand-Company B").withNumber("Price", 300) + .withStringSet("Color", new HashSet(Arrays.asList("Red", "Green", "Black"))) + .withString("ProductCategory", "Bicycle"); table.putItem(item); item = new Item().withPrimaryKey("Id", 204).withString("Title", "18-Bike-204") - .withString("Description", "204 Description").withString("BicycleType", "Mountain") - .withString("Brand", "Brand-Company B").withNumber("Price", 400) - .withStringSet("Color", new HashSet(Arrays.asList("Red"))) - .withString("ProductCategory", "Bicycle"); + .withString("Description", "204 Description").withString("BicycleType", "Mountain") + .withString("Brand", "Brand-Company B").withNumber("Price", 400) + .withStringSet("Color", new HashSet(Arrays.asList("Red"))) + .withString("ProductCategory", "Bicycle"); table.putItem(item); item = new Item().withPrimaryKey("Id", 205).withString("Title", "20-Bike-205") - .withString("Description", "205 Description").withString("BicycleType", "Hybrid") - .withString("Brand", "Brand-Company C").withNumber("Price", 500) - .withStringSet("Color", new HashSet(Arrays.asList("Red", "Black"))) - .withString("ProductCategory", "Bicycle"); + .withString("Description", "205 Description").withString("BicycleType", "Hybrid") + .withString("Brand", "Brand-Company C").withNumber("Price", 500) + .withStringSet("Color", new HashSet(Arrays.asList("Red", "Black"))) + .withString("ProductCategory", "Bicycle"); table.putItem(item); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Failed to create item in " + tableName); System.err.println(e.getMessage()); } @@ -255,16 +232,15 @@ private static void loadSampleForums(String tableName) { System.out.println("Adding data to " + tableName); Item item = new Item().withPrimaryKey("Name", "Amazon DynamoDB") - .withString("Category", "Amazon Web Services").withNumber("Threads", 2).withNumber("Messages", 4) - .withNumber("Views", 1000); + .withString("Category", "Amazon Web Services").withNumber("Threads", 2).withNumber("Messages", 4) + .withNumber("Views", 1000); table.putItem(item); item = new Item().withPrimaryKey("Name", "Amazon S3").withString("Category", "Amazon Web Services") - .withNumber("Threads", 0); + .withNumber("Threads", 0); table.putItem(item); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Failed to create item in " + tableName); System.err.println(e.getMessage()); } @@ -298,28 +274,27 @@ private static void loadSampleThreads(String tableName) { System.out.println("Adding data to " + tableName); Item item = new Item().withPrimaryKey("ForumName", "Amazon DynamoDB") - .withString("Subject", "DynamoDB Thread 1").withString("Message", "DynamoDB thread 1 message") - .withString("LastPostedBy", "User A").withString("LastPostedDateTime", dateFormatter.format(date2)) - .withNumber("Views", 0).withNumber("Replies", 0).withNumber("Answered", 0) - .withStringSet("Tags", new HashSet(Arrays.asList("index", "primarykey", "table"))); + .withString("Subject", "DynamoDB Thread 1").withString("Message", "DynamoDB thread 1 message") + .withString("LastPostedBy", "User A").withString("LastPostedDateTime", dateFormatter.format(date2)) + .withNumber("Views", 0).withNumber("Replies", 0).withNumber("Answered", 0) + .withStringSet("Tags", new HashSet(Arrays.asList("index", "primarykey", "table"))); table.putItem(item); item = new Item().withPrimaryKey("ForumName", "Amazon DynamoDB").withString("Subject", "DynamoDB Thread 2") - .withString("Message", "DynamoDB thread 2 message").withString("LastPostedBy", "User A") - .withString("LastPostedDateTime", dateFormatter.format(date3)).withNumber("Views", 0) - .withNumber("Replies", 0).withNumber("Answered", 0) - .withStringSet("Tags", new HashSet(Arrays.asList("index", "partitionkey", "sortkey"))); + .withString("Message", "DynamoDB thread 2 message").withString("LastPostedBy", "User A") + .withString("LastPostedDateTime", dateFormatter.format(date3)).withNumber("Views", 0) + .withNumber("Replies", 0).withNumber("Answered", 0) + .withStringSet("Tags", new HashSet(Arrays.asList("index", "partitionkey", "sortkey"))); table.putItem(item); item = new Item().withPrimaryKey("ForumName", "Amazon S3").withString("Subject", "S3 Thread 1") - .withString("Message", "S3 Thread 3 message").withString("LastPostedBy", "User A") - .withString("LastPostedDateTime", dateFormatter.format(date1)).withNumber("Views", 0) - .withNumber("Replies", 0).withNumber("Answered", 0) - .withStringSet("Tags", new HashSet(Arrays.asList("largeobjects", "multipart upload"))); + .withString("Message", "S3 Thread 3 message").withString("LastPostedBy", "User A") + .withString("LastPostedDateTime", dateFormatter.format(date1)).withNumber("Views", 0) + .withNumber("Replies", 0).withNumber("Answered", 0) + .withStringSet("Tags", new HashSet(Arrays.asList("largeobjects", "multipart upload"))); table.putItem(item); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Failed to create item in " + tableName); System.err.println(e.getMessage()); } @@ -358,27 +333,26 @@ private static void loadSampleReplies(String tableName) { // Add threads. Item item = new Item().withPrimaryKey("Id", "Amazon DynamoDB#DynamoDB Thread 1") - .withString("ReplyDateTime", (dateFormatter.format(date3))) - .withString("Message", "DynamoDB Thread 1 Reply 1 text").withString("PostedBy", "User A"); + .withString("ReplyDateTime", (dateFormatter.format(date3))) + .withString("Message", "DynamoDB Thread 1 Reply 1 text").withString("PostedBy", "User A"); table.putItem(item); item = new Item().withPrimaryKey("Id", "Amazon DynamoDB#DynamoDB Thread 1") - .withString("ReplyDateTime", dateFormatter.format(date2)) - .withString("Message", "DynamoDB Thread 1 Reply 2 text").withString("PostedBy", "User B"); + .withString("ReplyDateTime", dateFormatter.format(date2)) + .withString("Message", "DynamoDB Thread 1 Reply 2 text").withString("PostedBy", "User B"); table.putItem(item); item = new Item().withPrimaryKey("Id", "Amazon DynamoDB#DynamoDB Thread 2") - .withString("ReplyDateTime", dateFormatter.format(date1)) - .withString("Message", "DynamoDB Thread 2 Reply 1 text").withString("PostedBy", "User A"); + .withString("ReplyDateTime", dateFormatter.format(date1)) + .withString("Message", "DynamoDB Thread 2 Reply 1 text").withString("PostedBy", "User A"); table.putItem(item); item = new Item().withPrimaryKey("Id", "Amazon DynamoDB#DynamoDB Thread 2") - .withString("ReplyDateTime", dateFormatter.format(date0)) - .withString("Message", "DynamoDB Thread 2 Reply 2 text").withString("PostedBy", "User A"); + .withString("ReplyDateTime", dateFormatter.format(date0)) + .withString("Message", "DynamoDB Thread 2 Reply 2 text").withString("PostedBy", "User A"); table.putItem(item); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Failed to create item in " + tableName); System.err.println(e.getMessage()); @@ -387,4 +361,4 @@ private static void loadSampleReplies(String tableName) { } -// snippet-end:[dynamodb.java.codeexample.CreateTablesLoadData] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.CreateTablesLoadData] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/SampleDataLoad.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/SampleDataLoad.java index a170fe31638..74ff0ccab55 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/SampleDataLoad.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/SampleDataLoad.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.SampleDataLoad] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.SampleDataLoad] package com.amazonaws.codesamples; @@ -41,247 +20,267 @@ public class SampleDataLoad { - static AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build(); - static DynamoDB dynamoDB = new DynamoDB(client); + static AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build(); + static DynamoDB dynamoDB = new DynamoDB(client); - static SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - static String productCatalogTableName = "ProductCatalog"; - static String forumTableName = "Forum"; - static String threadTableName = "Thread"; - static String replyTableName = "Reply"; + static SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + static String productCatalogTableName = "ProductCatalog"; + static String forumTableName = "Forum"; + static String threadTableName = "Thread"; + static String replyTableName = "Reply"; - public static void main(String[] args) throws Exception { + public static void main(String[] args) throws Exception { - try { + try { - loadSampleProducts(productCatalogTableName); - loadSampleForums(forumTableName); - loadSampleThreads(threadTableName); - loadSampleReplies(replyTableName); + loadSampleProducts(productCatalogTableName); + loadSampleForums(forumTableName); + loadSampleThreads(threadTableName); + loadSampleReplies(replyTableName); + } catch (AmazonServiceException ase) { + System.err.println("Data load script failed."); + } } - catch (AmazonServiceException ase) { - System.err.println("Data load script failed."); - } - } - - private static void loadSampleProducts(String tableName) { - - Table table = dynamoDB.getTable(tableName); - - try { - - System.out.println("Adding data to " + tableName); - - Item item = new Item().withPrimaryKey("Id", 101).withString("Title", "Book 101 Title") - .withString("ISBN", "111-1111111111") - .withStringSet("Authors", new HashSet(Arrays.asList("Author1"))).withNumber("Price", 2) - .withString("Dimensions", "8.5 x 11.0 x 0.5").withNumber("PageCount", 500) - .withBoolean("InPublication", true).withString("ProductCategory", "Book"); - table.putItem(item); - - item = new Item().withPrimaryKey("Id", 102).withString("Title", "Book 102 Title") - .withString("ISBN", "222-2222222222") - .withStringSet("Authors", new HashSet(Arrays.asList("Author1", "Author2"))) - .withNumber("Price", 20).withString("Dimensions", "8.5 x 11.0 x 0.8").withNumber("PageCount", 600) - .withBoolean("InPublication", true).withString("ProductCategory", "Book"); - table.putItem(item); - - item = new Item().withPrimaryKey("Id", 103).withString("Title", "Book 103 Title") - .withString("ISBN", "333-3333333333") - .withStringSet("Authors", new HashSet(Arrays.asList("Author1", "Author2"))) - // Intentional. Later we'll run Scan to find price error. Find - // items > 1000 in price. - .withNumber("Price", 2000).withString("Dimensions", "8.5 x 11.0 x 1.5").withNumber("PageCount", 600) - .withBoolean("InPublication", false).withString("ProductCategory", "Book"); - table.putItem(item); - - // Add bikes. - - item = new Item().withPrimaryKey("Id", 201).withString("Title", "18-Bike-201") - // Size, followed by some title. - .withString("Description", "201 Description").withString("BicycleType", "Road") - .withString("Brand", "Mountain A") - // Trek, Specialized. - .withNumber("Price", 100).withStringSet("Color", new HashSet(Arrays.asList("Red", "Black"))) - .withString("ProductCategory", "Bicycle"); - table.putItem(item); - - item = new Item().withPrimaryKey("Id", 202).withString("Title", "21-Bike-202") - .withString("Description", "202 Description").withString("BicycleType", "Road") - .withString("Brand", "Brand-Company A").withNumber("Price", 200) - .withStringSet("Color", new HashSet(Arrays.asList("Green", "Black"))) - .withString("ProductCategory", "Bicycle"); - table.putItem(item); - - item = new Item().withPrimaryKey("Id", 203).withString("Title", "19-Bike-203") - .withString("Description", "203 Description").withString("BicycleType", "Road") - .withString("Brand", "Brand-Company B").withNumber("Price", 300) - .withStringSet("Color", new HashSet(Arrays.asList("Red", "Green", "Black"))) - .withString("ProductCategory", "Bicycle"); - table.putItem(item); - - item = new Item().withPrimaryKey("Id", 204).withString("Title", "18-Bike-204") - .withString("Description", "204 Description").withString("BicycleType", "Mountain") - .withString("Brand", "Brand-Company B").withNumber("Price", 400) - .withStringSet("Color", new HashSet(Arrays.asList("Red"))) - .withString("ProductCategory", "Bicycle"); - table.putItem(item); - - item = new Item().withPrimaryKey("Id", 205).withString("Title", "20-Bike-205") - .withString("Description", "205 Description").withString("BicycleType", "Hybrid") - .withString("Brand", "Brand-Company C").withNumber("Price", 500) - .withStringSet("Color", new HashSet(Arrays.asList("Red", "Black"))) - .withString("ProductCategory", "Bicycle"); - table.putItem(item); - } - catch (Exception e) { - System.err.println("Failed to create item in " + tableName); - System.err.println(e.getMessage()); - } + private static void loadSampleProducts(String tableName) { + + Table table = dynamoDB.getTable(tableName); + + try { + + System.out.println("Adding data to " + tableName); + + Item item = new Item().withPrimaryKey("Id", 101).withString("Title", "Book 101 Title") + .withString("ISBN", "111-1111111111") + .withStringSet("Authors", new HashSet(Arrays.asList("Author1"))) + .withNumber("Price", 2) + .withString("Dimensions", "8.5 x 11.0 x 0.5").withNumber("PageCount", 500) + .withBoolean("InPublication", true).withString("ProductCategory", "Book"); + table.putItem(item); + + item = new Item().withPrimaryKey("Id", 102).withString("Title", "Book 102 Title") + .withString("ISBN", "222-2222222222") + .withStringSet("Authors", + new HashSet(Arrays.asList("Author1", "Author2"))) + .withNumber("Price", 20).withString("Dimensions", "8.5 x 11.0 x 0.8") + .withNumber("PageCount", 600) + .withBoolean("InPublication", true).withString("ProductCategory", "Book"); + table.putItem(item); + + item = new Item().withPrimaryKey("Id", 103).withString("Title", "Book 103 Title") + .withString("ISBN", "333-3333333333") + .withStringSet("Authors", + new HashSet(Arrays.asList("Author1", "Author2"))) + // Intentional. Later we'll run Scan to find price error. Find + // items > 1000 in price. + .withNumber("Price", 2000).withString("Dimensions", "8.5 x 11.0 x 1.5") + .withNumber("PageCount", 600) + .withBoolean("InPublication", false).withString("ProductCategory", "Book"); + table.putItem(item); + + // Add bikes. + + item = new Item().withPrimaryKey("Id", 201).withString("Title", "18-Bike-201") + // Size, followed by some title. + .withString("Description", "201 Description").withString("BicycleType", "Road") + .withString("Brand", "Mountain A") + // Trek, Specialized. + .withNumber("Price", 100) + .withStringSet("Color", new HashSet(Arrays.asList("Red", "Black"))) + .withString("ProductCategory", "Bicycle"); + table.putItem(item); + + item = new Item().withPrimaryKey("Id", 202).withString("Title", "21-Bike-202") + .withString("Description", "202 Description").withString("BicycleType", "Road") + .withString("Brand", "Brand-Company A").withNumber("Price", 200) + .withStringSet("Color", new HashSet(Arrays.asList("Green", "Black"))) + .withString("ProductCategory", "Bicycle"); + table.putItem(item); + + item = new Item().withPrimaryKey("Id", 203).withString("Title", "19-Bike-203") + .withString("Description", "203 Description").withString("BicycleType", "Road") + .withString("Brand", "Brand-Company B").withNumber("Price", 300) + .withStringSet("Color", + new HashSet(Arrays.asList("Red", "Green", "Black"))) + .withString("ProductCategory", "Bicycle"); + table.putItem(item); + + item = new Item().withPrimaryKey("Id", 204).withString("Title", "18-Bike-204") + .withString("Description", "204 Description") + .withString("BicycleType", "Mountain") + .withString("Brand", "Brand-Company B").withNumber("Price", 400) + .withStringSet("Color", new HashSet(Arrays.asList("Red"))) + .withString("ProductCategory", "Bicycle"); + table.putItem(item); + + item = new Item().withPrimaryKey("Id", 205).withString("Title", "20-Bike-205") + .withString("Description", "205 Description") + .withString("BicycleType", "Hybrid") + .withString("Brand", "Brand-Company C").withNumber("Price", 500) + .withStringSet("Color", new HashSet(Arrays.asList("Red", "Black"))) + .withString("ProductCategory", "Bicycle"); + table.putItem(item); + + } catch (Exception e) { + System.err.println("Failed to create item in " + tableName); + System.err.println(e.getMessage()); + } - } + } - private static void loadSampleForums(String tableName) { + private static void loadSampleForums(String tableName) { - Table table = dynamoDB.getTable(tableName); + Table table = dynamoDB.getTable(tableName); - try { + try { - System.out.println("Adding data to " + tableName); + System.out.println("Adding data to " + tableName); - Item item = new Item().withPrimaryKey("Name", "Amazon DynamoDB") - .withString("Category", "Amazon Web Services").withNumber("Threads", 2).withNumber("Messages", 4) - .withNumber("Views", 1000); - table.putItem(item); + Item item = new Item().withPrimaryKey("Name", "Amazon DynamoDB") + .withString("Category", "Amazon Web Services").withNumber("Threads", 2) + .withNumber("Messages", 4) + .withNumber("Views", 1000); + table.putItem(item); - item = new Item().withPrimaryKey("Name", "Amazon S3").withString("Category", "Amazon Web Services") - .withNumber("Threads", 0); - table.putItem(item); + item = new Item().withPrimaryKey("Name", "Amazon S3") + .withString("Category", "Amazon Web Services") + .withNumber("Threads", 0); + table.putItem(item); + } catch (Exception e) { + System.err.println("Failed to create item in " + tableName); + System.err.println(e.getMessage()); + } } - catch (Exception e) { - System.err.println("Failed to create item in " + tableName); - System.err.println(e.getMessage()); - } - } - - private static void loadSampleThreads(String tableName) { - try { - long time1 = (new Date()).getTime() - (7 * 24 * 60 * 60 * 1000); // 7 - // days - // ago - long time2 = (new Date()).getTime() - (14 * 24 * 60 * 60 * 1000); // 14 - // days - // ago - long time3 = (new Date()).getTime() - (21 * 24 * 60 * 60 * 1000); // 21 - // days - // ago - - Date date1 = new Date(); - date1.setTime(time1); - - Date date2 = new Date(); - date2.setTime(time2); - - Date date3 = new Date(); - date3.setTime(time3); - - dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); - - Table table = dynamoDB.getTable(tableName); - - System.out.println("Adding data to " + tableName); - - Item item = new Item().withPrimaryKey("ForumName", "Amazon DynamoDB") - .withString("Subject", "DynamoDB Thread 1").withString("Message", "DynamoDB thread 1 message") - .withString("LastPostedBy", "User A").withString("LastPostedDateTime", dateFormatter.format(date2)) - .withNumber("Views", 0).withNumber("Replies", 0).withNumber("Answered", 0) - .withStringSet("Tags", new HashSet(Arrays.asList("index", "primarykey", "table"))); - table.putItem(item); - - item = new Item().withPrimaryKey("ForumName", "Amazon DynamoDB").withString("Subject", "DynamoDB Thread 2") - .withString("Message", "DynamoDB thread 2 message").withString("LastPostedBy", "User A") - .withString("LastPostedDateTime", dateFormatter.format(date3)).withNumber("Views", 0) - .withNumber("Replies", 0).withNumber("Answered", 0) - .withStringSet("Tags", new HashSet(Arrays.asList("index", "partitionkey", "sortkey"))); - table.putItem(item); - - item = new Item().withPrimaryKey("ForumName", "Amazon S3").withString("Subject", "S3 Thread 1") - .withString("Message", "S3 Thread 3 message").withString("LastPostedBy", "User A") - .withString("LastPostedDateTime", dateFormatter.format(date1)).withNumber("Views", 0) - .withNumber("Replies", 0).withNumber("Answered", 0) - .withStringSet("Tags", new HashSet(Arrays.asList("largeobjects", "multipart upload"))); - table.putItem(item); - } - catch (Exception e) { - System.err.println("Failed to create item in " + tableName); - System.err.println(e.getMessage()); - } + private static void loadSampleThreads(String tableName) { + try { + long time1 = (new Date()).getTime() - (7 * 24 * 60 * 60 * 1000); // 7 + // days + // ago + long time2 = (new Date()).getTime() - (14 * 24 * 60 * 60 * 1000); // 14 + // days + // ago + long time3 = (new Date()).getTime() - (21 * 24 * 60 * 60 * 1000); // 21 + // days + // ago + + Date date1 = new Date(); + date1.setTime(time1); + + Date date2 = new Date(); + date2.setTime(time2); + + Date date3 = new Date(); + date3.setTime(time3); + + dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); + + Table table = dynamoDB.getTable(tableName); + + System.out.println("Adding data to " + tableName); + + Item item = new Item().withPrimaryKey("ForumName", "Amazon DynamoDB") + .withString("Subject", "DynamoDB Thread 1") + .withString("Message", "DynamoDB thread 1 message") + .withString("LastPostedBy", "User A") + .withString("LastPostedDateTime", dateFormatter.format(date2)) + .withNumber("Views", 0).withNumber("Replies", 0).withNumber("Answered", 0) + .withStringSet("Tags", new HashSet( + Arrays.asList("index", "primarykey", "table"))); + table.putItem(item); + + item = new Item().withPrimaryKey("ForumName", "Amazon DynamoDB") + .withString("Subject", "DynamoDB Thread 2") + .withString("Message", "DynamoDB thread 2 message") + .withString("LastPostedBy", "User A") + .withString("LastPostedDateTime", dateFormatter.format(date3)) + .withNumber("Views", 0) + .withNumber("Replies", 0).withNumber("Answered", 0) + .withStringSet("Tags", new HashSet( + Arrays.asList("index", "partitionkey", "sortkey"))); + table.putItem(item); + + item = new Item().withPrimaryKey("ForumName", "Amazon S3").withString("Subject", "S3 Thread 1") + .withString("Message", "S3 Thread 3 message") + .withString("LastPostedBy", "User A") + .withString("LastPostedDateTime", dateFormatter.format(date1)) + .withNumber("Views", 0) + .withNumber("Replies", 0).withNumber("Answered", 0) + .withStringSet("Tags", new HashSet( + Arrays.asList("largeobjects", "multipart upload"))); + table.putItem(item); + + } catch (Exception e) { + System.err.println("Failed to create item in " + tableName); + System.err.println(e.getMessage()); + } - } + } - private static void loadSampleReplies(String tableName) { - try { - // 1 day ago - long time0 = (new Date()).getTime() - (1 * 24 * 60 * 60 * 1000); - // 7 days ago - long time1 = (new Date()).getTime() - (7 * 24 * 60 * 60 * 1000); - // 14 days ago - long time2 = (new Date()).getTime() - (14 * 24 * 60 * 60 * 1000); - // 21 days ago - long time3 = (new Date()).getTime() - (21 * 24 * 60 * 60 * 1000); + private static void loadSampleReplies(String tableName) { + try { + // 1 day ago + long time0 = (new Date()).getTime() - (1 * 24 * 60 * 60 * 1000); + // 7 days ago + long time1 = (new Date()).getTime() - (7 * 24 * 60 * 60 * 1000); + // 14 days ago + long time2 = (new Date()).getTime() - (14 * 24 * 60 * 60 * 1000); + // 21 days ago + long time3 = (new Date()).getTime() - (21 * 24 * 60 * 60 * 1000); - Date date0 = new Date(); - date0.setTime(time0); + Date date0 = new Date(); + date0.setTime(time0); - Date date1 = new Date(); - date1.setTime(time1); + Date date1 = new Date(); + date1.setTime(time1); - Date date2 = new Date(); - date2.setTime(time2); + Date date2 = new Date(); + date2.setTime(time2); - Date date3 = new Date(); - date3.setTime(time3); + Date date3 = new Date(); + date3.setTime(time3); - dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); + dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); - Table table = dynamoDB.getTable(tableName); + Table table = dynamoDB.getTable(tableName); - System.out.println("Adding data to " + tableName); + System.out.println("Adding data to " + tableName); - // Add threads. + // Add threads. - Item item = new Item().withPrimaryKey("Id", "Amazon DynamoDB#DynamoDB Thread 1") - .withString("ReplyDateTime", (dateFormatter.format(date3))) - .withString("Message", "DynamoDB Thread 1 Reply 1 text").withString("PostedBy", "User A"); - table.putItem(item); + Item item = new Item().withPrimaryKey("Id", "Amazon DynamoDB#DynamoDB Thread 1") + .withString("ReplyDateTime", (dateFormatter.format(date3))) + .withString("Message", "DynamoDB Thread 1 Reply 1 text") + .withString("PostedBy", "User A"); + table.putItem(item); - item = new Item().withPrimaryKey("Id", "Amazon DynamoDB#DynamoDB Thread 1") - .withString("ReplyDateTime", dateFormatter.format(date2)) - .withString("Message", "DynamoDB Thread 1 Reply 2 text").withString("PostedBy", "User B"); - table.putItem(item); + item = new Item().withPrimaryKey("Id", "Amazon DynamoDB#DynamoDB Thread 1") + .withString("ReplyDateTime", dateFormatter.format(date2)) + .withString("Message", "DynamoDB Thread 1 Reply 2 text") + .withString("PostedBy", "User B"); + table.putItem(item); - item = new Item().withPrimaryKey("Id", "Amazon DynamoDB#DynamoDB Thread 2") - .withString("ReplyDateTime", dateFormatter.format(date1)) - .withString("Message", "DynamoDB Thread 2 Reply 1 text").withString("PostedBy", "User A"); - table.putItem(item); + item = new Item().withPrimaryKey("Id", "Amazon DynamoDB#DynamoDB Thread 2") + .withString("ReplyDateTime", dateFormatter.format(date1)) + .withString("Message", "DynamoDB Thread 2 Reply 1 text") + .withString("PostedBy", "User A"); + table.putItem(item); - item = new Item().withPrimaryKey("Id", "Amazon DynamoDB#DynamoDB Thread 2") - .withString("ReplyDateTime", dateFormatter.format(date0)) - .withString("Message", "DynamoDB Thread 2 Reply 2 text").withString("PostedBy", "User A"); - table.putItem(item); + item = new Item().withPrimaryKey("Id", "Amazon DynamoDB#DynamoDB Thread 2") + .withString("ReplyDateTime", dateFormatter.format(date0)) + .withString("Message", "DynamoDB Thread 2 Reply 2 text") + .withString("PostedBy", "User A"); + table.putItem(item); - } - catch (Exception e) { - System.err.println("Failed to create item in " + tableName); - System.err.println(e.getMessage()); + } catch (Exception e) { + System.err.println("Failed to create item in " + tableName); + System.err.println(e.getMessage()); + } } - } } -// snippet-end:[dynamodb.java.codeexample.SampleDataLoad] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.SampleDataLoad] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/SampleDataTryQuery.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/SampleDataTryQuery.java index 206b3ae3819..3668b00e25f 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/SampleDataTryQuery.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/SampleDataTryQuery.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.SampleDataTryQuery] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.SampleDataTryQuery] package com.amazonaws.codesamples; @@ -58,8 +37,7 @@ public static void main(String[] args) throws Exception { // Query replies posted in the past 15 days for a forum thread. findRepliesInLast15DaysWithConfig("Reply", forumName, threadSubject); - } - catch (Exception e) { + } catch (Exception e) { System.err.println(e.getMessage()); } } @@ -69,9 +47,9 @@ private static void getBook(int id, String tableName) { Table table = dynamoDB.getTable(tableName); Item item = table.getItem("Id", // attribute name - id, // attribute value - "Id, ISBN, Title, Authors", // projection expression - null); // name map - don't need this + id, // attribute value + "Id, ISBN, Title, Authors", // projection expression + null); // name map - don't need this System.out.println("GetItem: printing results..."); System.out.println(item.toJSONPretty()); @@ -90,8 +68,8 @@ private static void findRepliesInLast15DaysWithConfig(String tableName, String f Table table = dynamoDB.getTable(tableName); QuerySpec querySpec = new QuerySpec().withKeyConditionExpression("Id = :v1 and ReplyDateTime > :v2") - .withValueMap(new ValueMap().withString(":v1", replyId).withString(":v2", twoWeeksAgoStr)) - .withProjectionExpression("Message, ReplyDateTime, PostedBy"); + .withValueMap(new ValueMap().withString(":v1", replyId).withString(":v2", twoWeeksAgoStr)) + .withProjectionExpression("Message, ReplyDateTime, PostedBy"); ItemCollection items = table.query(querySpec); Iterator iterator = items.iterator(); @@ -105,4 +83,4 @@ private static void findRepliesInLast15DaysWithConfig(String tableName, String f } -// snippet-end:[dynamodb.java.codeexample.SampleDataTryQuery] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.SampleDataTryQuery] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/StreamsAdapterDemo.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/StreamsAdapterDemo.java index 3699a665e7f..1ccf066ee93 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/StreamsAdapterDemo.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/StreamsAdapterDemo.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.StreamsAdapterDemo] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.StreamsAdapterDemo] package com.amazonaws.codesamples; @@ -68,14 +47,14 @@ public static void main(String[] args) throws Exception { System.out.println("Starting demo..."); dynamoDBClient = AmazonDynamoDBClientBuilder.standard() - .withRegion(awsRegion) - .build(); + .withRegion(awsRegion) + .build(); cloudWatchClient = AmazonCloudWatchClientBuilder.standard() - .withRegion(awsRegion) - .build(); + .withRegion(awsRegion) + .build(); dynamoDBStreamsClient = AmazonDynamoDBStreamsClientBuilder.standard() - .withRegion(awsRegion) - .build(); + .withRegion(awsRegion) + .build(); adapterClient = new AmazonDynamoDBStreamsAdapterClient(dynamoDBStreamsClient); String srcTable = tablePrefix + "-src"; String destTable = tablePrefix + "-dest"; @@ -84,15 +63,16 @@ public static void main(String[] args) throws Exception { setUpTables(); workerConfig = new KinesisClientLibConfiguration("streams-adapter-demo", - streamArn, - awsCredentialsProvider, - "streams-demo-worker") + streamArn, + awsCredentialsProvider, + "streams-demo-worker") .withMaxRecords(1000) .withIdleTimeBetweenReadsInMillis(500) .withInitialPositionInStream(InitialPositionInStream.TRIM_HORIZON); System.out.println("Creating worker for stream: " + streamArn); - worker = StreamsWorkerFactory.createDynamoDbStreamsWorker(recordProcessorFactory, workerConfig, adapterClient, dynamoDBClient, cloudWatchClient); + worker = StreamsWorkerFactory.createDynamoDbStreamsWorker(recordProcessorFactory, workerConfig, adapterClient, + dynamoDBClient, cloudWatchClient); System.out.println("Starting worker..."); Thread t = new Thread(worker); t.start(); @@ -102,10 +82,9 @@ public static void main(String[] args) throws Exception { t.join(); if (StreamsAdapterDemoHelper.scanTable(dynamoDBClient, srcTable).getItems() - .equals(StreamsAdapterDemoHelper.scanTable(dynamoDBClient, destTable).getItems())) { + .equals(StreamsAdapterDemoHelper.scanTable(dynamoDBClient, destTable).getItems())) { System.out.println("Scan result is equal."); - } - else { + } else { System.out.println("Tables are different!"); } @@ -133,13 +112,11 @@ private static void awaitTableCreation(String tableName) { if (created) { System.out.println("Table is active."); return; - } - else { + } else { retries++; try { Thread.sleep(1000); - } - catch (InterruptedException e) { + } catch (InterruptedException e) { // do nothing } } @@ -166,5 +143,4 @@ private static void cleanupAndExit(Integer returnValue) { } } - -// snippet-end:[dynamodb.java.codeexample.StreamsAdapterDemo] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.StreamsAdapterDemo] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/StreamsAdapterDemoHelper.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/StreamsAdapterDemoHelper.java index 50331af5118..8128f814178 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/StreamsAdapterDemoHelper.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/StreamsAdapterDemoHelper.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.StreamsAdapterDemoHelper] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.StreamsAdapterDemoHelper] package com.amazonaws.codesamples; @@ -65,21 +44,20 @@ public static String createTable(AmazonDynamoDB client, String tableName) { // key ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput().withReadCapacityUnits(2L) - .withWriteCapacityUnits(2L); + .withWriteCapacityUnits(2L); StreamSpecification streamSpecification = new StreamSpecification(); streamSpecification.setStreamEnabled(true); streamSpecification.setStreamViewType(StreamViewType.NEW_IMAGE); CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName) - .withAttributeDefinitions(attributeDefinitions).withKeySchema(keySchema) - .withProvisionedThroughput(provisionedThroughput).withStreamSpecification(streamSpecification); + .withAttributeDefinitions(attributeDefinitions).withKeySchema(keySchema) + .withProvisionedThroughput(provisionedThroughput).withStreamSpecification(streamSpecification); try { System.out.println("Creating table " + tableName); CreateTableResult result = client.createTable(createTableRequest); return result.getTableDescription().getLatestStreamArn(); - } - catch (ResourceInUseException e) { + } catch (ResourceInUseException e) { System.out.println("Table already exists."); return describeTable(client, tableName).getTable().getLatestStreamArn(); } @@ -103,7 +81,7 @@ public static void putItem(AmazonDynamoDB dynamoDBClient, String tableName, Stri } public static void putItem(AmazonDynamoDB dynamoDBClient, String tableName, - java.util.Map items) { + java.util.Map items) { PutItemRequest putItemRequest = new PutItemRequest().withTableName(tableName).withItem(items); dynamoDBClient.putItem(putItemRequest); } @@ -114,11 +92,11 @@ public static void updateItem(AmazonDynamoDB dynamoDBClient, String tableName, S Map attributeUpdates = new HashMap(); AttributeValueUpdate update = new AttributeValueUpdate().withAction(AttributeAction.PUT) - .withValue(new AttributeValue().withS(val)); + .withValue(new AttributeValue().withS(val)); attributeUpdates.put("attribute-2", update); UpdateItemRequest updateItemRequest = new UpdateItemRequest().withTableName(tableName).withKey(key) - .withAttributeUpdates(attributeUpdates); + .withAttributeUpdates(attributeUpdates); dynamoDBClient.updateItem(updateItemRequest); } @@ -132,4 +110,4 @@ public static void deleteItem(AmazonDynamoDB dynamoDBClient, String tableName, S } -// snippet-end:[dynamodb.java.codeexample.StreamsAdapterDemoHelper] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.StreamsAdapterDemoHelper] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/StreamsLowLevelDemo.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/StreamsLowLevelDemo.java index ad284871c81..8ea25845a9a 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/StreamsLowLevelDemo.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/StreamsLowLevelDemo.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.StreamsLowLevelDemo] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.StreamsLowLevelDemo] package com.amazon.codesamples; @@ -63,152 +42,153 @@ public class StreamsLowLevelDemo { - public static void main(String args[]) throws InterruptedException { - - AmazonDynamoDB dynamoDBClient = AmazonDynamoDBClientBuilder - .standard() - .withRegion(Regions.US_EAST_2) - .withCredentials(new DefaultAWSCredentialsProviderChain()) - .build(); - - AmazonDynamoDBStreams streamsClient = - AmazonDynamoDBStreamsClientBuilder - .standard() - .withRegion(Regions.US_EAST_2) - .withCredentials(new DefaultAWSCredentialsProviderChain()) - .build(); - - // Create a table, with a stream enabled - String tableName = "TestTableForStreams"; - - ArrayList attributeDefinitions = new ArrayList<>( - Arrays.asList(new AttributeDefinition() - .withAttributeName("Id") - .withAttributeType("N"))); - - ArrayList keySchema = new ArrayList<>( - Arrays.asList(new KeySchemaElement() - .withAttributeName("Id") - .withKeyType(KeyType.HASH))); // Partition key - - StreamSpecification streamSpecification = new StreamSpecification() - .withStreamEnabled(true) - .withStreamViewType(StreamViewType.NEW_AND_OLD_IMAGES); - - CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName) - .withKeySchema(keySchema).withAttributeDefinitions(attributeDefinitions) - .withProvisionedThroughput(new ProvisionedThroughput() - .withReadCapacityUnits(10L) - .withWriteCapacityUnits(10L)) - .withStreamSpecification(streamSpecification); - - System.out.println("Issuing CreateTable request for " + tableName); - dynamoDBClient.createTable(createTableRequest); - System.out.println("Waiting for " + tableName + " to be created..."); - - try { - TableUtils.waitUntilActive(dynamoDBClient, tableName); - } catch (AmazonClientException e) { - e.printStackTrace(); - } - - // Print the stream settings for the table - DescribeTableResult describeTableResult = dynamoDBClient.describeTable(tableName); - String streamArn = describeTableResult.getTable().getLatestStreamArn(); - System.out.println("Current stream ARN for " + tableName + ": " + - describeTableResult.getTable().getLatestStreamArn()); - StreamSpecification streamSpec = describeTableResult.getTable().getStreamSpecification(); - System.out.println("Stream enabled: " + streamSpec.getStreamEnabled()); - System.out.println("Update view type: " + streamSpec.getStreamViewType()); - System.out.println(); - - // Generate write activity in the table - - System.out.println("Performing write activities on " + tableName); - int maxItemCount = 100; - for (Integer i = 1; i <= maxItemCount; i++) { - System.out.println("Processing item " + i + " of " + maxItemCount); - - // Write a new item - Map item = new HashMap<>(); - item.put("Id", new AttributeValue().withN(i.toString())); - item.put("Message", new AttributeValue().withS("New item!")); - dynamoDBClient.putItem(tableName, item); - - - // Update the item - Map key = new HashMap<>(); - key.put("Id", new AttributeValue().withN(i.toString())); - Map attributeUpdates = new HashMap<>(); - attributeUpdates.put("Message", new AttributeValueUpdate() - .withAction(AttributeAction.PUT) - .withValue(new AttributeValue() - .withS("This item has changed"))); - dynamoDBClient.updateItem(tableName, key, attributeUpdates); - - // Delete the item - dynamoDBClient.deleteItem(tableName, key); - } - - // Get all the shard IDs from the stream. Note that DescribeStream returns - // the shard IDs one page at a time. - String lastEvaluatedShardId = null; - - do { - DescribeStreamResult describeStreamResult = streamsClient.describeStream( - new DescribeStreamRequest() - .withStreamArn(streamArn) - .withExclusiveStartShardId(lastEvaluatedShardId)); - List shards = describeStreamResult.getStreamDescription().getShards(); - - // Process each shard on this page - - for (Shard shard : shards) { - String shardId = shard.getShardId(); - System.out.println("Shard: " + shard); - - // Get an iterator for the current shard - - GetShardIteratorRequest getShardIteratorRequest = new GetShardIteratorRequest() - .withStreamArn(streamArn) - .withShardId(shardId) - .withShardIteratorType(ShardIteratorType.TRIM_HORIZON); - GetShardIteratorResult getShardIteratorResult = - streamsClient.getShardIterator(getShardIteratorRequest); - String currentShardIter = getShardIteratorResult.getShardIterator(); - - // Shard iterator is not null until the Shard is sealed (marked as READ_ONLY). - // To prevent running the loop until the Shard is sealed, which will be on average - // 4 hours, we process only the items that were written into DynamoDB and then exit. - int processedRecordCount = 0; - while (currentShardIter != null && processedRecordCount < maxItemCount) { - System.out.println(" Shard iterator: " + currentShardIter.substring(380)); - - // Use the shard iterator to read the stream records - - GetRecordsResult getRecordsResult = streamsClient.getRecords(new GetRecordsRequest() - .withShardIterator(currentShardIter)); - List records = getRecordsResult.getRecords(); - for (Record record : records) { - System.out.println(" " + record.getDynamodb()); - } - processedRecordCount += records.size(); - currentShardIter = getRecordsResult.getNextShardIterator(); + public static void main(String args[]) throws InterruptedException { + + AmazonDynamoDB dynamoDBClient = AmazonDynamoDBClientBuilder + .standard() + .withRegion(Regions.US_EAST_2) + .withCredentials(new DefaultAWSCredentialsProviderChain()) + .build(); + + AmazonDynamoDBStreams streamsClient = AmazonDynamoDBStreamsClientBuilder + .standard() + .withRegion(Regions.US_EAST_2) + .withCredentials(new DefaultAWSCredentialsProviderChain()) + .build(); + + // Create a table, with a stream enabled + String tableName = "TestTableForStreams"; + + ArrayList attributeDefinitions = new ArrayList<>( + Arrays.asList(new AttributeDefinition() + .withAttributeName("Id") + .withAttributeType("N"))); + + ArrayList keySchema = new ArrayList<>( + Arrays.asList(new KeySchemaElement() + .withAttributeName("Id") + .withKeyType(KeyType.HASH))); // Partition key + + StreamSpecification streamSpecification = new StreamSpecification() + .withStreamEnabled(true) + .withStreamViewType(StreamViewType.NEW_AND_OLD_IMAGES); + + CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName) + .withKeySchema(keySchema).withAttributeDefinitions(attributeDefinitions) + .withProvisionedThroughput(new ProvisionedThroughput() + .withReadCapacityUnits(10L) + .withWriteCapacityUnits(10L)) + .withStreamSpecification(streamSpecification); + + System.out.println("Issuing CreateTable request for " + tableName); + dynamoDBClient.createTable(createTableRequest); + System.out.println("Waiting for " + tableName + " to be created..."); + + try { + TableUtils.waitUntilActive(dynamoDBClient, tableName); + } catch (AmazonClientException e) { + e.printStackTrace(); } - } - - // If LastEvaluatedShardId is set, then there is - // at least one more page of shard IDs to retrieve - lastEvaluatedShardId = describeStreamResult.getStreamDescription().getLastEvaluatedShardId(); - - } while (lastEvaluatedShardId != null); - // Delete the table - System.out.println("Deleting the table..."); - dynamoDBClient.deleteTable(tableName); + // Print the stream settings for the table + DescribeTableResult describeTableResult = dynamoDBClient.describeTable(tableName); + String streamArn = describeTableResult.getTable().getLatestStreamArn(); + System.out.println("Current stream ARN for " + tableName + ": " + + describeTableResult.getTable().getLatestStreamArn()); + StreamSpecification streamSpec = describeTableResult.getTable().getStreamSpecification(); + System.out.println("Stream enabled: " + streamSpec.getStreamEnabled()); + System.out.println("Update view type: " + streamSpec.getStreamViewType()); + System.out.println(); + + // Generate write activity in the table + + System.out.println("Performing write activities on " + tableName); + int maxItemCount = 100; + for (Integer i = 1; i <= maxItemCount; i++) { + System.out.println("Processing item " + i + " of " + maxItemCount); + + // Write a new item + Map item = new HashMap<>(); + item.put("Id", new AttributeValue().withN(i.toString())); + item.put("Message", new AttributeValue().withS("New item!")); + dynamoDBClient.putItem(tableName, item); + + // Update the item + Map key = new HashMap<>(); + key.put("Id", new AttributeValue().withN(i.toString())); + Map attributeUpdates = new HashMap<>(); + attributeUpdates.put("Message", new AttributeValueUpdate() + .withAction(AttributeAction.PUT) + .withValue(new AttributeValue() + .withS("This item has changed"))); + dynamoDBClient.updateItem(tableName, key, attributeUpdates); + + // Delete the item + dynamoDBClient.deleteItem(tableName, key); + } - System.out.println("Demo complete"); + // Get all the shard IDs from the stream. Note that DescribeStream returns + // the shard IDs one page at a time. + String lastEvaluatedShardId = null; + + do { + DescribeStreamResult describeStreamResult = streamsClient.describeStream( + new DescribeStreamRequest() + .withStreamArn(streamArn) + .withExclusiveStartShardId(lastEvaluatedShardId)); + List shards = describeStreamResult.getStreamDescription().getShards(); + + // Process each shard on this page + + for (Shard shard : shards) { + String shardId = shard.getShardId(); + System.out.println("Shard: " + shard); + + // Get an iterator for the current shard + + GetShardIteratorRequest getShardIteratorRequest = new GetShardIteratorRequest() + .withStreamArn(streamArn) + .withShardId(shardId) + .withShardIteratorType(ShardIteratorType.TRIM_HORIZON); + GetShardIteratorResult getShardIteratorResult = streamsClient + .getShardIterator(getShardIteratorRequest); + String currentShardIter = getShardIteratorResult.getShardIterator(); + + // Shard iterator is not null until the Shard is sealed (marked as READ_ONLY). + // To prevent running the loop until the Shard is sealed, which will be on + // average + // 4 hours, we process only the items that were written into DynamoDB and then + // exit. + int processedRecordCount = 0; + while (currentShardIter != null && processedRecordCount < maxItemCount) { + System.out.println(" Shard iterator: " + currentShardIter.substring(380)); + + // Use the shard iterator to read the stream records + + GetRecordsResult getRecordsResult = streamsClient + .getRecords(new GetRecordsRequest() + .withShardIterator(currentShardIter)); + List records = getRecordsResult.getRecords(); + for (Record record : records) { + System.out.println(" " + record.getDynamodb()); + } + processedRecordCount += records.size(); + currentShardIter = getRecordsResult.getNextShardIterator(); + } + } + + // If LastEvaluatedShardId is set, then there is + // at least one more page of shard IDs to retrieve + lastEvaluatedShardId = describeStreamResult.getStreamDescription().getLastEvaluatedShardId(); + + } while (lastEvaluatedShardId != null); + + // Delete the table + System.out.println("Deleting the table..."); + dynamoDBClient.deleteTable(tableName); + + System.out.println("Demo complete"); - } + } } -// snippet-end:[dynamodb.java.codeexample.StreamsLowLevelDemo] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.StreamsLowLevelDemo] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/StreamsRecordProcessor.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/StreamsRecordProcessor.java index 67625cb8073..9e236ba00fc 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/StreamsRecordProcessor.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/StreamsRecordProcessor.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.StreamsRecordProcessor] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.StreamsRecordProcessor] package com.amazonaws.codesamples; @@ -66,24 +45,23 @@ public void processRecords(ProcessRecordsInput processRecordsInput) { case "INSERT": case "MODIFY": StreamsAdapterDemoHelper.putItem(dynamoDBClient, tableName, - streamRecord.getDynamodb().getNewImage()); + streamRecord.getDynamodb().getNewImage()); break; case "REMOVE": StreamsAdapterDemoHelper.deleteItem(dynamoDBClient, tableName, - streamRecord.getDynamodb().getKeys().get("Id").getN()); + streamRecord.getDynamodb().getKeys().get("Id").getN()); } } checkpointCounter += 1; if (checkpointCounter % 10 == 0) { try { processRecordsInput.getCheckpointer().checkpoint(); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } } } - + } @Override @@ -91,13 +69,12 @@ public void shutdown(ShutdownInput shutdownInput) { if (shutdownInput.getShutdownReason() == ShutdownReason.TERMINATE) { try { shutdownInput.getCheckpointer().checkpoint(); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } } - - } + + } } -// snippet-end:[dynamodb.java.codeexample.StreamsRecordProcessor] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.StreamsRecordProcessor] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/StreamsRecordProcessorFactory.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/StreamsRecordProcessorFactory.java index 6be5ed541e0..a544111c2c3 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/StreamsRecordProcessorFactory.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/StreamsRecordProcessorFactory.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.StreamsRecordProcessorFactory] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.StreamsRecordProcessorFactory] package com.amazonaws.codesamples; @@ -44,4 +23,4 @@ public IRecordProcessor createProcessor() { return new StreamsRecordProcessor(dynamoDBClient, tableName); } } -// snippet-end:[dynamodb.java.codeexample.StreamsRecordProcessorFactory] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.StreamsRecordProcessorFactory] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/datamodeling/DynamoDBMapperBatchWriteExample.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/datamodeling/DynamoDBMapperBatchWriteExample.java index e8087a40445..6acca9fd595 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/datamodeling/DynamoDBMapperBatchWriteExample.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/datamodeling/DynamoDBMapperBatchWriteExample.java @@ -1,27 +1,5 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.amazonaws.codesamples.datamodeling; @@ -59,8 +37,7 @@ public static void main(String[] args) throws Exception { System.out.println("Example complete!"); - } - catch (Throwable t) { + } catch (Throwable t) { System.err.println("Error running the DynamoDBMapperBatchWriteExample: " + t); t.printStackTrace(); } @@ -132,8 +109,8 @@ private static void testBatchWrite(DynamoDBMapper mapper) { List objectsToDelete = Arrays.asList(book3); DynamoDBMapperConfig config = DynamoDBMapperConfig.builder() - .withSaveBehavior(DynamoDBMapperConfig.SaveBehavior.CLOBBER) - .build(); + .withSaveBehavior(DynamoDBMapperConfig.SaveBehavior.CLOBBER) + .build(); mapper.batchWrite(objectsToWrite, objectsToDelete, config); } @@ -215,7 +192,7 @@ public void setInPublication(boolean inPublication) { @Override public String toString() { return "Book [ISBN=" + ISBN + ", price=" + price + ", product category=" + productCategory + ", id=" + id - + ", title=" + title + "]"; + + ", title=" + title + "]"; } } @@ -399,4 +376,4 @@ public void setThreads(int threads) { } } -// snippet-end:[dynamodb.java.codeexample.DynamoDBMapperBatchWriteExample] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.DynamoDBMapperBatchWriteExample] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/datamodeling/DynamoDBMapperCRUDExample.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/datamodeling/DynamoDBMapperCRUDExample.java index 568d1d80fd2..a3c054904cd 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/datamodeling/DynamoDBMapperCRUDExample.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/datamodeling/DynamoDBMapperCRUDExample.java @@ -1,27 +1,5 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.amazonaws.codesamples.datamodeling; @@ -126,8 +104,8 @@ private static void testCRUDOperations() { // Retrieve the updated item. DynamoDBMapperConfig config = DynamoDBMapperConfig.builder() - .withConsistentReads(DynamoDBMapperConfig.ConsistentReads.CONSISTENT) - .build(); + .withConsistentReads(DynamoDBMapperConfig.ConsistentReads.CONSISTENT) + .build(); CatalogItem updatedItem = mapper.load(CatalogItem.class, 601, config); System.out.println("Retrieved the previously updated item:"); System.out.println(updatedItem); @@ -143,4 +121,4 @@ private static void testCRUDOperations() { } } -// snippet-end:[dynamodb.java.codeexample.DynamoDBMapperCRUDExample] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.DynamoDBMapperCRUDExample] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/datamodeling/DynamoDBMapperExample.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/datamodeling/DynamoDBMapperExample.java index fe76777f2e3..540f2021056 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/datamodeling/DynamoDBMapperExample.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/datamodeling/DynamoDBMapperExample.java @@ -1,26 +1,5 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.amazonaws.codesamples.datamodeling; // snippet-start:[dynamodb.java.codeexample.DynamoDBMapperExample.import] @@ -138,8 +117,9 @@ public void setDimensions(DimensionType dimensionType) { @Override public String toString() { return "Book [ISBN=" + ISBN + ", bookAuthors=" + bookAuthors + ", dimensionType= " - + dimensionType.getHeight() + " X " + dimensionType.getLength() + " X " + dimensionType.getThickness() - + ", Id=" + id + ", Title=" + title + "]"; + + dimensionType.getHeight() + " X " + dimensionType.getLength() + " X " + + dimensionType.getThickness() + + ", Id=" + id + ", Title=" + title + "]"; } } @@ -184,10 +164,9 @@ public String convert(DimensionType object) { try { if (itemDimensions != null) { dimension = String.format("%s x %s x %s", itemDimensions.getLength(), itemDimensions.getHeight(), - itemDimensions.getThickness()); + itemDimensions.getThickness()); } - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } return dimension; @@ -204,8 +183,7 @@ public DimensionType unconvert(String s) { itemDimension.setHeight(data[1].trim()); itemDimension.setThickness(data[2].trim()); } - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } @@ -213,4 +191,4 @@ public DimensionType unconvert(String s) { } } } -// snippet-end:[dynamodb.java.codeexample.DynamoDBMapperExample] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.DynamoDBMapperExample] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/datamodeling/DynamoDBMapperQueryScanExample.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/datamodeling/DynamoDBMapperQueryScanExample.java index d256807317e..efbe40a08e3 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/datamodeling/DynamoDBMapperQueryScanExample.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/datamodeling/DynamoDBMapperQueryScanExample.java @@ -1,27 +1,5 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.amazonaws.codesamples.datamodeling; @@ -76,8 +54,7 @@ public static void main(String[] args) throws Exception { System.out.println("Example complete!"); - } - catch (Throwable t) { + } catch (Throwable t) { System.err.println("Error running the DynamoDBMapperQueryScanExample: " + t); t.printStackTrace(); } @@ -91,7 +68,7 @@ private static void GetBook(DynamoDBMapper mapper, int id) throws Exception { } private static void FindRepliesInLast15Days(DynamoDBMapper mapper, String forumName, String threadSubject) - throws Exception { + throws Exception { System.out.println("FindRepliesInLast15Days: Replies within last 15 days."); String partitionKey = forumName + "#" + threadSubject; @@ -108,22 +85,22 @@ private static void FindRepliesInLast15Days(DynamoDBMapper mapper, String forumN eav.put(":val2", new AttributeValue().withS(twoWeeksAgoStr.toString())); DynamoDBQueryExpression queryExpression = new DynamoDBQueryExpression() - .withKeyConditionExpression("Id = :val1 and ReplyDateTime > :val2").withExpressionAttributeValues(eav); + .withKeyConditionExpression("Id = :val1 and ReplyDateTime > :val2").withExpressionAttributeValues(eav); List latestReplies = mapper.query(Reply.class, queryExpression); for (Reply reply : latestReplies) { System.out.format("Id=%s, Message=%s, PostedBy=%s %n, ReplyDateTime=%s %n", reply.getId(), - reply.getMessage(), reply.getPostedBy(), reply.getReplyDateTime()); + reply.getMessage(), reply.getPostedBy(), reply.getReplyDateTime()); } } private static void FindRepliesPostedWithinTimePeriod(DynamoDBMapper mapper, String forumName, String threadSubject) - throws Exception { + throws Exception { String partitionKey = forumName + "#" + threadSubject; System.out.println( - "FindRepliesPostedWithinTimePeriod: Find replies for thread Message = 'DynamoDB Thread 2' posted within a period."); + "FindRepliesPostedWithinTimePeriod: Find replies for thread Message = 'DynamoDB Thread 2' posted within a period."); long startDateMilli = (new Date()).getTime() - (14L * 24L * 60L * 60L * 1000L); // Two // weeks // ago. @@ -141,14 +118,14 @@ private static void FindRepliesPostedWithinTimePeriod(DynamoDBMapper mapper, Str eav.put(":val3", new AttributeValue().withS(endDate)); DynamoDBQueryExpression queryExpression = new DynamoDBQueryExpression() - .withKeyConditionExpression("Id = :val1 and ReplyDateTime between :val2 and :val3") - .withExpressionAttributeValues(eav); + .withKeyConditionExpression("Id = :val1 and ReplyDateTime between :val2 and :val3") + .withExpressionAttributeValues(eav); List betweenReplies = mapper.query(Reply.class, queryExpression); for (Reply reply : betweenReplies) { System.out.format("Id=%s, Message=%s, PostedBy=%s %n, PostedDateTime=%s %n", reply.getId(), - reply.getMessage(), reply.getPostedBy(), reply.getReplyDateTime()); + reply.getMessage(), reply.getPostedBy(), reply.getReplyDateTime()); } } @@ -162,7 +139,7 @@ private static void FindBooksPricedLessThanSpecifiedValue(DynamoDBMapper mapper, eav.put(":val2", new AttributeValue().withS("Book")); DynamoDBScanExpression scanExpression = new DynamoDBScanExpression() - .withFilterExpression("Price < :val1 and ProductCategory = :val2").withExpressionAttributeValues(eav); + .withFilterExpression("Price < :val1 and ProductCategory = :val2").withExpressionAttributeValues(eav); List scanResult = mapper.scan(Book.class, scanExpression); @@ -172,7 +149,7 @@ private static void FindBooksPricedLessThanSpecifiedValue(DynamoDBMapper mapper, } private static void FindBicyclesOfSpecificTypeWithMultipleThreads(DynamoDBMapper mapper, int numberOfThreads, - String bicycleType) throws Exception { + String bicycleType) throws Exception { System.out.println("FindBicyclesOfSpecificTypeWithMultipleThreads: Scan ProductCatalog With Multiple Threads."); Map eav = new HashMap(); @@ -180,7 +157,8 @@ private static void FindBicyclesOfSpecificTypeWithMultipleThreads(DynamoDBMapper eav.put(":val2", new AttributeValue().withS(bicycleType)); DynamoDBScanExpression scanExpression = new DynamoDBScanExpression() - .withFilterExpression("ProductCategory = :val1 and BicycleType = :val2").withExpressionAttributeValues(eav); + .withFilterExpression("ProductCategory = :val1 and BicycleType = :val2") + .withExpressionAttributeValues(eav); List scanResult = mapper.parallelScan(Bicycle.class, scanExpression, numberOfThreads); for (Bicycle bicycle : scanResult) { @@ -264,7 +242,7 @@ public void setInPublication(boolean inPublication) { @Override public String toString() { return "Book [ISBN=" + ISBN + ", price=" + price + ", product category=" + productCategory + ", id=" + id - + ", title=" + title + "]"; + + ", title=" + title + "]"; } } @@ -355,7 +333,7 @@ public void setProductCategory(String productCategory) { @Override public String toString() { return "Bicycle [Type=" + bicycleType + ", color=" + color + ", price=" + price + ", product category=" - + productCategory + ", id=" + id + ", title=" + title + "]"; + + productCategory + ", id=" + id + ", title=" + title + "]"; } } @@ -538,4 +516,4 @@ public void setThreads(int threads) { } } -// snippet-end:[dynamodb.java.codeexample.DynamoDBMapperQueryScanExample] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.DynamoDBMapperQueryScanExample] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/datamodeling/DynamoDBMapperTransactionExample.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/datamodeling/DynamoDBMapperTransactionExample.java index c0766095fdd..d28f4d9e763 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/datamodeling/DynamoDBMapperTransactionExample.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/datamodeling/DynamoDBMapperTransactionExample.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.amazonaws.codesamples.datamodeling; @@ -33,7 +31,7 @@ public class DynamoDBMapperTransactionExample { static AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build(); static DynamoDBMapper mapper; - public static void main(String[] args) throws Exception { + public static void main(String[] args) throws Exception { try { mapper = new DynamoDBMapper(client); @@ -46,8 +44,7 @@ public static void main(String[] args) throws Exception { testTransactionLoadWithTransactionWrite(); System.out.println("Example complete"); - } - catch (Throwable t) { + } catch (Throwable t) { System.err.println("Error running the DynamoDBMapperTransactionWriteExample: " + t); t.printStackTrace(); } @@ -72,8 +69,8 @@ private static void testTransactionLoadWithSave() { dynamodbForum.setThreads(1); mapper.save(dynamodbForum); - - // Read DynamoDB Forum item and Thread item at the same time in a serializable manner + // Read DynamoDB Forum item and Thread item at the same time in a serializable + // manner TransactionLoadRequest transactionLoadRequest = new TransactionLoadRequest(); // Read entire item for DynamoDB Forum @@ -84,7 +81,8 @@ private static void testTransactionLoadWithSave() { .withProjectionExpression("Subject, Message"); transactionLoadRequest.addLoad(dynamodbForumThread, loadExpressionForThread); - // Loaded objects are guaranteed to be in same order as the order in which they are + // Loaded objects are guaranteed to be in same order as the order in which they + // are // added to TransactionLoadRequest List loadedObjects = executeTransactionLoad(transactionLoadRequest); Forum loadedDynamoDBForum = (Forum) loadedObjects.get(0); @@ -116,8 +114,8 @@ private static void testTransactionLoadWithTransactionWrite() { transactionWriteRequest.addUpdate(dynamodbForum); executeTransactionWrite(transactionWriteRequest); - - // Read DynamoDB Forum item and Thread item at the same time in a serializable manner + // Read DynamoDB Forum item and Thread item at the same time in a serializable + // manner TransactionLoadRequest transactionLoadRequest = new TransactionLoadRequest(); // Read entire item for DynamoDB Forum @@ -128,7 +126,8 @@ private static void testTransactionLoadWithTransactionWrite() { .withProjectionExpression("Subject, Message"); transactionLoadRequest.addLoad(dynamodbForumThread, loadExpressionForThread); - // Loaded objects are guaranteed to be in same order as the order in which they are + // Loaded objects are guaranteed to be in same order as the order in which they + // are // added to TransactionLoadRequest List loadedObjects = executeTransactionLoad(transactionLoadRequest); Forum loadedDynamoDBForum = (Forum) loadedObjects.get(0); @@ -147,7 +146,8 @@ private static void testPutAndUpdateInTransactionWrite() { s3Forum.setThreads(0); mapper.save(s3Forum); - // Update Forum item for S3 and Create new Forum item for DynamoDB using transactionWrite + // Update Forum item for S3 and Create new Forum item for DynamoDB using + // transactionWrite s3Forum.setCategory("Amazon Web Services"); Forum dynamodbForum = new Forum(); dynamodbForum.setName("DynamoDB Forum"); @@ -160,7 +160,8 @@ private static void testPutAndUpdateInTransactionWrite() { } private static void testPutWithConditionalUpdateInTransactionWrite() { - // Create new Thread item for DynamoDB forum and update thread count in DynamoDB forum + // Create new Thread item for DynamoDB forum and update thread count in DynamoDB + // forum // if the DynamoDB Forum exists Thread dynamodbForumThread = new Thread(); dynamodbForumThread.setForumName("DynamoDB Forum"); @@ -182,7 +183,8 @@ private static void testPutWithConditionalUpdateInTransactionWrite() { } private static void testPutWithConditionCheckInTransactionWrite() { - // Create new Thread item for DynamoDB forum and update thread count in DynamoDB forum if a thread already exists + // Create new Thread item for DynamoDB forum and update thread count in DynamoDB + // forum if a thread already exists Thread dynamodbForumThread2 = new Thread(); dynamodbForumThread2.setForumName("DynamoDB Forum"); dynamodbForumThread2.setSubject("Sample Subject 2"); @@ -207,7 +209,8 @@ private static void testPutWithConditionCheckInTransactionWrite() { } private static void testMixedOperationsInTransactionWrite() { - // Create new Thread item for S3 forum and delete "Sample Subject 1" Thread from DynamoDB forum if + // Create new Thread item for S3 forum and delete "Sample Subject 1" Thread from + // DynamoDB forum if // "Sample Subject 2" Thread exists in DynamoDB forum Thread s3ForumThread = new Thread(); s3ForumThread.setForumName("S3 Forum"); @@ -242,6 +245,7 @@ private static void testMixedOperationsInTransactionWrite() { transactionWriteRequest.addUpdate(dynamodbForum); executeTransactionWrite(transactionWriteRequest); } + private static List executeTransactionLoad(TransactionLoadRequest transactionLoadRequest) { List loadedObjects = new ArrayList(); try { @@ -249,29 +253,38 @@ private static List executeTransactionLoad(TransactionLoadRequest transa } catch (DynamoDBMappingException ddbme) { System.err.println("Client side error in Mapper, fix before retrying. Error: " + ddbme.getMessage()); } catch (ResourceNotFoundException rnfe) { - System.err.println("One of the tables was not found, verify table exists before retrying. Error: " + rnfe.getMessage()); + System.err.println("One of the tables was not found, verify table exists before retrying. Error: " + + rnfe.getMessage()); } catch (InternalServerErrorException ise) { - System.err.println("Internal Server Error, generally safe to retry with back-off. Error: " + ise.getMessage()); + System.err.println( + "Internal Server Error, generally safe to retry with back-off. Error: " + ise.getMessage()); } catch (TransactionCanceledException tce) { - System.err.println("Transaction Canceled, implies a client issue, fix before retrying. Error: " + tce.getMessage()); + System.err.println( + "Transaction Canceled, implies a client issue, fix before retrying. Error: " + tce.getMessage()); } catch (Exception ex) { - System.err.println("An exception occurred, investigate and configure retry strategy. Error: " + ex.getMessage()); + System.err.println( + "An exception occurred, investigate and configure retry strategy. Error: " + ex.getMessage()); } return loadedObjects; } + private static void executeTransactionWrite(TransactionWriteRequest transactionWriteRequest) { try { mapper.transactionWrite(transactionWriteRequest); } catch (DynamoDBMappingException ddbme) { System.err.println("Client side error in Mapper, fix before retrying. Error: " + ddbme.getMessage()); } catch (ResourceNotFoundException rnfe) { - System.err.println("One of the tables was not found, verify table exists before retrying. Error: " + rnfe.getMessage()); + System.err.println("One of the tables was not found, verify table exists before retrying. Error: " + + rnfe.getMessage()); } catch (InternalServerErrorException ise) { - System.err.println("Internal Server Error, generally safe to retry with back-off. Error: " + ise.getMessage()); + System.err.println( + "Internal Server Error, generally safe to retry with back-off. Error: " + ise.getMessage()); } catch (TransactionCanceledException tce) { - System.err.println("Transaction Canceled, implies a client issue, fix before retrying. Error: " + tce.getMessage()); + System.err.println( + "Transaction Canceled, implies a client issue, fix before retrying. Error: " + tce.getMessage()); } catch (Exception ex) { - System.err.println("An exception occurred, investigate and configure retry strategy. Error: " + ex.getMessage()); + System.err.println( + "An exception occurred, investigate and configure retry strategy. Error: " + ex.getMessage()); } } diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIBatchGet.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIBatchGet.java index 8ffc1fd0db2..91b8a94f57b 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIBatchGet.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIBatchGet.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.DocumentAPIBatchGet] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.DocumentAPIBatchGet] package com.amazonaws.codesamples.document; @@ -60,12 +39,12 @@ private static void retrieveMultipleItemsBatchGet() { TableKeysAndAttributes threadTableKeysAndAttributes = new TableKeysAndAttributes(threadTableName); // Add a partition key and a sort key threadTableKeysAndAttributes.addHashAndRangePrimaryKeys("ForumName", "Subject", "Amazon DynamoDB", - "DynamoDB Thread 1", "Amazon DynamoDB", "DynamoDB Thread 2", "Amazon S3", "S3 Thread 1"); + "DynamoDB Thread 1", "Amazon DynamoDB", "DynamoDB Thread 2", "Amazon S3", "S3 Thread 1"); System.out.println("Making the request."); BatchGetItemOutcome outcome = dynamoDB.batchGetItem(forumTableKeysAndAttributes, - threadTableKeysAndAttributes); + threadTableKeysAndAttributes); Map unprocessed = null; @@ -85,16 +64,14 @@ private static void retrieveMultipleItemsBatchGet() { if (unprocessed.isEmpty()) { System.out.println("No unprocessed keys found"); - } - else { + } else { System.out.println("Retrieving the unprocessed keys"); outcome = dynamoDB.batchGetItemUnprocessed(unprocessed); } } while (!unprocessed.isEmpty()); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Failed to retrieve items."); System.err.println(e.getMessage()); } @@ -103,4 +80,4 @@ private static void retrieveMultipleItemsBatchGet() { } -// snippet-end:[dynamodb.java.codeexample.DocumentAPIBatchGet] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.DocumentAPIBatchGet] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIBatchWrite.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIBatchWrite.java index dc2b0fa16f3..78d6026ac18 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIBatchWrite.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIBatchWrite.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.DocumentAPIBatchWrite] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.DocumentAPIBatchWrite] package com.amazonaws.codesamples.document; @@ -59,16 +38,17 @@ private static void writeMultipleItemsBatchWrite() { // Add a new item to Forum TableWriteItems forumTableWriteItems = new TableWriteItems(forumTableName) // Forum - .withItemsToPut(new Item().withPrimaryKey("Name", "Amazon RDS").withNumber("Threads", 0)); + .withItemsToPut(new Item().withPrimaryKey("Name", "Amazon RDS").withNumber("Threads", 0)); // Add a new item, and delete an existing item, from Thread // This table has a partition key and range key, so need to specify // both of them TableWriteItems threadTableWriteItems = new TableWriteItems(threadTableName) - .withItemsToPut(new Item().withPrimaryKey("ForumName", "Amazon RDS", "Subject", "Amazon RDS Thread 1") - .withString("Message", "ElastiCache Thread 1 message") - .withStringSet("Tags", new HashSet(Arrays.asList("cache", "in-memory")))) - .withHashAndRangeKeysToDelete("ForumName", "Subject", "Amazon S3", "S3 Thread 100"); + .withItemsToPut( + new Item().withPrimaryKey("ForumName", "Amazon RDS", "Subject", "Amazon RDS Thread 1") + .withString("Message", "ElastiCache Thread 1 message") + .withStringSet("Tags", new HashSet(Arrays.asList("cache", "in-memory")))) + .withHashAndRangeKeysToDelete("ForumName", "Subject", "Amazon S3", "S3 Thread 100"); System.out.println("Making the request."); BatchWriteItemOutcome outcome = dynamoDB.batchWriteItem(forumTableWriteItems, threadTableWriteItems); @@ -82,16 +62,14 @@ private static void writeMultipleItemsBatchWrite() { if (outcome.getUnprocessedItems().size() == 0) { System.out.println("No unprocessed items found"); - } - else { + } else { System.out.println("Retrieving the unprocessed items"); outcome = dynamoDB.batchWriteItemUnprocessed(unprocessedItems); } } while (outcome.getUnprocessedItems().size() > 0); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Failed to retrieve items: "); e.printStackTrace(System.err); } @@ -100,4 +78,4 @@ private static void writeMultipleItemsBatchWrite() { } -// snippet-end:[dynamodb.java.codeexample.DocumentAPIBatchWrite] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.DocumentAPIBatchWrite] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIGlobalSecondaryIndexExample.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIGlobalSecondaryIndexExample.java index 1f423da1e95..48c1c723d3b 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIGlobalSecondaryIndexExample.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIGlobalSecondaryIndexExample.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.DocumentAPIGlobalSecondaryIndexExample] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.DocumentAPIGlobalSecondaryIndexExample] package com.amazonaws.codesamples.document; @@ -86,39 +65,39 @@ public static void createTable() { // Initial provisioned throughput settings for the indexes ProvisionedThroughput ptIndex = new ProvisionedThroughput().withReadCapacityUnits(1L) - .withWriteCapacityUnits(1L); + .withWriteCapacityUnits(1L); // CreateDateIndex GlobalSecondaryIndex createDateIndex = new GlobalSecondaryIndex().withIndexName("CreateDateIndex") - .withProvisionedThroughput(ptIndex) - .withKeySchema(new KeySchemaElement().withAttributeName("CreateDate").withKeyType(KeyType.HASH), // Partition - // key - new KeySchemaElement().withAttributeName("IssueId").withKeyType(KeyType.RANGE)) // Sort - // key - .withProjection( - new Projection().withProjectionType("INCLUDE").withNonKeyAttributes("Description", "Status")); + .withProvisionedThroughput(ptIndex) + .withKeySchema(new KeySchemaElement().withAttributeName("CreateDate").withKeyType(KeyType.HASH), // Partition + // key + new KeySchemaElement().withAttributeName("IssueId").withKeyType(KeyType.RANGE)) // Sort + // key + .withProjection( + new Projection().withProjectionType("INCLUDE").withNonKeyAttributes("Description", "Status")); // TitleIndex GlobalSecondaryIndex titleIndex = new GlobalSecondaryIndex().withIndexName("TitleIndex") - .withProvisionedThroughput(ptIndex) - .withKeySchema(new KeySchemaElement().withAttributeName("Title").withKeyType(KeyType.HASH), // Partition + .withProvisionedThroughput(ptIndex) + .withKeySchema(new KeySchemaElement().withAttributeName("Title").withKeyType(KeyType.HASH), // Partition + // key + new KeySchemaElement().withAttributeName("IssueId").withKeyType(KeyType.RANGE)) // Sort // key - new KeySchemaElement().withAttributeName("IssueId").withKeyType(KeyType.RANGE)) // Sort - // key - .withProjection(new Projection().withProjectionType("KEYS_ONLY")); + .withProjection(new Projection().withProjectionType("KEYS_ONLY")); // DueDateIndex GlobalSecondaryIndex dueDateIndex = new GlobalSecondaryIndex().withIndexName("DueDateIndex") - .withProvisionedThroughput(ptIndex) - .withKeySchema(new KeySchemaElement().withAttributeName("DueDate").withKeyType(KeyType.HASH)) // Partition - // key - .withProjection(new Projection().withProjectionType("ALL")); + .withProvisionedThroughput(ptIndex) + .withKeySchema(new KeySchemaElement().withAttributeName("DueDate").withKeyType(KeyType.HASH)) // Partition + // key + .withProjection(new Projection().withProjectionType("ALL")); CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName) - .withProvisionedThroughput( - new ProvisionedThroughput().withReadCapacityUnits((long) 1).withWriteCapacityUnits((long) 1)) - .withAttributeDefinitions(attributeDefinitions).withKeySchema(tableKeySchema) - .withGlobalSecondaryIndexes(createDateIndex, titleIndex, dueDateIndex); + .withProvisionedThroughput( + new ProvisionedThroughput().withReadCapacityUnits((long) 1).withWriteCapacityUnits((long) 1)) + .withAttributeDefinitions(attributeDefinitions).withKeySchema(tableKeySchema) + .withGlobalSecondaryIndexes(createDateIndex, titleIndex, dueDateIndex); System.out.println("Creating table " + tableName + "..."); dynamoDB.createTable(createTableRequest); @@ -128,8 +107,7 @@ public static void createTable() { try { Table table = dynamoDB.getTable(tableName); table.waitForActive(); - } - catch (InterruptedException e) { + } catch (InterruptedException e) { e.printStackTrace(); } } @@ -150,22 +128,20 @@ public static void queryIndex(String indexName) { if (indexName == "CreateDateIndex") { System.out.println("Issues filed on 2013-11-01"); querySpec.withKeyConditionExpression("CreateDate = :v_date and begins_with(IssueId, :v_issue)") - .withValueMap(new ValueMap().withString(":v_date", "2013-11-01").withString(":v_issue", "A-")); + .withValueMap(new ValueMap().withString(":v_date", "2013-11-01").withString(":v_issue", "A-")); items = index.query(querySpec); - } - else if (indexName == "TitleIndex") { + } else if (indexName == "TitleIndex") { System.out.println("Compilation errors"); querySpec.withKeyConditionExpression("Title = :v_title and begins_with(IssueId, :v_issue)") - .withValueMap(new ValueMap().withString(":v_title", "Compilation error").withString(":v_issue", "A-")); + .withValueMap( + new ValueMap().withString(":v_title", "Compilation error").withString(":v_issue", "A-")); items = index.query(querySpec); - } - else if (indexName == "DueDateIndex") { + } else if (indexName == "DueDateIndex") { System.out.println("Items that are due on 2013-11-30"); querySpec.withKeyConditionExpression("DueDate = :v_date") - .withValueMap(new ValueMap().withString(":v_date", "2013-11-30")); + .withValueMap(new ValueMap().withString(":v_date", "2013-11-30")); items = index.query(querySpec); - } - else { + } else { System.out.println("\nNo valid index name provided"); return; } @@ -191,8 +167,7 @@ public static void deleteTable(String tableName) { System.out.println("Waiting for " + tableName + " to be deleted..."); try { table.waitForDelete(); - } - catch (InterruptedException e) { + } catch (InterruptedException e) { e.printStackTrace(); } } @@ -207,37 +182,37 @@ public static void loadData() { // Priority, Status putItem("A-101", "Compilation error", "Can't compile Project X - bad version number. What does this mean?", - "2013-11-01", "2013-11-02", "2013-11-10", 1, "Assigned"); + "2013-11-01", "2013-11-02", "2013-11-10", 1, "Assigned"); putItem("A-102", "Can't read data file", "The main data file is missing, or the permissions are incorrect", - "2013-11-01", "2013-11-04", "2013-11-30", 2, "In progress"); + "2013-11-01", "2013-11-04", "2013-11-30", 2, "In progress"); putItem("A-103", "Test failure", "Functional test of Project X produces errors", "2013-11-01", "2013-11-02", - "2013-11-10", 1, "In progress"); + "2013-11-10", 1, "In progress"); putItem("A-104", "Compilation error", "Variable 'messageCount' was not initialized.", "2013-11-15", - "2013-11-16", "2013-11-30", 3, "Assigned"); + "2013-11-16", "2013-11-30", 3, "Assigned"); putItem("A-105", "Network issue", "Can't ping IP address 127.0.0.1. Please fix this.", "2013-11-15", - "2013-11-16", "2013-11-19", 5, "Assigned"); + "2013-11-16", "2013-11-19", 5, "Assigned"); } public static void putItem( - String issueId, String title, String description, String createDate, String lastUpdateDate, String dueDate, - Integer priority, String status) { + String issueId, String title, String description, String createDate, String lastUpdateDate, String dueDate, + Integer priority, String status) { Table table = dynamoDB.getTable(tableName); Item item = new Item().withPrimaryKey("IssueId", issueId).withString("Title", title) - .withString("Description", description).withString("CreateDate", createDate) - .withString("LastUpdateDate", lastUpdateDate).withString("DueDate", dueDate) - .withNumber("Priority", priority).withString("Status", status); + .withString("Description", description).withString("CreateDate", createDate) + .withString("LastUpdateDate", lastUpdateDate).withString("DueDate", dueDate) + .withNumber("Priority", priority).withString("Status", status); table.putItem(item); } } -// snippet-end:[dynamodb.java.codeexample.DocumentAPIGlobalSecondaryIndexExample] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.DocumentAPIGlobalSecondaryIndexExample] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIItemBinaryExample.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIItemBinaryExample.java index 7b102880930..e18f678c0f9 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIItemBinaryExample.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIItemBinaryExample.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.DocumentAPIItemBinaryExample] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.DocumentAPIItemBinaryExample] package com.amazonaws.codesamples.document; @@ -68,8 +47,7 @@ public static void main(String[] args) throws IOException { // clean up by deleting the item deleteItem(threadId, replyDateTime); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Error running the binary attribute type example: " + e); e.printStackTrace(System.err); } @@ -86,8 +64,8 @@ public static void createItem(String threadId, String replyDateTime) throws IOEx ByteBuffer compressedMessage = compressString(messageInput.toString()); table.putItem(new Item().withPrimaryKey("Id", threadId).withString("ReplyDateTime", replyDateTime) - .withString("Message", "Long message follows").withBinary("ExtendedMessage", compressedMessage) - .withString("PostedBy", "User A")); + .withString("Message", "Long message follows").withBinary("ExtendedMessage", compressedMessage) + .withString("PostedBy", "User A")); } public static void retrieveItem(String threadId, String replyDateTime) throws IOException { @@ -95,7 +73,7 @@ public static void retrieveItem(String threadId, String replyDateTime) throws IO Table table = dynamoDB.getTable(tableName); GetItemSpec spec = new GetItemSpec().withPrimaryKey("Id", threadId, "ReplyDateTime", replyDateTime) - .withConsistentRead(true); + .withConsistentRead(true); Item item = table.getItem(spec); @@ -103,8 +81,9 @@ public static void retrieveItem(String threadId, String replyDateTime) throws IO String uncompressed = uncompressString(ByteBuffer.wrap(item.getBinary("ExtendedMessage"))); System.out.println("Reply message:\n" + " Id: " + item.getString("Id") + "\n" + " ReplyDateTime: " - + item.getString("ReplyDateTime") + "\n" + " PostedBy: " + item.getString("PostedBy") + "\n" + " Message: " - + item.getString("Message") + "\n" + " ExtendedMessage (uncompressed): " + uncompressed + "\n"); + + item.getString("ReplyDateTime") + "\n" + " PostedBy: " + item.getString("PostedBy") + "\n" + + " Message: " + + item.getString("Message") + "\n" + " ExtendedMessage (uncompressed): " + uncompressed + "\n"); } public static void deleteItem(String threadId, String replyDateTime) { @@ -162,4 +141,4 @@ private static String uncompressString(ByteBuffer input) throws IOException { } } -// snippet-end:[dynamodb.java.codeexample.DocumentAPIItemBinaryExample] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.DocumentAPIItemBinaryExample] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIItemCRUDExample.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIItemCRUDExample.java index 56e9086822e..e0fb3d38c5c 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIItemCRUDExample.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIItemCRUDExample.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.DocumentAPIItemCRUDExample] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.DocumentAPIItemCRUDExample] package com.amazonaws.codesamples.document; @@ -74,21 +53,20 @@ private static void createItems() { try { Item item = new Item().withPrimaryKey("Id", 120).withString("Title", "Book 120 Title") - .withString("ISBN", "120-1111111111") - .withStringSet("Authors", new HashSet(Arrays.asList("Author12", "Author22"))) - .withNumber("Price", 20).withString("Dimensions", "8.5x11.0x.75").withNumber("PageCount", 500) - .withBoolean("InPublication", false).withString("ProductCategory", "Book"); + .withString("ISBN", "120-1111111111") + .withStringSet("Authors", new HashSet(Arrays.asList("Author12", "Author22"))) + .withNumber("Price", 20).withString("Dimensions", "8.5x11.0x.75").withNumber("PageCount", 500) + .withBoolean("InPublication", false).withString("ProductCategory", "Book"); table.putItem(item); item = new Item().withPrimaryKey("Id", 121).withString("Title", "Book 121 Title") - .withString("ISBN", "121-1111111111") - .withStringSet("Authors", new HashSet(Arrays.asList("Author21", "Author 22"))) - .withNumber("Price", 20).withString("Dimensions", "8.5x11.0x.75").withNumber("PageCount", 500) - .withBoolean("InPublication", true).withString("ProductCategory", "Book"); + .withString("ISBN", "121-1111111111") + .withStringSet("Authors", new HashSet(Arrays.asList("Author21", "Author 22"))) + .withNumber("Price", 20).withString("Dimensions", "8.5x11.0x.75").withNumber("PageCount", 500) + .withBoolean("InPublication", true).withString("ProductCategory", "Book"); table.putItem(item); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Create items failed."); System.err.println(e.getMessage()); @@ -105,8 +83,7 @@ private static void retrieveItem() { System.out.println("Printing item after retrieving it...."); System.out.println(item.toJSONPretty()); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("GetItem failed."); System.err.println(e.getMessage()); } @@ -119,8 +96,9 @@ private static void updateAddNewAttribute() { try { UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("Id", 121) - .withUpdateExpression("set #na = :val1").withNameMap(new NameMap().with("#na", "NewAttribute")) - .withValueMap(new ValueMap().withString(":val1", "Some value")).withReturnValues(ReturnValue.ALL_NEW); + .withUpdateExpression("set #na = :val1").withNameMap(new NameMap().with("#na", "NewAttribute")) + .withValueMap(new ValueMap().withString(":val1", "Some value")) + .withReturnValues(ReturnValue.ALL_NEW); UpdateItemOutcome outcome = table.updateItem(updateItemSpec); @@ -128,8 +106,7 @@ private static void updateAddNewAttribute() { System.out.println("Printing item after adding new attribute..."); System.out.println(outcome.getItem().toJSONPretty()); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Failed to add new attribute in " + tableName); System.err.println(e.getMessage()); } @@ -142,11 +119,12 @@ private static void updateMultipleAttributes() { try { UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("Id", 120) - .withUpdateExpression("add #a :val1 set #na=:val2") - .withNameMap(new NameMap().with("#a", "Authors").with("#na", "NewAttribute")) - .withValueMap( - new ValueMap().withStringSet(":val1", "Author YY", "Author ZZ").withString(":val2", "someValue")) - .withReturnValues(ReturnValue.ALL_NEW); + .withUpdateExpression("add #a :val1 set #na=:val2") + .withNameMap(new NameMap().with("#a", "Authors").with("#na", "NewAttribute")) + .withValueMap( + new ValueMap().withStringSet(":val1", "Author YY", "Author ZZ").withString(":val2", + "someValue")) + .withReturnValues(ReturnValue.ALL_NEW); UpdateItemOutcome outcome = table.updateItem(updateItemSpec); @@ -154,8 +132,7 @@ private static void updateMultipleAttributes() { System.out.println("Printing item after multiple attribute update..."); System.out.println(outcome.getItem().toJSONPretty()); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Failed to update multiple attributes in " + tableName); System.err.println(e.getMessage()); @@ -172,9 +149,9 @@ private static void updateExistingAttributeConditionally() { // 20.00) UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("Id", 120) - .withReturnValues(ReturnValue.ALL_NEW).withUpdateExpression("set #p = :val1") - .withConditionExpression("#p = :val2").withNameMap(new NameMap().with("#p", "Price")) - .withValueMap(new ValueMap().withNumber(":val1", 25).withNumber(":val2", 20)); + .withReturnValues(ReturnValue.ALL_NEW).withUpdateExpression("set #p = :val1") + .withConditionExpression("#p = :val2").withNameMap(new NameMap().with("#p", "Price")) + .withValueMap(new ValueMap().withNumber(":val1", 25).withNumber(":val2", 20)); UpdateItemOutcome outcome = table.updateItem(updateItemSpec); @@ -182,8 +159,7 @@ private static void updateExistingAttributeConditionally() { System.out.println("Printing item after conditional update to new attribute..."); System.out.println(outcome.getItem().toJSONPretty()); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Error updating item in " + tableName); System.err.println(e.getMessage()); } @@ -196,8 +172,8 @@ private static void deleteItem() { try { DeleteItemSpec deleteItemSpec = new DeleteItemSpec().withPrimaryKey("Id", 120) - .withConditionExpression("#ip = :val").withNameMap(new NameMap().with("#ip", "InPublication")) - .withValueMap(new ValueMap().withBoolean(":val", false)).withReturnValues(ReturnValue.ALL_OLD); + .withConditionExpression("#ip = :val").withNameMap(new NameMap().with("#ip", "InPublication")) + .withValueMap(new ValueMap().withBoolean(":val", false)).withReturnValues(ReturnValue.ALL_OLD); DeleteItemOutcome outcome = table.deleteItem(deleteItemSpec); @@ -205,12 +181,11 @@ private static void deleteItem() { System.out.println("Printing item that was deleted..."); System.out.println(outcome.getItem().toJSONPretty()); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Error deleting item in " + tableName); System.err.println(e.getMessage()); } } } -// snippet-end:[dynamodb.java.codeexample.DocumentAPIItemCRUDExample] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.DocumentAPIItemCRUDExample] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPILocalSecondaryIndexExample.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPILocalSecondaryIndexExample.java index 614279b6caf..3cdd68aa713 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPILocalSecondaryIndexExample.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPILocalSecondaryIndexExample.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.DocumentAPILocalSecondaryIndexExample] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.DocumentAPILocalSecondaryIndexExample] package com.amazonaws.codesamples.document; @@ -53,284 +32,298 @@ public class DocumentAPILocalSecondaryIndexExample { - static AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build(); - static DynamoDB dynamoDB = new DynamoDB(client); + static AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build(); + static DynamoDB dynamoDB = new DynamoDB(client); - public static String tableName = "CustomerOrders"; + public static String tableName = "CustomerOrders"; - public static void main(String[] args) throws Exception { + public static void main(String[] args) throws Exception { - createTable(); - loadData(); + createTable(); + loadData(); - query(null); - query("IsOpenIndex"); - query("OrderCreationDateIndex"); + query(null); + query("IsOpenIndex"); + query("OrderCreationDateIndex"); - deleteTable(tableName); + deleteTable(tableName); - } + } - public static void createTable() { + public static void createTable() { - CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName) - .withProvisionedThroughput( - new ProvisionedThroughput().withReadCapacityUnits((long) 1).withWriteCapacityUnits((long) 1)); + CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName) + .withProvisionedThroughput( + new ProvisionedThroughput().withReadCapacityUnits((long) 1) + .withWriteCapacityUnits((long) 1)); - // Attribute definitions for table partition and sort keys - ArrayList attributeDefinitions = new ArrayList(); - attributeDefinitions.add(new AttributeDefinition().withAttributeName("CustomerId").withAttributeType("S")); - attributeDefinitions.add(new AttributeDefinition().withAttributeName("OrderId").withAttributeType("N")); + // Attribute definitions for table partition and sort keys + ArrayList attributeDefinitions = new ArrayList(); + attributeDefinitions + .add(new AttributeDefinition().withAttributeName("CustomerId").withAttributeType("S")); + attributeDefinitions.add(new AttributeDefinition().withAttributeName("OrderId").withAttributeType("N")); - // Attribute definition for index primary key attributes - attributeDefinitions - .add(new AttributeDefinition().withAttributeName("OrderCreationDate").withAttributeType("N")); - attributeDefinitions.add(new AttributeDefinition().withAttributeName("IsOpen").withAttributeType("N")); + // Attribute definition for index primary key attributes + attributeDefinitions + .add(new AttributeDefinition().withAttributeName("OrderCreationDate") + .withAttributeType("N")); + attributeDefinitions.add(new AttributeDefinition().withAttributeName("IsOpen").withAttributeType("N")); - createTableRequest.setAttributeDefinitions(attributeDefinitions); + createTableRequest.setAttributeDefinitions(attributeDefinitions); - // Key schema for table - ArrayList tableKeySchema = new ArrayList(); - tableKeySchema.add(new KeySchemaElement().withAttributeName("CustomerId").withKeyType(KeyType.HASH)); // Partition - // key - tableKeySchema.add(new KeySchemaElement().withAttributeName("OrderId").withKeyType(KeyType.RANGE)); // Sort - // key + // Key schema for table + ArrayList tableKeySchema = new ArrayList(); + tableKeySchema.add(new KeySchemaElement().withAttributeName("CustomerId").withKeyType(KeyType.HASH)); // Partition + // key + tableKeySchema.add(new KeySchemaElement().withAttributeName("OrderId").withKeyType(KeyType.RANGE)); // Sort + // key - createTableRequest.setKeySchema(tableKeySchema); + createTableRequest.setKeySchema(tableKeySchema); - ArrayList localSecondaryIndexes = new ArrayList(); + ArrayList localSecondaryIndexes = new ArrayList(); - // OrderCreationDateIndex - LocalSecondaryIndex orderCreationDateIndex = new LocalSecondaryIndex().withIndexName("OrderCreationDateIndex"); + // OrderCreationDateIndex + LocalSecondaryIndex orderCreationDateIndex = new LocalSecondaryIndex() + .withIndexName("OrderCreationDateIndex"); - // Key schema for OrderCreationDateIndex - ArrayList indexKeySchema = new ArrayList(); - indexKeySchema.add(new KeySchemaElement().withAttributeName("CustomerId").withKeyType(KeyType.HASH)); // Partition - // key - indexKeySchema.add(new KeySchemaElement().withAttributeName("OrderCreationDate").withKeyType(KeyType.RANGE)); // Sort + // Key schema for OrderCreationDateIndex + ArrayList indexKeySchema = new ArrayList(); + indexKeySchema.add(new KeySchemaElement().withAttributeName("CustomerId").withKeyType(KeyType.HASH)); // Partition // key + indexKeySchema.add(new KeySchemaElement().withAttributeName("OrderCreationDate") + .withKeyType(KeyType.RANGE)); // Sort + // key - orderCreationDateIndex.setKeySchema(indexKeySchema); + orderCreationDateIndex.setKeySchema(indexKeySchema); - // Projection (with list of projected attributes) for - // OrderCreationDateIndex - Projection projection = new Projection().withProjectionType(ProjectionType.INCLUDE); - ArrayList nonKeyAttributes = new ArrayList(); - nonKeyAttributes.add("ProductCategory"); - nonKeyAttributes.add("ProductName"); - projection.setNonKeyAttributes(nonKeyAttributes); + // Projection (with list of projected attributes) for + // OrderCreationDateIndex + Projection projection = new Projection().withProjectionType(ProjectionType.INCLUDE); + ArrayList nonKeyAttributes = new ArrayList(); + nonKeyAttributes.add("ProductCategory"); + nonKeyAttributes.add("ProductName"); + projection.setNonKeyAttributes(nonKeyAttributes); - orderCreationDateIndex.setProjection(projection); + orderCreationDateIndex.setProjection(projection); - localSecondaryIndexes.add(orderCreationDateIndex); + localSecondaryIndexes.add(orderCreationDateIndex); - // IsOpenIndex - LocalSecondaryIndex isOpenIndex = new LocalSecondaryIndex().withIndexName("IsOpenIndex"); + // IsOpenIndex + LocalSecondaryIndex isOpenIndex = new LocalSecondaryIndex().withIndexName("IsOpenIndex"); - // Key schema for IsOpenIndex - indexKeySchema = new ArrayList(); - indexKeySchema.add(new KeySchemaElement().withAttributeName("CustomerId").withKeyType(KeyType.HASH)); // Partition - // key - indexKeySchema.add(new KeySchemaElement().withAttributeName("IsOpen").withKeyType(KeyType.RANGE)); // Sort - // key + // Key schema for IsOpenIndex + indexKeySchema = new ArrayList(); + indexKeySchema.add(new KeySchemaElement().withAttributeName("CustomerId").withKeyType(KeyType.HASH)); // Partition + // key + indexKeySchema.add(new KeySchemaElement().withAttributeName("IsOpen").withKeyType(KeyType.RANGE)); // Sort + // key - // Projection (all attributes) for IsOpenIndex - projection = new Projection().withProjectionType(ProjectionType.ALL); + // Projection (all attributes) for IsOpenIndex + projection = new Projection().withProjectionType(ProjectionType.ALL); - isOpenIndex.setKeySchema(indexKeySchema); - isOpenIndex.setProjection(projection); + isOpenIndex.setKeySchema(indexKeySchema); + isOpenIndex.setProjection(projection); - localSecondaryIndexes.add(isOpenIndex); + localSecondaryIndexes.add(isOpenIndex); - // Add index definitions to CreateTable request - createTableRequest.setLocalSecondaryIndexes(localSecondaryIndexes); + // Add index definitions to CreateTable request + createTableRequest.setLocalSecondaryIndexes(localSecondaryIndexes); - System.out.println("Creating table " + tableName + "..."); - System.out.println(dynamoDB.createTable(createTableRequest)); + System.out.println("Creating table " + tableName + "..."); + System.out.println(dynamoDB.createTable(createTableRequest)); - // Wait for table to become active - System.out.println("Waiting for " + tableName + " to become ACTIVE..."); - try { - Table table = dynamoDB.getTable(tableName); - table.waitForActive(); - } - catch (InterruptedException e) { - e.printStackTrace(); + // Wait for table to become active + System.out.println("Waiting for " + tableName + " to become ACTIVE..."); + try { + Table table = dynamoDB.getTable(tableName); + table.waitForActive(); + } catch (InterruptedException e) { + e.printStackTrace(); + } } - } - public static void query(String indexName) { + public static void query(String indexName) { - Table table = dynamoDB.getTable(tableName); + Table table = dynamoDB.getTable(tableName); - System.out.println("\n***********************************************************\n"); - System.out.println("Querying table " + tableName + "..."); + System.out.println("\n***********************************************************\n"); + System.out.println("Querying table " + tableName + "..."); - QuerySpec querySpec = new QuerySpec().withConsistentRead(true).withScanIndexForward(true) - .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL); + QuerySpec querySpec = new QuerySpec().withConsistentRead(true).withScanIndexForward(true) + .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL); - if (indexName == "IsOpenIndex") { + if (indexName == "IsOpenIndex") { - System.out.println("\nUsing index: '" + indexName + "': Bob's orders that are open."); - System.out.println("Only a user-specified list of attributes are returned\n"); - Index index = table.getIndex(indexName); + System.out.println("\nUsing index: '" + indexName + "': Bob's orders that are open."); + System.out.println("Only a user-specified list of attributes are returned\n"); + Index index = table.getIndex(indexName); - querySpec.withKeyConditionExpression("CustomerId = :v_custid and IsOpen = :v_isopen") - .withValueMap(new ValueMap().withString(":v_custid", "bob@example.com").withNumber(":v_isopen", 1)); + querySpec.withKeyConditionExpression("CustomerId = :v_custid and IsOpen = :v_isopen") + .withValueMap(new ValueMap().withString(":v_custid", "bob@example.com") + .withNumber(":v_isopen", 1)); - querySpec.withProjectionExpression("OrderCreationDate, ProductCategory, ProductName, OrderStatus"); + querySpec.withProjectionExpression( + "OrderCreationDate, ProductCategory, ProductName, OrderStatus"); - ItemCollection items = index.query(querySpec); - Iterator iterator = items.iterator(); + ItemCollection items = index.query(querySpec); + Iterator iterator = items.iterator(); - System.out.println("Query: printing results..."); + System.out.println("Query: printing results..."); - while (iterator.hasNext()) { - System.out.println(iterator.next().toJSONPretty()); - } + while (iterator.hasNext()) { + System.out.println(iterator.next().toJSONPretty()); + } - } - else if (indexName == "OrderCreationDateIndex") { - System.out.println("\nUsing index: '" + indexName + "': Bob's orders that were placed after 01/31/2015."); - System.out.println("Only the projected attributes are returned\n"); - Index index = table.getIndex(indexName); + } else if (indexName == "OrderCreationDateIndex") { + System.out.println("\nUsing index: '" + indexName + + "': Bob's orders that were placed after 01/31/2015."); + System.out.println("Only the projected attributes are returned\n"); + Index index = table.getIndex(indexName); - querySpec.withKeyConditionExpression("CustomerId = :v_custid and OrderCreationDate >= :v_orddate") - .withValueMap( - new ValueMap().withString(":v_custid", "bob@example.com").withNumber(":v_orddate", 20150131)); + querySpec.withKeyConditionExpression( + "CustomerId = :v_custid and OrderCreationDate >= :v_orddate") + .withValueMap( + new ValueMap().withString(":v_custid", "bob@example.com") + .withNumber(":v_orddate", + 20150131)); - querySpec.withSelect(Select.ALL_PROJECTED_ATTRIBUTES); + querySpec.withSelect(Select.ALL_PROJECTED_ATTRIBUTES); - ItemCollection items = index.query(querySpec); - Iterator iterator = items.iterator(); + ItemCollection items = index.query(querySpec); + Iterator iterator = items.iterator(); - System.out.println("Query: printing results..."); + System.out.println("Query: printing results..."); - while (iterator.hasNext()) { - System.out.println(iterator.next().toJSONPretty()); - } + while (iterator.hasNext()) { + System.out.println(iterator.next().toJSONPretty()); + } - } - else { - System.out.println("\nNo index: All of Bob's orders, by OrderId:\n"); + } else { + System.out.println("\nNo index: All of Bob's orders, by OrderId:\n"); - querySpec.withKeyConditionExpression("CustomerId = :v_custid") - .withValueMap(new ValueMap().withString(":v_custid", "bob@example.com")); + querySpec.withKeyConditionExpression("CustomerId = :v_custid") + .withValueMap(new ValueMap().withString(":v_custid", "bob@example.com")); - ItemCollection items = table.query(querySpec); - Iterator iterator = items.iterator(); + ItemCollection items = table.query(querySpec); + Iterator iterator = items.iterator(); - System.out.println("Query: printing results..."); + System.out.println("Query: printing results..."); - while (iterator.hasNext()) { - System.out.println(iterator.next().toJSONPretty()); - } + while (iterator.hasNext()) { + System.out.println(iterator.next().toJSONPretty()); + } - } + } - } + } - public static void deleteTable(String tableName) { + public static void deleteTable(String tableName) { - Table table = dynamoDB.getTable(tableName); - System.out.println("Deleting table " + tableName + "..."); - table.delete(); + Table table = dynamoDB.getTable(tableName); + System.out.println("Deleting table " + tableName + "..."); + table.delete(); - // Wait for table to be deleted - System.out.println("Waiting for " + tableName + " to be deleted..."); - try { - table.waitForDelete(); - } - catch (InterruptedException e) { - e.printStackTrace(); + // Wait for table to be deleted + System.out.println("Waiting for " + tableName + " to be deleted..."); + try { + table.waitForDelete(); + } catch (InterruptedException e) { + e.printStackTrace(); + } } - } - public static void loadData() { + public static void loadData() { - Table table = dynamoDB.getTable(tableName); + Table table = dynamoDB.getTable(tableName); - System.out.println("Loading data into table " + tableName + "..."); + System.out.println("Loading data into table " + tableName + "..."); - Item item = new Item().withPrimaryKey("CustomerId", "alice@example.com").withNumber("OrderId", 1) - .withNumber("IsOpen", 1).withNumber("OrderCreationDate", 20150101).withString("ProductCategory", "Book") - .withString("ProductName", "The Great Outdoors").withString("OrderStatus", "PACKING ITEMS"); - // no ShipmentTrackingId attribute + Item item = new Item().withPrimaryKey("CustomerId", "alice@example.com").withNumber("OrderId", 1) + .withNumber("IsOpen", 1).withNumber("OrderCreationDate", 20150101) + .withString("ProductCategory", "Book") + .withString("ProductName", "The Great Outdoors") + .withString("OrderStatus", "PACKING ITEMS"); + // no ShipmentTrackingId attribute - PutItemOutcome putItemOutcome = table.putItem(item); + PutItemOutcome putItemOutcome = table.putItem(item); - item = new Item().withPrimaryKey("CustomerId", "alice@example.com").withNumber("OrderId", 2) - .withNumber("IsOpen", 1).withNumber("OrderCreationDate", 20150221).withString("ProductCategory", "Bike") - .withString("ProductName", "Super Mountain").withString("OrderStatus", "ORDER RECEIVED"); - // no ShipmentTrackingId attribute + item = new Item().withPrimaryKey("CustomerId", "alice@example.com").withNumber("OrderId", 2) + .withNumber("IsOpen", 1).withNumber("OrderCreationDate", 20150221) + .withString("ProductCategory", "Bike") + .withString("ProductName", "Super Mountain") + .withString("OrderStatus", "ORDER RECEIVED"); + // no ShipmentTrackingId attribute - putItemOutcome = table.putItem(item); + putItemOutcome = table.putItem(item); - item = new Item().withPrimaryKey("CustomerId", "alice@example.com").withNumber("OrderId", 3) - // no IsOpen attribute - .withNumber("OrderCreationDate", 20150304).withString("ProductCategory", "Music") - .withString("ProductName", "A Quiet Interlude").withString("OrderStatus", "IN TRANSIT") - .withString("ShipmentTrackingId", "176493"); + item = new Item().withPrimaryKey("CustomerId", "alice@example.com").withNumber("OrderId", 3) + // no IsOpen attribute + .withNumber("OrderCreationDate", 20150304).withString("ProductCategory", "Music") + .withString("ProductName", "A Quiet Interlude").withString("OrderStatus", "IN TRANSIT") + .withString("ShipmentTrackingId", "176493"); - putItemOutcome = table.putItem(item); + putItemOutcome = table.putItem(item); - item = new Item().withPrimaryKey("CustomerId", "bob@example.com").withNumber("OrderId", 1) - // no IsOpen attribute - .withNumber("OrderCreationDate", 20150111).withString("ProductCategory", "Movie") - .withString("ProductName", "Calm Before The Storm").withString("OrderStatus", "SHIPPING DELAY") - .withString("ShipmentTrackingId", "859323"); + item = new Item().withPrimaryKey("CustomerId", "bob@example.com").withNumber("OrderId", 1) + // no IsOpen attribute + .withNumber("OrderCreationDate", 20150111).withString("ProductCategory", "Movie") + .withString("ProductName", "Calm Before The Storm") + .withString("OrderStatus", "SHIPPING DELAY") + .withString("ShipmentTrackingId", "859323"); - putItemOutcome = table.putItem(item); + putItemOutcome = table.putItem(item); - item = new Item().withPrimaryKey("CustomerId", "bob@example.com").withNumber("OrderId", 2) - // no IsOpen attribute - .withNumber("OrderCreationDate", 20150124).withString("ProductCategory", "Music") - .withString("ProductName", "E-Z Listening").withString("OrderStatus", "DELIVERED") - .withString("ShipmentTrackingId", "756943"); + item = new Item().withPrimaryKey("CustomerId", "bob@example.com").withNumber("OrderId", 2) + // no IsOpen attribute + .withNumber("OrderCreationDate", 20150124).withString("ProductCategory", "Music") + .withString("ProductName", "E-Z Listening").withString("OrderStatus", "DELIVERED") + .withString("ShipmentTrackingId", "756943"); - putItemOutcome = table.putItem(item); + putItemOutcome = table.putItem(item); - item = new Item().withPrimaryKey("CustomerId", "bob@example.com").withNumber("OrderId", 3) - // no IsOpen attribute - .withNumber("OrderCreationDate", 20150221).withString("ProductCategory", "Music") - .withString("ProductName", "Symphony 9").withString("OrderStatus", "DELIVERED") - .withString("ShipmentTrackingId", "645193"); + item = new Item().withPrimaryKey("CustomerId", "bob@example.com").withNumber("OrderId", 3) + // no IsOpen attribute + .withNumber("OrderCreationDate", 20150221).withString("ProductCategory", "Music") + .withString("ProductName", "Symphony 9").withString("OrderStatus", "DELIVERED") + .withString("ShipmentTrackingId", "645193"); - putItemOutcome = table.putItem(item); + putItemOutcome = table.putItem(item); - item = new Item().withPrimaryKey("CustomerId", "bob@example.com").withNumber("OrderId", 4) - .withNumber("IsOpen", 1).withNumber("OrderCreationDate", 20150222).withString("ProductCategory", "Hardware") - .withString("ProductName", "Extra Heavy Hammer").withString("OrderStatus", "PACKING ITEMS"); - // no ShipmentTrackingId attribute + item = new Item().withPrimaryKey("CustomerId", "bob@example.com").withNumber("OrderId", 4) + .withNumber("IsOpen", 1).withNumber("OrderCreationDate", 20150222) + .withString("ProductCategory", "Hardware") + .withString("ProductName", "Extra Heavy Hammer") + .withString("OrderStatus", "PACKING ITEMS"); + // no ShipmentTrackingId attribute - putItemOutcome = table.putItem(item); + putItemOutcome = table.putItem(item); - item = new Item().withPrimaryKey("CustomerId", "bob@example.com").withNumber("OrderId", 5) - /* no IsOpen attribute */ - .withNumber("OrderCreationDate", 20150309).withString("ProductCategory", "Book") - .withString("ProductName", "How To Cook").withString("OrderStatus", "IN TRANSIT") - .withString("ShipmentTrackingId", "440185"); + item = new Item().withPrimaryKey("CustomerId", "bob@example.com").withNumber("OrderId", 5) + /* no IsOpen attribute */ + .withNumber("OrderCreationDate", 20150309).withString("ProductCategory", "Book") + .withString("ProductName", "How To Cook").withString("OrderStatus", "IN TRANSIT") + .withString("ShipmentTrackingId", "440185"); - putItemOutcome = table.putItem(item); + putItemOutcome = table.putItem(item); - item = new Item().withPrimaryKey("CustomerId", "bob@example.com").withNumber("OrderId", 6) - // no IsOpen attribute - .withNumber("OrderCreationDate", 20150318).withString("ProductCategory", "Luggage") - .withString("ProductName", "Really Big Suitcase").withString("OrderStatus", "DELIVERED") - .withString("ShipmentTrackingId", "893927"); + item = new Item().withPrimaryKey("CustomerId", "bob@example.com").withNumber("OrderId", 6) + // no IsOpen attribute + .withNumber("OrderCreationDate", 20150318).withString("ProductCategory", "Luggage") + .withString("ProductName", "Really Big Suitcase").withString("OrderStatus", "DELIVERED") + .withString("ShipmentTrackingId", "893927"); - putItemOutcome = table.putItem(item); + putItemOutcome = table.putItem(item); - item = new Item().withPrimaryKey("CustomerId", "bob@example.com").withNumber("OrderId", 7) - /* no IsOpen attribute */ - .withNumber("OrderCreationDate", 20150324).withString("ProductCategory", "Golf") - .withString("ProductName", "PGA Pro II").withString("OrderStatus", "OUT FOR DELIVERY") - .withString("ShipmentTrackingId", "383283"); + item = new Item().withPrimaryKey("CustomerId", "bob@example.com").withNumber("OrderId", 7) + /* no IsOpen attribute */ + .withNumber("OrderCreationDate", 20150324).withString("ProductCategory", "Golf") + .withString("ProductName", "PGA Pro II").withString("OrderStatus", "OUT FOR DELIVERY") + .withString("ShipmentTrackingId", "383283"); - putItemOutcome = table.putItem(item); - assert putItemOutcome != null; - } + putItemOutcome = table.putItem(item); + assert putItemOutcome != null; + } } -// snippet-end:[dynamodb.java.codeexample.DocumentAPILocalSecondaryIndexExample] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.DocumentAPILocalSecondaryIndexExample] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIParallelScan.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIParallelScan.java index 7e9f0d1b47c..b5310b72329 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIParallelScan.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIParallelScan.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.DocumentAPIParallelScan] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.DocumentAPIParallelScan] package com.amazonaws.codesamples.document; @@ -78,15 +57,14 @@ public static void main(String[] args) throws Exception { // Scan the table using multiple threads parallelScan(parallelScanTestTableName, scanItemLimit, parallelScanThreads); - } - catch (AmazonServiceException ase) { + } catch (AmazonServiceException ase) { System.err.println(ase.getMessage()); } } private static void parallelScan(String tableName, int itemLimit, int numberOfThreads) { System.out.println( - "Scanning " + tableName + " using " + numberOfThreads + " threads " + itemLimit + " items at a time"); + "Scanning " + tableName + " using " + numberOfThreads + " threads " + itemLimit + " items at a time"); ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads); // Divide DynamoDB table into logical segments @@ -130,14 +108,14 @@ public ScanSegmentTask(String tableName, int itemLimit, int totalSegments, int s @Override public void run() { System.out.println("Scanning " + tableName + " segment " + segment + " out of " + totalSegments - + " segments " + itemLimit + " items at a time..."); + + " segments " + itemLimit + " items at a time..."); int totalScannedItemCount = 0; Table table = dynamoDB.getTable(tableName); try { ScanSpec spec = new ScanSpec().withMaxResultSize(itemLimit).withTotalSegments(totalSegments) - .withSegment(segment); + .withSegment(segment); ItemCollection items = table.scan(spec); Iterator iterator = items.iterator(); @@ -149,13 +127,11 @@ public void run() { System.out.println(currentItem.toString()); } - } - catch (Exception e) { + } catch (Exception e) { System.err.println(e.getMessage()); - } - finally { + } finally { System.out.println("Scanned " + totalScannedItemCount + " items from segment " + segment + " out of " - + totalSegments + " of " + tableName); + + totalSegments + " of " + tableName); } } } @@ -175,14 +151,13 @@ private static void uploadProduct(String tableName, int productIndex) { System.out.println("Processing record #" + productIndex); Item item = new Item().withPrimaryKey("Id", productIndex) - .withString("Title", "Book " + productIndex + " Title").withString("ISBN", "111-1111111111") - .withStringSet("Authors", new HashSet(Arrays.asList("Author1"))).withNumber("Price", 2) - .withString("Dimensions", "8.5 x 11.0 x 0.5").withNumber("PageCount", 500) - .withBoolean("InPublication", true).withString("ProductCategory", "Book"); + .withString("Title", "Book " + productIndex + " Title").withString("ISBN", "111-1111111111") + .withStringSet("Authors", new HashSet(Arrays.asList("Author1"))).withNumber("Price", 2) + .withString("Dimensions", "8.5 x 11.0 x 0.5").withNumber("PageCount", 500) + .withBoolean("InPublication", true).withString("ProductCategory", "Book"); table.putItem(item); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Failed to create item " + productIndex + " in " + tableName); System.err.println(e.getMessage()); } @@ -196,21 +171,20 @@ private static void deleteTable(String tableName) { System.out.println("Waiting for " + tableName + " to be deleted...this may take a while..."); table.waitForDelete(); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Failed to delete table " + tableName); e.printStackTrace(System.err); } } private static void createTable(String tableName, long readCapacityUnits, long writeCapacityUnits, - String partitionKeyName, String partitionKeyType) { + String partitionKeyName, String partitionKeyType) { createTable(tableName, readCapacityUnits, writeCapacityUnits, partitionKeyName, partitionKeyType, null, null); } private static void createTable(String tableName, long readCapacityUnits, long writeCapacityUnits, - String partitionKeyName, String partitionKeyType, String sortKeyName, String sortKeyType) { + String partitionKeyName, String partitionKeyType, String sortKeyName, String sortKeyType) { try { System.out.println("Creating table " + tableName); @@ -221,22 +195,22 @@ private static void createTable(String tableName, long readCapacityUnits, long w List attributeDefinitions = new ArrayList(); attributeDefinitions - .add(new AttributeDefinition().withAttributeName(partitionKeyName).withAttributeType(partitionKeyType)); + .add(new AttributeDefinition().withAttributeName(partitionKeyName) + .withAttributeType(partitionKeyType)); if (sortKeyName != null) { keySchema.add(new KeySchemaElement().withAttributeName(sortKeyName).withKeyType(KeyType.RANGE)); // Sort // key attributeDefinitions - .add(new AttributeDefinition().withAttributeName(sortKeyName).withAttributeType(sortKeyType)); + .add(new AttributeDefinition().withAttributeName(sortKeyName).withAttributeType(sortKeyType)); } Table table = dynamoDB.createTable(tableName, keySchema, attributeDefinitions, new ProvisionedThroughput() - .withReadCapacityUnits(readCapacityUnits).withWriteCapacityUnits(writeCapacityUnits)); + .withReadCapacityUnits(readCapacityUnits).withWriteCapacityUnits(writeCapacityUnits)); System.out.println("Waiting for " + tableName + " to be created...this may take a while..."); table.waitForActive(); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Failed to create table " + tableName); e.printStackTrace(System.err); } @@ -248,8 +222,7 @@ private static void shutDownExecutorService(ExecutorService executor) { if (!executor.awaitTermination(10, TimeUnit.SECONDS)) { executor.shutdownNow(); } - } - catch (InterruptedException e) { + } catch (InterruptedException e) { executor.shutdownNow(); // Preserve interrupt status @@ -258,4 +231,4 @@ private static void shutDownExecutorService(ExecutorService executor) { } } -// snippet-end:[dynamodb.java.codeexample.DocumentAPIParallelScan] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.DocumentAPIParallelScan] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIQuery.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIQuery.java index 24a9a682c5e..b78beb54039 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIQuery.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIQuery.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.DocumentAPIQuery] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.DocumentAPIQuery] package com.amazonaws.codesamples.document; @@ -67,7 +46,7 @@ private static void findRepliesForAThread(String forumName, String threadSubject String replyId = forumName + "#" + threadSubject; QuerySpec spec = new QuerySpec().withKeyConditionExpression("Id = :v_id") - .withValueMap(new ValueMap().withString(":v_id", replyId)); + .withValueMap(new ValueMap().withString(":v_id", replyId)); ItemCollection items = table.query(spec); @@ -87,7 +66,7 @@ private static void findRepliesForAThreadSpecifyOptionalLimit(String forumName, String replyId = forumName + "#" + threadSubject; QuerySpec spec = new QuerySpec().withKeyConditionExpression("Id = :v_id") - .withValueMap(new ValueMap().withString(":v_id", replyId)).withMaxPageSize(1); + .withValueMap(new ValueMap().withString(":v_id", replyId)).withMaxPageSize(1); ItemCollection items = table.query(spec); @@ -120,8 +99,8 @@ private static void findRepliesInLast15DaysWithConfig(String forumName, String t String replyId = forumName + "#" + threadSubject; QuerySpec spec = new QuerySpec().withProjectionExpression("Message, ReplyDateTime, PostedBy") - .withKeyConditionExpression("Id = :v_id and ReplyDateTime <= :v_reply_dt_tm") - .withValueMap(new ValueMap().withString(":v_id", replyId).withString(":v_reply_dt_tm", twoWeeksAgoStr)); + .withKeyConditionExpression("Id = :v_id and ReplyDateTime <= :v_reply_dt_tm") + .withValueMap(new ValueMap().withString(":v_id", replyId).withString(":v_reply_dt_tm", twoWeeksAgoStr)); ItemCollection items = table.query(spec); @@ -146,9 +125,9 @@ private static void findRepliesPostedWithinTimePeriod(String forumName, String t String replyId = forumName + "#" + threadSubject; QuerySpec spec = new QuerySpec().withProjectionExpression("Message, ReplyDateTime, PostedBy") - .withKeyConditionExpression("Id = :v_id and ReplyDateTime between :v_start_dt and :v_end_dt") - .withValueMap(new ValueMap().withString(":v_id", replyId).withString(":v_start_dt", startDate) - .withString(":v_end_dt", endDate)); + .withKeyConditionExpression("Id = :v_id and ReplyDateTime between :v_start_dt and :v_end_dt") + .withValueMap(new ValueMap().withString(":v_id", replyId).withString(":v_start_dt", startDate) + .withString(":v_end_dt", endDate)); ItemCollection items = table.query(spec); @@ -166,8 +145,8 @@ private static void findRepliesUsingAFilterExpression(String forumName, String t String replyId = forumName + "#" + threadSubject; QuerySpec spec = new QuerySpec().withProjectionExpression("Message, ReplyDateTime, PostedBy") - .withKeyConditionExpression("Id = :v_id").withFilterExpression("PostedBy = :v_postedby") - .withValueMap(new ValueMap().withString(":v_id", replyId).withString(":v_postedby", "User B")); + .withKeyConditionExpression("Id = :v_id").withFilterExpression("PostedBy = :v_postedby") + .withValueMap(new ValueMap().withString(":v_id", replyId).withString(":v_postedby", "User B")); ItemCollection items = table.query(spec); @@ -180,4 +159,4 @@ private static void findRepliesUsingAFilterExpression(String forumName, String t } -// snippet-end:[dynamodb.java.codeexample.DocumentAPIQuery] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.DocumentAPIQuery] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIScan.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIScan.java index 1e88365de7e..7b6cc741c0a 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIScan.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPIScan.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.DocumentAPIScan] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.DocumentAPIScan] package com.amazonaws.codesamples.document; @@ -57,9 +36,9 @@ private static void findProductsForPriceLessThanOneHundred() { expressionAttributeValues.put(":pr", 100); ItemCollection items = table.scan("Price < :pr", // FilterExpression - "Id, Title, ProductCategory, Price", // ProjectionExpression - null, // ExpressionAttributeNames - not used in this example - expressionAttributeValues); + "Id, Title, ProductCategory, Price", // ProjectionExpression + null, // ExpressionAttributeNames - not used in this example + expressionAttributeValues); System.out.println("Scan of " + tableName + " for items with a price less than 100."); Iterator iterator = items.iterator(); @@ -70,4 +49,4 @@ private static void findProductsForPriceLessThanOneHundred() { } -// snippet-end:[dynamodb.java.codeexample.DocumentAPIScan] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.DocumentAPIScan] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPITableExample.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPITableExample.java index 19ff270f3a2..c0e7c88cc42 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPITableExample.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/document/DocumentAPITableExample.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.DocumentAPITableExample] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.DocumentAPITableExample] package com.amazonaws.codesamples.document; @@ -71,8 +50,8 @@ static void createExampleTable() { // key CreateTableRequest request = new CreateTableRequest().withTableName(tableName).withKeySchema(keySchema) - .withAttributeDefinitions(attributeDefinitions).withProvisionedThroughput( - new ProvisionedThroughput().withReadCapacityUnits(5L).withWriteCapacityUnits(6L)); + .withAttributeDefinitions(attributeDefinitions).withProvisionedThroughput( + new ProvisionedThroughput().withReadCapacityUnits(5L).withWriteCapacityUnits(6L)); System.out.println("Issuing CreateTable request for " + tableName); Table table = dynamoDB.createTable(request); @@ -82,8 +61,7 @@ static void createExampleTable() { getTableInformation(); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("CreateTable request failed for " + tableName); System.err.println(e.getMessage()); } @@ -109,11 +87,11 @@ static void getTableInformation() { TableDescription tableDescription = dynamoDB.getTable(tableName).describe(); System.out.format( - "Name: %s:\n" + "Status: %s \n" + "Provisioned Throughput (read capacity units/sec): %d \n" - + "Provisioned Throughput (write capacity units/sec): %d \n", - tableDescription.getTableName(), tableDescription.getTableStatus(), - tableDescription.getProvisionedThroughput().getReadCapacityUnits(), - tableDescription.getProvisionedThroughput().getWriteCapacityUnits()); + "Name: %s:\n" + "Status: %s \n" + "Provisioned Throughput (read capacity units/sec): %d \n" + + "Provisioned Throughput (write capacity units/sec): %d \n", + tableDescription.getTableName(), tableDescription.getTableStatus(), + tableDescription.getProvisionedThroughput().getReadCapacityUnits(), + tableDescription.getProvisionedThroughput().getWriteCapacityUnits()); } static void updateExampleTable() { @@ -125,8 +103,7 @@ static void updateExampleTable() { table.updateTable(new ProvisionedThroughput().withReadCapacityUnits(6L).withWriteCapacityUnits(7L)); table.waitForActive(); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("UpdateTable request failed for " + tableName); System.err.println(e.getMessage()); } @@ -142,8 +119,7 @@ static void deleteExampleTable() { System.out.println("Waiting for " + tableName + " to be deleted...this may take a while..."); table.waitForDelete(); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("DeleteTable request failed for " + tableName); System.err.println(e.getMessage()); } @@ -151,4 +127,4 @@ static void deleteExampleTable() { } -// snippet-end:[dynamodb.java.codeexample.DocumentAPITableExample] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.DocumentAPITableExample] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesCreateTable.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesCreateTable.java index 57ed7fdcb43..47e51d79e6e 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesCreateTable.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesCreateTable.java @@ -1,29 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.MoviesCreateTable] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.MoviesCreateTable] package com.amazonaws.codesamples.gsg; @@ -42,34 +20,35 @@ public class MoviesCreateTable { - public static void main(String[] args) throws Exception { + public static void main(String[] args) throws Exception { - AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() - .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) - .build(); + AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() + .withEndpointConfiguration( + new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", + "us-west-2")) + .build(); - DynamoDB dynamoDB = new DynamoDB(client); + DynamoDB dynamoDB = new DynamoDB(client); - String tableName = "Movies"; + String tableName = "Movies"; - try { - System.out.println("Attempting to create table; please wait..."); - Table table = dynamoDB.createTable(tableName, - Arrays.asList(new KeySchemaElement("year", KeyType.HASH), // Partition - // key - new KeySchemaElement("title", KeyType.RANGE)), // Sort key - Arrays.asList(new AttributeDefinition("year", ScalarAttributeType.N), - new AttributeDefinition("title", ScalarAttributeType.S)), - new ProvisionedThroughput(10L, 10L)); - table.waitForActive(); - System.out.println("Success. Table status: " + table.getDescription().getTableStatus()); + try { + System.out.println("Attempting to create table; please wait..."); + Table table = dynamoDB.createTable(tableName, + Arrays.asList(new KeySchemaElement("year", KeyType.HASH), // Partition + // key + new KeySchemaElement("title", KeyType.RANGE)), // Sort key + Arrays.asList(new AttributeDefinition("year", ScalarAttributeType.N), + new AttributeDefinition("title", ScalarAttributeType.S)), + new ProvisionedThroughput(10L, 10L)); + table.waitForActive(); + System.out.println("Success. Table status: " + table.getDescription().getTableStatus()); - } - catch (Exception e) { - System.err.println("Unable to create table: "); - System.err.println(e.getMessage()); - } + } catch (Exception e) { + System.err.println("Unable to create table: "); + System.err.println(e.getMessage()); + } - } + } } -// snippet-end:[dynamodb.java.codeexample.MoviesCreateTable] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.MoviesCreateTable] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesDeleteTable.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesDeleteTable.java index aa2f179abce..e944d388ed9 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesDeleteTable.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesDeleteTable.java @@ -1,29 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.MoviesDeleteTable] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.MoviesDeleteTable] package com.amazonaws.codesamples.gsg; @@ -38,8 +16,9 @@ public class MoviesDeleteTable { public static void main(String[] args) throws Exception { AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() - .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) - .build(); + .withEndpointConfiguration( + new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) + .build(); DynamoDB dynamoDB = new DynamoDB(client); @@ -51,11 +30,10 @@ public static void main(String[] args) throws Exception { table.waitForDelete(); System.out.print("Success."); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Unable to delete table: "); System.err.println(e.getMessage()); } } } -// snippet-end:[dynamodb.java.codeexample.MoviesDeleteTable] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.MoviesDeleteTable] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps01.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps01.java index 1444fd1b2d0..074ffe88642 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps01.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps01.java @@ -1,29 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.MoviesItemOps01] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.MoviesItemOps01] package com.amazonaws.codesamples.gsg; @@ -43,8 +21,9 @@ public class MoviesItemOps01 { public static void main(String[] args) throws Exception { AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() - .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) - .build(); + .withEndpointConfiguration( + new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) + .build(); DynamoDB dynamoDB = new DynamoDB(client); @@ -60,12 +39,11 @@ public static void main(String[] args) throws Exception { try { System.out.println("Adding a new item..."); PutItemOutcome outcome = table - .putItem(new Item().withPrimaryKey("year", year, "title", title).withMap("info", infoMap)); + .putItem(new Item().withPrimaryKey("year", year, "title", title).withMap("info", infoMap)); System.out.println("PutItem succeeded:\n" + outcome.getPutItemResult()); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Unable to add item: " + year + " " + title); System.err.println(e.getMessage()); } @@ -73,4 +51,4 @@ public static void main(String[] args) throws Exception { } } -// snippet-end:[dynamodb.java.codeexample.MoviesItemOps01] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.MoviesItemOps01] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps02.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps02.java index de05e27b4b0..285c1b85fed 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps02.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps02.java @@ -1,29 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.MoviesItemOps02] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.MoviesItemOps02] package com.amazonaws.codesamples.gsg; @@ -40,8 +18,9 @@ public class MoviesItemOps02 { public static void main(String[] args) throws Exception { AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() - .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) - .build(); + .withEndpointConfiguration( + new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) + .build(); DynamoDB dynamoDB = new DynamoDB(client); @@ -57,12 +36,11 @@ public static void main(String[] args) throws Exception { Item outcome = table.getItem(spec); System.out.println("GetItem succeeded: " + outcome); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Unable to read item: " + year + " " + title); System.err.println(e.getMessage()); } } } -// snippet-end:[dynamodb.java.codeexample.MoviesItemOps02] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.MoviesItemOps02] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps03.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps03.java index 9a7ef5c33f2..96f50bf8385 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps03.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps03.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.MoviesItemOps03] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.MoviesItemOps03] package com.amazonaws.codesamples.gsg; @@ -43,8 +22,9 @@ public class MoviesItemOps03 { public static void main(String[] args) throws Exception { AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() - .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) - .build(); + .withEndpointConfiguration( + new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) + .build(); DynamoDB dynamoDB = new DynamoDB(client); @@ -54,21 +34,20 @@ public static void main(String[] args) throws Exception { String title = "The Big New Movie"; UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("year", year, "title", title) - .withUpdateExpression("set info.rating = :r, info.plot=:p, info.actors=:a") - .withValueMap(new ValueMap().withNumber(":r", 5.5).withString(":p", "Everything happens all at once.") - .withList(":a", Arrays.asList("Larry", "Moe", "Curly"))) - .withReturnValues(ReturnValue.UPDATED_NEW); + .withUpdateExpression("set info.rating = :r, info.plot=:p, info.actors=:a") + .withValueMap(new ValueMap().withNumber(":r", 5.5).withString(":p", "Everything happens all at once.") + .withList(":a", Arrays.asList("Larry", "Moe", "Curly"))) + .withReturnValues(ReturnValue.UPDATED_NEW); try { System.out.println("Updating the item..."); UpdateItemOutcome outcome = table.updateItem(updateItemSpec); System.out.println("UpdateItem succeeded:\n" + outcome.getItem().toJSONPretty()); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Unable to update item: " + year + " " + title); System.err.println(e.getMessage()); } } } -// snippet-end:[dynamodb.java.codeexample.MoviesItemOps03] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.MoviesItemOps03] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps04.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps04.java index 2437753177e..91c3a0424bf 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps04.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps04.java @@ -1,29 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.MoviesItemOps04] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.MoviesItemOps04] package com.amazonaws.codesamples.gsg; @@ -42,8 +20,9 @@ public class MoviesItemOps04 { public static void main(String[] args) throws Exception { AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() - .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) - .build(); + .withEndpointConfiguration( + new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) + .build(); DynamoDB dynamoDB = new DynamoDB(client); @@ -53,19 +32,18 @@ public static void main(String[] args) throws Exception { String title = "The Big New Movie"; UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("year", year, "title", title) - .withUpdateExpression("set info.rating = info.rating + :val") - .withValueMap(new ValueMap().withNumber(":val", 1)).withReturnValues(ReturnValue.UPDATED_NEW); + .withUpdateExpression("set info.rating = info.rating + :val") + .withValueMap(new ValueMap().withNumber(":val", 1)).withReturnValues(ReturnValue.UPDATED_NEW); try { System.out.println("Incrementing an atomic counter..."); UpdateItemOutcome outcome = table.updateItem(updateItemSpec); System.out.println("UpdateItem succeeded:\n" + outcome.getItem().toJSONPretty()); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Unable to update item: " + year + " " + title); System.err.println(e.getMessage()); } } } -// snippet-end:[dynamodb.java.codeexample.MoviesItemOps04] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.MoviesItemOps04] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps05.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps05.java index 43145942096..7e772cbb1d3 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps05.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps05.java @@ -1,29 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.MoviesItemOps05] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.MoviesItemOps05] package com.amazonaws.codesamples.gsg; @@ -43,8 +21,9 @@ public class MoviesItemOps05 { public static void main(String[] args) throws Exception { AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() - .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) - .build(); + .withEndpointConfiguration( + new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) + .build(); DynamoDB dynamoDB = new DynamoDB(client); @@ -54,9 +33,10 @@ public static void main(String[] args) throws Exception { String title = "The Big New Movie"; UpdateItemSpec updateItemSpec = new UpdateItemSpec() - .withPrimaryKey(new PrimaryKey("year", year, "title", title)).withUpdateExpression("remove info.actors[0]") - .withConditionExpression("size(info.actors) > :num").withValueMap(new ValueMap().withNumber(":num", 3)) - .withReturnValues(ReturnValue.UPDATED_NEW); + .withPrimaryKey(new PrimaryKey("year", year, "title", title)) + .withUpdateExpression("remove info.actors[0]") + .withConditionExpression("size(info.actors) > :num").withValueMap(new ValueMap().withNumber(":num", 3)) + .withReturnValues(ReturnValue.UPDATED_NEW); // Conditional update (we expect this to fail) try { @@ -64,11 +44,10 @@ public static void main(String[] args) throws Exception { UpdateItemOutcome outcome = table.updateItem(updateItemSpec); System.out.println("UpdateItem succeeded:\n" + outcome.getItem().toJSONPretty()); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Unable to update item: " + year + " " + title); System.err.println(e.getMessage()); } } } -// snippet-end:[dynamodb.java.codeexample.MoviesItemOps05] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.MoviesItemOps05] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps06.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps06.java index 8c3ea011e08..ee6d7284d2a 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps06.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesItemOps06.java @@ -1,29 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.MoviesItemOps06] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.MoviesItemOps06] package com.amazonaws.codesamples.gsg; @@ -41,8 +19,9 @@ public class MoviesItemOps06 { public static void main(String[] args) throws Exception { AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() - .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) - .build(); + .withEndpointConfiguration( + new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) + .build(); DynamoDB dynamoDB = new DynamoDB(client); @@ -52,8 +31,9 @@ public static void main(String[] args) throws Exception { String title = "The Big New Movie"; DeleteItemSpec deleteItemSpec = new DeleteItemSpec() - .withPrimaryKey(new PrimaryKey("year", year, "title", title)).withConditionExpression("info.rating <= :val") - .withValueMap(new ValueMap().withNumber(":val", 5.0)); + .withPrimaryKey(new PrimaryKey("year", year, "title", title)) + .withConditionExpression("info.rating <= :val") + .withValueMap(new ValueMap().withNumber(":val", 5.0)); // Conditional delete (we expect this to fail) @@ -61,11 +41,10 @@ public static void main(String[] args) throws Exception { System.out.println("Attempting a conditional delete..."); table.deleteItem(deleteItemSpec); System.out.println("DeleteItem succeeded"); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Unable to delete item: " + year + " " + title); System.err.println(e.getMessage()); } } } -// snippet-end:[dynamodb.java.codeexample.MoviesItemOps06] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.MoviesItemOps06] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesLoadData.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesLoadData.java index 0acd8287466..55bdbba87d7 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesLoadData.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesLoadData.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.MoviesLoadData] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.MoviesLoadData] package com.amazonaws.codesamples.gsg; @@ -46,8 +25,9 @@ public class MoviesLoadData { public static void main(String[] args) throws Exception { AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() - .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) - .build(); + .withEndpointConfiguration( + new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) + .build(); DynamoDB dynamoDB = new DynamoDB(client); @@ -68,11 +48,10 @@ public static void main(String[] args) throws Exception { try { table.putItem(new Item().withPrimaryKey("year", year, "title", title).withJSON("info", - currentNode.path("info").toString())); + currentNode.path("info").toString())); System.out.println("PutItem succeeded: " + year + " " + title); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Unable to add movie: " + year + " " + title); System.err.println(e.getMessage()); break; @@ -81,4 +60,4 @@ public static void main(String[] args) throws Exception { parser.close(); } } -// snippet-end:[dynamodb.java.codeexample.MoviesLoadData] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.MoviesLoadData] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesQuery.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesQuery.java index 310acd5e248..b6661e6cc26 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesQuery.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesQuery.java @@ -1,29 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.MoviesQuery] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.MoviesQuery] package com.amazonaws.codesamples.gsg; @@ -45,8 +23,9 @@ public class MoviesQuery { public static void main(String[] args) throws Exception { AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() - .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) - .build(); + .withEndpointConfiguration( + new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) + .build(); DynamoDB dynamoDB = new DynamoDB(client); @@ -59,7 +38,7 @@ public static void main(String[] args) throws Exception { valueMap.put(":yyyy", 1985); QuerySpec querySpec = new QuerySpec().withKeyConditionExpression("#yr = :yyyy").withNameMap(nameMap) - .withValueMap(valueMap); + .withValueMap(valueMap); ItemCollection items = null; Iterator iterator = null; @@ -75,8 +54,7 @@ public static void main(String[] args) throws Exception { System.out.println(item.getNumber("year") + ": " + item.getString("title")); } - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Unable to query movies from 1985"); System.err.println(e.getMessage()); } @@ -86,8 +64,8 @@ public static void main(String[] args) throws Exception { valueMap.put(":letter2", "L"); querySpec.withProjectionExpression("#yr, title, info.genres, info.actors[0]") - .withKeyConditionExpression("#yr = :yyyy and title between :letter1 and :letter2").withNameMap(nameMap) - .withValueMap(valueMap); + .withKeyConditionExpression("#yr = :yyyy and title between :letter1 and :letter2").withNameMap(nameMap) + .withValueMap(valueMap); try { System.out.println("Movies from 1992 - titles A-L, with genres and lead actor"); @@ -99,12 +77,11 @@ public static void main(String[] args) throws Exception { System.out.println(item.getNumber("year") + ": " + item.getString("title") + " " + item.getMap("info")); } - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Unable to query movies from 1992:"); System.err.println(e.getMessage()); } } } -// snippet-end:[dynamodb.java.codeexample.MoviesQuery] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.MoviesQuery] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesScan.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesScan.java index 16e8b65cece..baf8a6d19d9 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesScan.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/gsg/MoviesScan.java @@ -1,29 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.MoviesScan] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.MoviesScan] package com.amazonaws.codesamples.gsg; @@ -46,16 +24,18 @@ public class MoviesScan { public static void main(String[] args) throws Exception { AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() - .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) - .build(); + .withEndpointConfiguration( + new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")) + .build(); DynamoDB dynamoDB = new DynamoDB(client); Table table = dynamoDB.getTable("Movies"); ScanSpec scanSpec = new ScanSpec().withProjectionExpression("#yr, title, info.rating") - .withFilterExpression("#yr between :start_yr and :end_yr").withNameMap(new NameMap().with("#yr", "year")) - .withValueMap(new ValueMap().withNumber(":start_yr", 1950).withNumber(":end_yr", 1959)); + .withFilterExpression("#yr between :start_yr and :end_yr") + .withNameMap(new NameMap().with("#yr", "year")) + .withValueMap(new ValueMap().withNumber(":start_yr", 1950).withNumber(":end_yr", 1959)); try { ItemCollection items = table.scan(scanSpec); @@ -66,11 +46,10 @@ public static void main(String[] args) throws Exception { System.out.println(item.toString()); } - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Unable to scan the table:"); System.err.println(e.getMessage()); } } } -// snippet-end:[dynamodb.java.codeexample.MoviesScan] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.MoviesScan] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelBatchGet.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelBatchGet.java index c9a9914cc28..d78f260f0e4 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelBatchGet.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelBatchGet.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.LowLevelBatchGet] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.LowLevelBatchGet] package com.amazonaws.codesamples.lowlevel; @@ -120,8 +99,7 @@ private static void retrieveMultipleItemsBatchGet() { requestItems = result.getUnprocessedKeys(); } while (result.getUnprocessedKeys().size() > 0); - } - catch (AmazonServiceException ase) { + } catch (AmazonServiceException ase) { System.err.println("Failed to retrieve items."); } @@ -132,12 +110,12 @@ private static void printItem(Map attributeList) { String attributeName = item.getKey(); AttributeValue value = item.getValue(); System.out.println(attributeName + " " + (value.getS() == null ? "" : "S=[" + value.getS() + "]") - + (value.getN() == null ? "" : "N=[" + value.getN() + "]") - + (value.getB() == null ? "" : "B=[" + value.getB() + "]") - + (value.getSS() == null ? "" : "SS=[" + value.getSS() + "]") - + (value.getNS() == null ? "" : "NS=[" + value.getNS() + "]") - + (value.getBS() == null ? "" : "BS=[" + value.getBS() + "] \n")); + + (value.getN() == null ? "" : "N=[" + value.getN() + "]") + + (value.getB() == null ? "" : "B=[" + value.getB() + "]") + + (value.getSS() == null ? "" : "SS=[" + value.getSS() + "]") + + (value.getNS() == null ? "" : "NS=[" + value.getNS() + "]") + + (value.getBS() == null ? "" : "BS=[" + value.getBS() + "] \n")); } } } -// snippet-end:[dynamodb.java.codeexample.LowLevelBatchGet] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.LowLevelBatchGet] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelBatchWrite.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelBatchWrite.java index ae03839c35f..08f1967fe3a 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelBatchWrite.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelBatchWrite.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.LowLevelBatchWrite] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.LowLevelBatchWrite] package com.amazonaws.codesamples.lowlevel; @@ -92,7 +71,7 @@ private static void writeMultipleItemsBatchWrite() { BatchWriteItemResult result; BatchWriteItemRequest batchWriteItemRequest = new BatchWriteItemRequest() - .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL); + .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL); do { System.out.println("Making the request."); @@ -113,8 +92,7 @@ private static void writeMultipleItemsBatchWrite() { requestItems = result.getUnprocessedItems(); } while (result.getUnprocessedItems().size() > 0); - } - catch (AmazonServiceException ase) { + } catch (AmazonServiceException ase) { System.err.println("Failed to retrieve items: "); ase.printStackTrace(System.err); } @@ -123,4 +101,4 @@ private static void writeMultipleItemsBatchWrite() { } -// snippet-end:[dynamodb.java.codeexample.LowLevelBatchWrite] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.LowLevelBatchWrite] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelBatchWriteSyntax.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelBatchWriteSyntax.java index 423dd457131..615078b9677 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelBatchWriteSyntax.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelBatchWriteSyntax.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.LowLevelBatchWriteSyntax] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.LowLevelBatchWriteSyntax] package com.amazonaws.codesamples.lowlevel; @@ -63,7 +42,7 @@ public static void main(String[] args) throws IOException { private static void createClient() throws IOException { AWSCredentials credentials = new PropertiesCredentials( - LowLevelBatchWriteSyntax.class.getResourceAsStream("AwsCredentials.properties")); + LowLevelBatchWriteSyntax.class.getResourceAsStream("AwsCredentials.properties")); client = new AmazonDynamoDBClient(credentials); } @@ -110,8 +89,7 @@ private static void writeMultipleItemsBatchWrite() { // End syntax extract - } - catch (AmazonServiceException ase) { + } catch (AmazonServiceException ase) { System.err.println("Failed to retrieve items: "); ase.printStackTrace(System.err); } @@ -120,4 +98,4 @@ private static void writeMultipleItemsBatchWrite() { } -// snippet-end:[dynamodb.java.codeexample.LowLevelBatchWriteSyntax] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.LowLevelBatchWriteSyntax] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelGlobalSecondaryIndexExample.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelGlobalSecondaryIndexExample.java index 146b5233b8b..2a4ffb98722 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelGlobalSecondaryIndexExample.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelGlobalSecondaryIndexExample.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.LowLevelGlobalSecondaryIndexExample] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.LowLevelGlobalSecondaryIndexExample] package com.amazonaws.codesamples.lowlevel; @@ -92,39 +71,39 @@ public static void createTable() { // Initial provisioned throughput settings for the indexes ProvisionedThroughput ptIndex = new ProvisionedThroughput().withReadCapacityUnits(1L) - .withWriteCapacityUnits(1L); + .withWriteCapacityUnits(1L); // CreateDateIndex GlobalSecondaryIndex createDateIndex = new GlobalSecondaryIndex().withIndexName("CreateDateIndex") - .withProvisionedThroughput(ptIndex) - .withKeySchema(new KeySchemaElement().withAttributeName("CreateDate").withKeyType(KeyType.HASH), // Partition - // key - new KeySchemaElement().withAttributeName("IssueId").withKeyType(KeyType.RANGE)) // Sort - // key - .withProjection( - new Projection().withProjectionType("INCLUDE").withNonKeyAttributes("Description", "Status")); + .withProvisionedThroughput(ptIndex) + .withKeySchema(new KeySchemaElement().withAttributeName("CreateDate").withKeyType(KeyType.HASH), // Partition + // key + new KeySchemaElement().withAttributeName("IssueId").withKeyType(KeyType.RANGE)) // Sort + // key + .withProjection( + new Projection().withProjectionType("INCLUDE").withNonKeyAttributes("Description", "Status")); // TitleIndex GlobalSecondaryIndex titleIndex = new GlobalSecondaryIndex().withIndexName("TitleIndex") - .withProvisionedThroughput(ptIndex) - .withKeySchema(new KeySchemaElement().withAttributeName("Title").withKeyType(KeyType.HASH), // Partition + .withProvisionedThroughput(ptIndex) + .withKeySchema(new KeySchemaElement().withAttributeName("Title").withKeyType(KeyType.HASH), // Partition + // key + new KeySchemaElement().withAttributeName("IssueId").withKeyType(KeyType.RANGE)) // Sort // key - new KeySchemaElement().withAttributeName("IssueId").withKeyType(KeyType.RANGE)) // Sort - // key - .withProjection(new Projection().withProjectionType("KEYS_ONLY")); + .withProjection(new Projection().withProjectionType("KEYS_ONLY")); // DueDateIndex GlobalSecondaryIndex dueDateIndex = new GlobalSecondaryIndex().withIndexName("DueDateIndex") - .withProvisionedThroughput(ptIndex) - .withKeySchema(new KeySchemaElement().withAttributeName("DueDate").withKeyType(KeyType.HASH)) // Partition - // key - .withProjection(new Projection().withProjectionType("ALL")); + .withProvisionedThroughput(ptIndex) + .withKeySchema(new KeySchemaElement().withAttributeName("DueDate").withKeyType(KeyType.HASH)) // Partition + // key + .withProjection(new Projection().withProjectionType("ALL")); CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName) - .withProvisionedThroughput( - new ProvisionedThroughput().withReadCapacityUnits((long) 1).withWriteCapacityUnits((long) 1)) - .withAttributeDefinitions(attributeDefinitions).withKeySchema(tableKeySchema) - .withGlobalSecondaryIndexes(createDateIndex, titleIndex, dueDateIndex); + .withProvisionedThroughput( + new ProvisionedThroughput().withReadCapacityUnits((long) 1).withWriteCapacityUnits((long) 1)) + .withAttributeDefinitions(attributeDefinitions).withKeySchema(tableKeySchema) + .withGlobalSecondaryIndexes(createDateIndex, titleIndex, dueDateIndex); System.out.println("Creating table " + tableName + "..."); System.out.println(client.createTable(createTableRequest)); @@ -137,41 +116,38 @@ public static void queryIndex(String indexName) { System.out.print("Querying index " + indexName + "..."); QueryRequest queryRequest = new QueryRequest().withTableName(tableName).withIndexName(indexName) - .withScanIndexForward(true); + .withScanIndexForward(true); HashMap keyConditions = new HashMap(); if (indexName == "CreateDateIndex") { System.out.println("Issues filed on 2013-11-01"); keyConditions.put("CreateDate", new Condition().withComparisonOperator(ComparisonOperator.EQ) - .withAttributeValueList(new AttributeValue().withS("2013-11-01"))); + .withAttributeValueList(new AttributeValue().withS("2013-11-01"))); keyConditions.put("IssueId", new Condition().withComparisonOperator(ComparisonOperator.BEGINS_WITH) - .withAttributeValueList(new AttributeValue().withS("A-"))); + .withAttributeValueList(new AttributeValue().withS("A-"))); - } - else if (indexName == "TitleIndex") { + } else if (indexName == "TitleIndex") { System.out.println("Compilation errors"); keyConditions.put("Title", new Condition().withComparisonOperator(ComparisonOperator.EQ) - .withAttributeValueList(new AttributeValue().withS("Compilation error"))); + .withAttributeValueList(new AttributeValue().withS("Compilation error"))); keyConditions.put("IssueId", new Condition().withComparisonOperator(ComparisonOperator.BEGINS_WITH) - .withAttributeValueList(new AttributeValue().withS("A-"))); + .withAttributeValueList(new AttributeValue().withS("A-"))); // Select queryRequest.setSelect(Select.ALL_PROJECTED_ATTRIBUTES); - } - else if (indexName == "DueDateIndex") { + } else if (indexName == "DueDateIndex") { System.out.println("Items that are due on 2013-11-30"); keyConditions.put("DueDate", new Condition().withComparisonOperator(ComparisonOperator.EQ) - .withAttributeValueList(new AttributeValue().withS("2013-11-30"))); + .withAttributeValueList(new AttributeValue().withS("2013-11-30"))); // Select queryRequest.setSelect(Select.ALL_PROJECTED_ATTRIBUTES); - } - else { + } else { System.out.println("\nNo valid index name provided"); return; } @@ -193,8 +169,7 @@ else if (indexName == "DueDateIndex") { String attr = (String) currentItemIter.next(); if (attr == "Priority") { System.out.println(attr + "---> " + currentItem.get(attr).getN()); - } - else { + } else { System.out.println(attr + "---> " + currentItem.get(attr).getS()); } } @@ -219,24 +194,24 @@ public static void loadData() { // Priority, Status putItem("A-101", "Compilation error", "Can't compile Project X - bad version number. What does this mean?", - "2013-11-01", "2013-11-02", "2013-11-10", 1, "Assigned"); + "2013-11-01", "2013-11-02", "2013-11-10", 1, "Assigned"); putItem("A-102", "Can't read data file", "The main data file is missing, or the permissions are incorrect", - "2013-11-01", "2013-11-04", "2013-11-30", 2, "In progress"); + "2013-11-01", "2013-11-04", "2013-11-30", 2, "In progress"); putItem("A-103", "Test failure", "Functional test of Project X produces errors", "2013-11-01", "2013-11-02", - "2013-11-10", 1, "In progress"); + "2013-11-10", 1, "In progress"); putItem("A-104", "Compilation error", "Variable 'messageCount' was not initialized.", "2013-11-15", - "2013-11-16", "2013-11-30", 3, "Assigned"); + "2013-11-16", "2013-11-30", 3, "Assigned"); putItem("A-105", "Network issue", "Can't ping IP address 127.0.0.1. Please fix this.", "2013-11-15", - "2013-11-16", "2013-11-19", 5, "Assigned"); + "2013-11-16", "2013-11-19", 5, "Assigned"); } public static void putItem(String issueId, String title, String description, String createDate, - String lastUpdateDate, String dueDate, Integer priority, String status) { + String lastUpdateDate, String dueDate, Integer priority, String status) { HashMap item = new HashMap(); @@ -251,8 +226,7 @@ public static void putItem(String issueId, String title, String description, Str try { client.putItem(new PutItemRequest().withTableName(tableName).withItem(item)); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } } @@ -274,8 +248,7 @@ private static void waitForTableToBecomeAvailable(String tableName) { return; try { Thread.sleep(1000 * 20); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } } @@ -298,15 +271,13 @@ private static void waitForTableToBeDeleted(String tableName) { if (tableStatus.equals(TableStatus.ACTIVE.toString())) return; - } - catch (ResourceNotFoundException e) { + } catch (ResourceNotFoundException e) { System.out.println("Table " + tableName + " is not found. It was deleted."); return; } try { Thread.sleep(1000 * 20); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } } @@ -315,4 +286,4 @@ private static void waitForTableToBeDeleted(String tableName) { } -// snippet-end:[dynamodb.java.codeexample.LowLevelGlobalSecondaryIndexExample] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.LowLevelGlobalSecondaryIndexExample] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelItemBinaryExample.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelItemBinaryExample.java index 484679bfa2d..b37ccadc084 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelItemBinaryExample.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelItemBinaryExample.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.LowLevelItemBinaryExample] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.LowLevelItemBinaryExample] package com.amazonaws.codesamples.lowlevel; @@ -69,8 +48,7 @@ public static void main(String[] args) throws IOException { // clean up by deleting the item deleteItem(threadId, replyDateTime); - } - catch (Exception e) { + } catch (Exception e) { System.err.println("Error running the binary attribute type example: " + e); e.printStackTrace(System.err); } @@ -102,7 +80,7 @@ public static void retrieveItem(String threadId, String replyDateTime) throws IO key.put("ReplyDateTime", new AttributeValue().withS(replyDateTime)); GetItemRequest getReplyRequest = new GetItemRequest().withTableName(tableName).withKey(key) - .withConsistentRead(true); + .withConsistentRead(true); GetItemResult getReplyResult = client.getItem(getReplyRequest); @@ -110,8 +88,8 @@ public static void retrieveItem(String threadId, String replyDateTime) throws IO Map reply = getReplyResult.getItem(); String message = decompressString(reply.get("ExtendedMessage").getB()); System.out.println("Reply message:\n" + " Id: " + reply.get("Id").getS() + "\n" + " ReplyDateTime: " - + reply.get("ReplyDateTime").getS() + "\n" + " PostedBy: " + reply.get("PostedBy").getS() + "\n" - + " Message: " + reply.get("Message").getS() + "\n" + " ExtendedMessage (decompressed): " + message); + + reply.get("ReplyDateTime").getS() + "\n" + " PostedBy: " + reply.get("PostedBy").getS() + "\n" + + " Message: " + reply.get("Message").getS() + "\n" + " ExtendedMessage (decompressed): " + message); } public static void deleteItem(String threadId, String replyDateTime) { @@ -165,4 +143,4 @@ private static String decompressString(ByteBuffer input) throws IOException { } } -// snippet-end:[dynamodb.java.codeexample.LowLevelItemBinaryExample] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.LowLevelItemBinaryExample] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelItemCRUDExample.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelItemCRUDExample.java index 6d3092d6085..dfc5c8943c8 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelItemCRUDExample.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelItemCRUDExample.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.LowLevelItemCRUDExample] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.LowLevelItemCRUDExample] package com.amazonaws.codesamples.lowlevel; @@ -93,8 +72,7 @@ private static void createItems() { PutItemRequest putItemRequest2 = new PutItemRequest().withTableName(tableName).withItem(item2); client.putItem(putItemRequest2); - } - catch (AmazonServiceException ase) { + } catch (AmazonServiceException ase) { System.err.println("Create items failed."); } } @@ -105,7 +83,7 @@ private static void retrieveItem() { HashMap key = new HashMap(); key.put("Id", new AttributeValue().withN("120")); GetItemRequest getItemRequest = new GetItemRequest().withTableName(tableName).withKey(key) - .withProjectionExpression("Id, ISBN, Title, Authors"); + .withProjectionExpression("Id, ISBN, Title, Authors"); GetItemResult result = client.getItem(getItemRequest); @@ -113,8 +91,7 @@ private static void retrieveItem() { System.out.println("Printing item after retrieving it...."); printItem(result.getItem()); - } - catch (AmazonServiceException ase) { + } catch (AmazonServiceException ase) { System.err.println("Failed to retrieve item in " + tableName); } @@ -131,8 +108,8 @@ private static void updateAddNewAttribute() { ReturnValue returnValues = ReturnValue.ALL_NEW; UpdateItemRequest updateItemRequest = new UpdateItemRequest().withTableName(tableName).withKey(key) - .withUpdateExpression("set NewAttribute = :val1") - .withExpressionAttributeValues(expressionAttributeValues).withReturnValues(returnValues); + .withUpdateExpression("set NewAttribute = :val1") + .withExpressionAttributeValues(expressionAttributeValues).withReturnValues(returnValues); UpdateItemResult result = client.updateItem(updateItemRequest); @@ -140,8 +117,7 @@ private static void updateAddNewAttribute() { System.out.println("Printing item after adding new attribute..."); printItem(result.getAttributes()); - } - catch (AmazonServiceException ase) { + } catch (AmazonServiceException ase) { System.err.println("Failed to add new attribute in " + tableName); System.err.println(ase.getMessage()); } @@ -160,8 +136,8 @@ private static void updateMultipleAttributes() { ReturnValue returnValues = ReturnValue.ALL_NEW; UpdateItemRequest updateItemRequest = new UpdateItemRequest().withTableName(tableName).withKey(key) - .withUpdateExpression("add Authors :val1 set NewAttribute=:val2") - .withExpressionAttributeValues(expressionAttributeValues).withReturnValues(returnValues); + .withUpdateExpression("add Authors :val1 set NewAttribute=:val2") + .withExpressionAttributeValues(expressionAttributeValues).withReturnValues(returnValues); UpdateItemResult result = client.updateItem(updateItemRequest); @@ -169,8 +145,7 @@ private static void updateMultipleAttributes() { System.out.println("Printing item after multiple attribute update..."); printItem(result.getAttributes()); - } - catch (AmazonServiceException ase) { + } catch (AmazonServiceException ase) { System.err.println("Failed to update multiple attributes in " + tableName); System.out.println(ase.getMessage()); // DELETEME System.err.println("Failed to update multiple attributes in " + tableName); // DELETEME @@ -193,20 +168,18 @@ private static void updateExistingAttributeConditionally() { ReturnValue returnValues = ReturnValue.ALL_NEW; UpdateItemRequest updateItemRequest = new UpdateItemRequest().withTableName(tableName).withKey(key) - .withUpdateExpression("set Price = :val1").withConditionExpression("Price = :val2") - .withExpressionAttributeValues(expressionAttributeValues).withReturnValues(returnValues); + .withUpdateExpression("set Price = :val1").withConditionExpression("Price = :val2") + .withExpressionAttributeValues(expressionAttributeValues).withReturnValues(returnValues); UpdateItemResult result = client.updateItem(updateItemRequest); // Check the response. System.out.println("Printing item after conditional update to new attribute..."); printItem(result.getAttributes()); - } - catch (ConditionalCheckFailedException cse) { + } catch (ConditionalCheckFailedException cse) { // Reload object and retry code. System.err.println("Conditional check failed in " + tableName); - } - catch (AmazonServiceException ase) { + } catch (AmazonServiceException ase) { System.err.println("Error updating item in " + tableName); } } @@ -223,8 +196,8 @@ private static void deleteItem() { ReturnValue returnValues = ReturnValue.ALL_OLD; DeleteItemRequest deleteItemRequest = new DeleteItemRequest().withTableName(tableName).withKey(key) - .withConditionExpression("InPublication = :val") - .withExpressionAttributeValues(expressionAttributeValues).withReturnValues(returnValues); + .withConditionExpression("InPublication = :val") + .withExpressionAttributeValues(expressionAttributeValues).withReturnValues(returnValues); DeleteItemResult result = client.deleteItem(deleteItemRequest); @@ -232,8 +205,7 @@ private static void deleteItem() { System.out.println("Printing item that was deleted..."); printItem(result.getAttributes()); - } - catch (AmazonServiceException ase) { + } catch (AmazonServiceException ase) { System.err.println("Failed to get item after deletion " + tableName); } @@ -244,13 +216,13 @@ private static void printItem(Map attributeList) { String attributeName = item.getKey(); AttributeValue value = item.getValue(); System.out.println(attributeName + " " + (value.getS() == null ? "" : "S=[" + value.getS() + "]") - + (value.getN() == null ? "" : "N=[" + value.getN() + "]") - + (value.getB() == null ? "" : "B=[" + value.getB() + "]") - + (value.getSS() == null ? "" : "SS=[" + value.getSS() + "]") - + (value.getNS() == null ? "" : "NS=[" + value.getNS() + "]") - + (value.getBS() == null ? "" : "BS=[" + value.getBS() + "] \n")); + + (value.getN() == null ? "" : "N=[" + value.getN() + "]") + + (value.getB() == null ? "" : "B=[" + value.getB() + "]") + + (value.getSS() == null ? "" : "SS=[" + value.getSS() + "]") + + (value.getNS() == null ? "" : "NS=[" + value.getNS() + "]") + + (value.getBS() == null ? "" : "BS=[" + value.getBS() + "] \n")); } } } -// snippet-end:[dynamodb.java.codeexample.LowLevelItemCRUDExample] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.LowLevelItemCRUDExample] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelLocalSecondaryIndexExample.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelLocalSecondaryIndexExample.java index 1e5e3610bb2..c2816b76cf9 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelLocalSecondaryIndexExample.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelLocalSecondaryIndexExample.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.LowLevelLocalSecondaryIndexExample] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.LowLevelLocalSecondaryIndexExample] package com.amazonaws.codesamples.lowlevel; @@ -80,8 +59,8 @@ public static void main(String[] args) throws Exception { public static void createTable() { CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName) - .withProvisionedThroughput( - new ProvisionedThroughput().withReadCapacityUnits((long) 1).withWriteCapacityUnits((long) 1)); + .withProvisionedThroughput( + new ProvisionedThroughput().withReadCapacityUnits((long) 1).withWriteCapacityUnits((long) 1)); // Attribute definitions for table partition key and sort key ArrayList attributeDefinitions = new ArrayList(); @@ -90,7 +69,7 @@ public static void createTable() { // Attribute definition for index sort key attributes attributeDefinitions - .add(new AttributeDefinition().withAttributeName("OrderCreationDate").withAttributeType("N")); + .add(new AttributeDefinition().withAttributeName("OrderCreationDate").withAttributeType("N")); attributeDefinitions.add(new AttributeDefinition().withAttributeName("IsOpen").withAttributeType("N")); createTableRequest.setAttributeDefinitions(attributeDefinitions); @@ -162,12 +141,12 @@ public static void query(String indexName) { System.out.println("Querying table " + tableName + "..."); QueryRequest queryRequest = new QueryRequest().withTableName(tableName).withConsistentRead(true) - .withScanIndexForward(true).withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL); + .withScanIndexForward(true).withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL); HashMap keyConditions = new HashMap(); keyConditions.put("CustomerId", new Condition().withComparisonOperator(ComparisonOperator.EQ) - .withAttributeValueList(new AttributeValue().withS("bob@example.com"))); + .withAttributeValueList(new AttributeValue().withS("bob@example.com"))); if (indexName == "IsOpenIndex") { System.out.println("\nUsing index: '" + indexName + "': Bob's orders that are open."); @@ -175,25 +154,23 @@ public static void query(String indexName) { queryRequest.setIndexName(indexName); keyConditions.put("IsOpen", new Condition().withComparisonOperator(ComparisonOperator.EQ) - .withAttributeValueList(new AttributeValue().withN("1"))); + .withAttributeValueList(new AttributeValue().withN("1"))); // ProjectionExpression queryRequest.setProjectionExpression("OrderCreationDate, ProductCategory, ProductName, OrderStatus"); - } - else if (indexName == "OrderCreationDateIndex") { + } else if (indexName == "OrderCreationDateIndex") { System.out.println("\nUsing index: '" + indexName + "': Bob's orders that were placed after 01/31/2013."); System.out.println("Only the projected attributes are returned\n"); queryRequest.setIndexName(indexName); keyConditions.put("OrderCreationDate", new Condition().withComparisonOperator(ComparisonOperator.GT) - .withAttributeValueList(new AttributeValue().withN("20130131"))); + .withAttributeValueList(new AttributeValue().withN("20130131"))); // Select queryRequest.setSelect(Select.ALL_PROJECTED_ATTRIBUTES); - } - else { + } else { System.out.println("\nNo index: All of Bob's orders, by OrderId:\n"); } @@ -210,8 +187,7 @@ else if (indexName == "OrderCreationDateIndex") { String attr = (String) currentItemIter.next(); if (attr == "OrderId" || attr == "IsOpen" || attr == "OrderCreationDate") { System.out.println(attr + "---> " + currentItem.get(attr).getN()); - } - else { + } else { System.out.println(attr + "---> " + currentItem.get(attr).getS()); } } @@ -241,7 +217,7 @@ public static void loadData() { item.put("OrderStatus", new AttributeValue().withS("PACKING ITEMS")); /* no ShipmentTrackingId attribute */ PutItemRequest putItemRequest = new PutItemRequest().withTableName(tableName).withItem(item) - .withReturnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE); + .withReturnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE); PutItemResult result = client.putItem(putItemRequest); System.out.println("Item collection metrics: " + result.getItemCollectionMetrics()); @@ -255,7 +231,7 @@ public static void loadData() { item.put("OrderStatus", new AttributeValue().withS("ORDER RECEIVED")); /* no ShipmentTrackingId attribute */ putItemRequest = new PutItemRequest().withTableName(tableName).withItem(item) - .withReturnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE); + .withReturnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE); result = client.putItem(putItemRequest); System.out.println("Item collection metrics: " + result.getItemCollectionMetrics()); @@ -269,7 +245,7 @@ public static void loadData() { item.put("OrderStatus", new AttributeValue().withS("IN TRANSIT")); item.put("ShipmentTrackingId", new AttributeValue().withS("176493")); putItemRequest = new PutItemRequest().withTableName(tableName).withItem(item) - .withReturnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE); + .withReturnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE); result = client.putItem(putItemRequest); System.out.println("Item collection metrics: " + result.getItemCollectionMetrics()); @@ -283,7 +259,7 @@ public static void loadData() { item.put("OrderStatus", new AttributeValue().withS("SHIPPING DELAY")); item.put("ShipmentTrackingId", new AttributeValue().withS("859323")); putItemRequest = new PutItemRequest().withTableName(tableName).withItem(item) - .withReturnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE); + .withReturnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE); result = client.putItem(putItemRequest); System.out.println("Item collection metrics: " + result.getItemCollectionMetrics()); @@ -297,7 +273,7 @@ public static void loadData() { item.put("OrderStatus", new AttributeValue().withS("DELIVERED")); item.put("ShipmentTrackingId", new AttributeValue().withS("756943")); putItemRequest = new PutItemRequest().withTableName(tableName).withItem(item) - .withReturnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE); + .withReturnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE); result = client.putItem(putItemRequest); System.out.println("Item collection metrics: " + result.getItemCollectionMetrics()); @@ -311,7 +287,7 @@ public static void loadData() { item.put("OrderStatus", new AttributeValue().withS("DELIVERED")); item.put("ShipmentTrackingId", new AttributeValue().withS("645193")); putItemRequest = new PutItemRequest().withTableName(tableName).withItem(item) - .withReturnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE); + .withReturnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE); result = client.putItem(putItemRequest); System.out.println("Item collection metrics: " + result.getItemCollectionMetrics()); @@ -325,7 +301,7 @@ public static void loadData() { item.put("OrderStatus", new AttributeValue().withS("PACKING ITEMS")); /* no ShipmentTrackingId attribute */ putItemRequest = new PutItemRequest().withTableName(tableName).withItem(item) - .withReturnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE); + .withReturnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE); result = client.putItem(putItemRequest); System.out.println("Item collection metrics: " + result.getItemCollectionMetrics()); @@ -339,7 +315,7 @@ public static void loadData() { item.put("OrderStatus", new AttributeValue().withS("IN TRANSIT")); item.put("ShipmentTrackingId", new AttributeValue().withS("440185")); putItemRequest = new PutItemRequest().withTableName(tableName).withItem(item) - .withReturnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE); + .withReturnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE); result = client.putItem(putItemRequest); System.out.println("Item collection metrics: " + result.getItemCollectionMetrics()); @@ -353,7 +329,7 @@ public static void loadData() { item.put("OrderStatus", new AttributeValue().withS("DELIVERED")); item.put("ShipmentTrackingId", new AttributeValue().withS("893927")); putItemRequest = new PutItemRequest().withTableName(tableName).withItem(item) - .withReturnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE); + .withReturnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE); result = client.putItem(putItemRequest); System.out.println("Item collection metrics: " + result.getItemCollectionMetrics()); @@ -367,7 +343,7 @@ public static void loadData() { item.put("OrderStatus", new AttributeValue().withS("OUT FOR DELIVERY")); item.put("ShipmentTrackingId", new AttributeValue().withS("383283")); putItemRequest = new PutItemRequest().withTableName(tableName).withItem(item) - .withReturnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE); + .withReturnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE); result = client.putItem(putItemRequest); System.out.println("Item collection metrics: " + result.getItemCollectionMetrics()); @@ -387,8 +363,7 @@ private static void waitForTableToBecomeAvailable(String tableName) { return; try { Thread.sleep(1000 * 20); - } - catch (Exception e) { + } catch (Exception e) { } } throw new RuntimeException("Table " + tableName + " never went active"); @@ -407,15 +382,13 @@ private static void waitForTableToBeDeleted(String tableName) { System.out.println(" - current state: " + tableStatus); if (tableStatus.equals(TableStatus.ACTIVE.toString())) return; - } - catch (ResourceNotFoundException e) { + } catch (ResourceNotFoundException e) { System.out.println("Table " + tableName + " is not found. It was deleted."); return; } try { Thread.sleep(1000 * 20); - } - catch (Exception e) { + } catch (Exception e) { } } throw new RuntimeException("Table " + tableName + " was never deleted"); @@ -423,4 +396,4 @@ private static void waitForTableToBeDeleted(String tableName) { } -// snippet-end:[dynamodb.java.codeexample.LowLevelLocalSecondaryIndexExample] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.LowLevelLocalSecondaryIndexExample] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelParallelScan.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelParallelScan.java index ccd57481eee..b104aa2e556 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelParallelScan.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelParallelScan.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.LowLevelParallelScan] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.LowLevelParallelScan] package com.amazonaws.codesamples.lowlevel; @@ -82,15 +61,14 @@ public static void main(String[] args) throws Exception { // Scan the table using multiple threads parallelScan(productCatalogTableName, scanItemLimit, parallelScanThreads); - } - catch (AmazonServiceException ase) { + } catch (AmazonServiceException ase) { System.err.println(ase.getMessage()); } } private static void parallelScan(String tableName, int itemLimit, int numberOfThreads) { System.out.println( - "Scanning " + tableName + " using " + numberOfThreads + " threads " + itemLimit + " items at a time"); + "Scanning " + tableName + " using " + numberOfThreads + " threads " + itemLimit + " items at a time"); ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads); // Divide DynamoDB table into logical segments @@ -134,14 +112,15 @@ public ScanSegmentTask(String tableName, int itemLimit, int totalSegments, int s @Override public void run() { System.out.println("Scanning " + tableName + " segment " + segment + " out of " + totalSegments - + " segments " + itemLimit + " items at a time..."); + + " segments " + itemLimit + " items at a time..."); Map exclusiveStartKey = null; int totalScannedItemCount = 0; int totalScanRequestCount = 0; try { while (true) { ScanRequest scanRequest = new ScanRequest().withTableName(tableName).withLimit(itemLimit) - .withExclusiveStartKey(exclusiveStartKey).withTotalSegments(totalSegments).withSegment(segment); + .withExclusiveStartKey(exclusiveStartKey).withTotalSegments(totalSegments) + .withSegment(segment); ScanResult result = client.scan(scanRequest); @@ -156,13 +135,11 @@ public void run() { break; } } - } - catch (AmazonServiceException ase) { + } catch (AmazonServiceException ase) { System.err.println(ase.getMessage()); - } - finally { + } finally { System.out.println("Scanned " + totalScannedItemCount + " items from segment " + segment + " out of " - + totalSegments + " of " + tableName + " with " + totalScanRequestCount + " scan requests"); + + totalSegments + " of " + tableName + " with " + totalScanRequestCount + " scan requests"); } } } @@ -198,8 +175,7 @@ private static void uploadProduct(String tableName, String productIndex) { client.putItem(itemRequest); item.clear(); - } - catch (AmazonServiceException ase) { + } catch (AmazonServiceException ase) { System.err.println("Failed to create item " + productIndex + " in " + tableName); } } @@ -211,20 +187,19 @@ private static void deleteTable(String tableName) { client.deleteTable(request); - } - catch (AmazonServiceException ase) { + } catch (AmazonServiceException ase) { System.err.println("Failed to delete table " + tableName + " " + ase); } } private static void createTable(String tableName, long readCapacityUnits, long writeCapacityUnits, - String partitionKeyName, String partitionKeyType) { + String partitionKeyName, String partitionKeyType) { createTable(tableName, readCapacityUnits, writeCapacityUnits, partitionKeyName, partitionKeyType, null, null); } private static void createTable(String tableName, long readCapacityUnits, long writeCapacityUnits, - String partitionKeyName, String partitionKeyType, String sortKeyName, String sortKeyType) { + String partitionKeyName, String partitionKeyType, String sortKeyName, String sortKeyType) { try { System.out.println("Creating table " + tableName); @@ -234,27 +209,27 @@ private static void createTable(String tableName, long readCapacityUnits, long w ks.add(new KeySchemaElement().withAttributeName(partitionKeyName).withKeyType(KeyType.HASH)); // Partition // key attributeDefinitions - .add(new AttributeDefinition().withAttributeName(partitionKeyName).withAttributeType(partitionKeyType)); + .add(new AttributeDefinition().withAttributeName(partitionKeyName) + .withAttributeType(partitionKeyType)); if (sortKeyName != null) { ks.add(new KeySchemaElement().withAttributeName(sortKeyName).withKeyType(KeyType.RANGE)); // Sort // key attributeDefinitions - .add(new AttributeDefinition().withAttributeName(sortKeyName).withAttributeType(sortKeyType)); + .add(new AttributeDefinition().withAttributeName(sortKeyName).withAttributeType(sortKeyType)); } // Provide initial provisioned throughput values as Java long data // types ProvisionedThroughput provisionedthroughput = new ProvisionedThroughput() - .withReadCapacityUnits(readCapacityUnits).withWriteCapacityUnits(writeCapacityUnits); + .withReadCapacityUnits(readCapacityUnits).withWriteCapacityUnits(writeCapacityUnits); CreateTableRequest request = new CreateTableRequest().withTableName(tableName).withKeySchema(ks) - .withProvisionedThroughput(provisionedthroughput).withAttributeDefinitions(attributeDefinitions); + .withProvisionedThroughput(provisionedthroughput).withAttributeDefinitions(attributeDefinitions); client.createTable(request); - } - catch (AmazonServiceException ase) { + } catch (AmazonServiceException ase) { System.err.println("Failed to create table " + tableName + " " + ase); } } @@ -273,8 +248,7 @@ private static void waitForTableToBecomeAvailable(String tableName) { return; try { Thread.sleep(1000 * 20); - } - catch (Exception e) { + } catch (Exception e) { } } throw new RuntimeException("Table " + tableName + " never went active"); @@ -293,15 +267,13 @@ private static void waitForTableToBeDeleted(String tableName) { System.out.println(" - current state: " + tableStatus); if (tableStatus.equals(TableStatus.ACTIVE.toString())) return; - } - catch (ResourceNotFoundException e) { + } catch (ResourceNotFoundException e) { System.out.println("Table " + tableName + " is not found. It was deleted."); return; } try { Thread.sleep(1000 * 20); - } - catch (Exception e) { + } catch (Exception e) { } } throw new RuntimeException("Table " + tableName + " was never deleted"); @@ -313,11 +285,11 @@ private static void printItem(int segment, Map attribute String attributeName = item.getKey(); AttributeValue value = item.getValue(); System.out.print(attributeName + " " + (value.getS() == null ? "" : "S=[" + value.getS() + "]") - + (value.getN() == null ? "" : "N=[" + value.getN() + "]") - + (value.getB() == null ? "" : "B=[" + value.getB() + "]") - + (value.getSS() == null ? "" : "SS=[" + value.getSS() + "]") - + (value.getNS() == null ? "" : "NS=[" + value.getNS() + "]") - + (value.getBS() == null ? "" : "BS=[" + value.getBS() + "]") + ", "); + + (value.getN() == null ? "" : "N=[" + value.getN() + "]") + + (value.getB() == null ? "" : "B=[" + value.getB() + "]") + + (value.getSS() == null ? "" : "SS=[" + value.getSS() + "]") + + (value.getNS() == null ? "" : "NS=[" + value.getNS() + "]") + + (value.getBS() == null ? "" : "BS=[" + value.getBS() + "]") + ", "); } // Move to next line System.out.println(); @@ -329,8 +301,7 @@ private static void shutDownExecutorService(ExecutorService executor) { if (!executor.awaitTermination(10, TimeUnit.SECONDS)) { executor.shutdownNow(); } - } - catch (InterruptedException e) { + } catch (InterruptedException e) { executor.shutdownNow(); // Preserve interrupt status @@ -339,4 +310,4 @@ private static void shutDownExecutorService(ExecutorService executor) { } } -// snippet-end:[dynamodb.java.codeexample.LowLevelParallelScan] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.LowLevelParallelScan] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelQuery.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelQuery.java index 5acadc81fdf..64bcc173170 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelQuery.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelQuery.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.LowLevelQuery] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.LowLevelQuery] package com.amazonaws.codesamples.lowlevel; @@ -61,7 +40,7 @@ private static void findRepliesForAThread(String forumName, String threadSubject String replyId = forumName + "#" + threadSubject; Condition partitionKeyCondition = new Condition().withComparisonOperator(ComparisonOperator.EQ) - .withAttributeValueList(new AttributeValue().withS(replyId)); + .withAttributeValueList(new AttributeValue().withS(replyId)); Map keyConditions = new HashMap(); keyConditions.put("Id", partitionKeyCondition); @@ -79,8 +58,8 @@ private static void findRepliesForAThreadSpecifyOptionalLimit(String forumName, Map lastEvaluatedKey = null; do { QueryRequest queryRequest = new QueryRequest().withTableName(tableName) - .withKeyConditions(makeReplyKeyConditions(forumName, threadSubject)).withLimit(1) - .withExclusiveStartKey(lastEvaluatedKey); + .withKeyConditions(makeReplyKeyConditions(forumName, threadSubject)).withLimit(1) + .withExclusiveStartKey(lastEvaluatedKey); QueryResult result = client.query(queryRequest); for (Map item : result.getItems()) { @@ -99,13 +78,13 @@ private static void findRepliesInLast15DaysWithConfig(String forumName, String t String twoWeeksAgoStr = df.format(twoWeeksAgo); Condition sortKeyCondition = new Condition().withComparisonOperator(ComparisonOperator.GT.toString()) - .withAttributeValueList(new AttributeValue().withS(twoWeeksAgoStr)); + .withAttributeValueList(new AttributeValue().withS(twoWeeksAgoStr)); Map keyConditions = makeReplyKeyConditions(forumName, threadSubject); keyConditions.put("ReplyDateTime", sortKeyCondition); QueryRequest queryRequest = new QueryRequest().withTableName(tableName).withKeyConditions(keyConditions) - .withProjectionExpression("Message, ReplyDateTime, PostedBy"); + .withProjectionExpression("Message, ReplyDateTime, PostedBy"); QueryResult result = client.query(queryRequest); for (Map item : result.getItems()) { @@ -123,13 +102,13 @@ private static void findRepliesPostedWithinTimePeriod(String forumName, String t String endDate = df.format(endDateMilli); Condition sortKeyCondition = new Condition().withComparisonOperator(ComparisonOperator.BETWEEN.toString()) - .withAttributeValueList(new AttributeValue().withS(startDate), new AttributeValue().withS(endDate)); + .withAttributeValueList(new AttributeValue().withS(startDate), new AttributeValue().withS(endDate)); Map keyConditions = makeReplyKeyConditions(forumName, threadSubject); keyConditions.put("ReplyDateTime", sortKeyCondition); QueryRequest queryRequest = new QueryRequest().withTableName(tableName).withKeyConditions(keyConditions) - .withProjectionExpression("Message, ReplyDateTime, PostedBy"); + .withProjectionExpression("Message, ReplyDateTime, PostedBy"); QueryResult result = client.query(queryRequest); for (Map item : result.getItems()) { @@ -145,8 +124,8 @@ private static void findRepliesUsingAFilterExpression(String forumName, String t expressionAttributeValues.put(":val", new AttributeValue().withS("User B")); QueryRequest queryRequest = new QueryRequest().withTableName(tableName).withKeyConditions(keyConditions) - .withFilterExpression("PostedBy = :val").withExpressionAttributeValues(expressionAttributeValues) - .withProjectionExpression("Message, ReplyDateTime, PostedBy"); + .withFilterExpression("PostedBy = :val").withExpressionAttributeValues(expressionAttributeValues) + .withProjectionExpression("Message, ReplyDateTime, PostedBy"); QueryResult result = client.query(queryRequest); for (Map item : result.getItems()) { @@ -159,11 +138,11 @@ private static void printItem(Map attributeList) { String attributeName = item.getKey(); AttributeValue value = item.getValue(); System.out.println(attributeName + " " + (value.getS() == null ? "" : "S=[" + value.getS() + "]") - + (value.getN() == null ? "" : "N=[" + value.getN() + "]") - + (value.getB() == null ? "" : "B=[" + value.getB() + "]") - + (value.getSS() == null ? "" : "SS=[" + value.getSS() + "]") - + (value.getNS() == null ? "" : "NS=[" + value.getNS() + "]") - + (value.getBS() == null ? "" : "BS=[" + value.getBS() + "] \n")); + + (value.getN() == null ? "" : "N=[" + value.getN() + "]") + + (value.getB() == null ? "" : "B=[" + value.getB() + "]") + + (value.getSS() == null ? "" : "SS=[" + value.getSS() + "]") + + (value.getNS() == null ? "" : "NS=[" + value.getNS() + "]") + + (value.getBS() == null ? "" : "BS=[" + value.getBS() + "] \n")); } } @@ -176,7 +155,7 @@ private static Map makeReplyKeyConditions(String forumName, S String replyId = forumName + "#" + threadSubject; Condition partitionKeyCondition = new Condition().withComparisonOperator(ComparisonOperator.EQ) - .withAttributeValueList(new AttributeValue().withS(replyId)); + .withAttributeValueList(new AttributeValue().withS(replyId)); Map keyConditions = new HashMap(); keyConditions.put("Id", partitionKeyCondition); @@ -185,4 +164,4 @@ private static Map makeReplyKeyConditions(String forumName, S } } -// snippet-end:[dynamodb.java.codeexample.LowLevelQuery] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.LowLevelQuery] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelScan.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelScan.java index f3c586a1152..eb00f9f8a04 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelScan.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelScan.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.LowLevelScan] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.LowLevelScan] package com.amazonaws.codesamples.lowlevel; @@ -51,8 +30,8 @@ private static void findProductsForPriceLessThanZero() { expressionAttributeValues.put(":pr", new AttributeValue().withN("100")); ScanRequest scanRequest = new ScanRequest().withTableName(tableName).withFilterExpression("Price < :pr") - .withExpressionAttributeValues(expressionAttributeValues) - .withProjectionExpression("Id, Title, ProductCategory, Price"); + .withExpressionAttributeValues(expressionAttributeValues) + .withProjectionExpression("Id, Title, ProductCategory, Price"); ScanResult result = client.scan(scanRequest); @@ -68,13 +47,13 @@ private static void printItem(Map attributeList) { String attributeName = item.getKey(); AttributeValue value = item.getValue(); System.out.println(attributeName + " " + (value.getS() == null ? "" : "S=[" + value.getS() + "]") - + (value.getN() == null ? "" : "N=[" + value.getN() + "]") - + (value.getB() == null ? "" : "B=[" + value.getB() + "]") - + (value.getSS() == null ? "" : "SS=[" + value.getSS() + "]") - + (value.getNS() == null ? "" : "NS=[" + value.getNS() + "]") - + (value.getBS() == null ? "" : "BS=[" + value.getBS() + "] \n")); + + (value.getN() == null ? "" : "N=[" + value.getN() + "]") + + (value.getB() == null ? "" : "B=[" + value.getB() + "]") + + (value.getSS() == null ? "" : "SS=[" + value.getSS() + "]") + + (value.getNS() == null ? "" : "NS=[" + value.getNS() + "]") + + (value.getBS() == null ? "" : "BS=[" + value.getBS() + "] \n")); } } } -// snippet-end:[dynamodb.java.codeexample.LowLevelScan] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.LowLevelScan] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelTableExample.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelTableExample.java index b43297cb273..91b496545bc 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelTableExample.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/codesamples/lowlevel/LowLevelTableExample.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.LowLevelTableExample] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.LowLevelTableExample] package com.amazonaws.codesamples.lowlevel; @@ -64,9 +43,9 @@ static void createExampleTable() { // Provide the initial provisioned throughput values as Java long data // types ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput().withReadCapacityUnits(5L) - .withWriteCapacityUnits(6L); + .withWriteCapacityUnits(6L); CreateTableRequest request = new CreateTableRequest().withTableName(tableName) - .withProvisionedThroughput(provisionedThroughput); + .withProvisionedThroughput(provisionedThroughput); ArrayList attributeDefinitions = new ArrayList(); attributeDefinitions.add(new AttributeDefinition().withAttributeName("Id").withAttributeType("N")); @@ -90,7 +69,7 @@ static void listMyTables() { do { ListTablesRequest listTablesRequest = new ListTablesRequest().withLimit(10) - .withExclusiveStartTableName(lastEvaluatedTableName); + .withExclusiveStartTableName(lastEvaluatedTableName); ListTablesResult result = client.listTables(listTablesRequest); lastEvaluatedTableName = result.getLastEvaluatedTableName(); @@ -105,22 +84,22 @@ static void listMyTables() { static void getTableInformation() { TableDescription tableDescription = client.describeTable(new DescribeTableRequest().withTableName(tableName)) - .getTable(); + .getTable(); System.out.format( - "Name: %s:\n" + "Status: %s \n" + "Provisioned Throughput (read capacity units/sec): %d \n" - + "Provisioned Throughput (write capacity units/sec): %d \n", - tableDescription.getTableName(), tableDescription.getTableStatus(), - tableDescription.getProvisionedThroughput().getReadCapacityUnits(), - tableDescription.getProvisionedThroughput().getWriteCapacityUnits()); + "Name: %s:\n" + "Status: %s \n" + "Provisioned Throughput (read capacity units/sec): %d \n" + + "Provisioned Throughput (write capacity units/sec): %d \n", + tableDescription.getTableName(), tableDescription.getTableStatus(), + tableDescription.getProvisionedThroughput().getReadCapacityUnits(), + tableDescription.getProvisionedThroughput().getWriteCapacityUnits()); } static void updateExampleTable() { ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput().withReadCapacityUnits(6L) - .withWriteCapacityUnits(7L); + .withWriteCapacityUnits(7L); UpdateTableRequest updateTableRequest = new UpdateTableRequest().withTableName(tableName) - .withProvisionedThroughput(provisionedThroughput); + .withProvisionedThroughput(provisionedThroughput); client.updateTable(updateTableRequest); waitForTableToBecomeAvailable(tableName); @@ -146,8 +125,7 @@ private static void waitForTableToBecomeAvailable(String tableName) { return; try { Thread.sleep(1000 * 20); - } - catch (Exception e) { + } catch (Exception e) { } } throw new RuntimeException("Table " + tableName + " never went active"); @@ -166,15 +144,13 @@ private static void waitForTableToBeDeleted(String tableName) { System.out.println(" - current state: " + tableStatus); if (tableStatus.equals(TableStatus.ACTIVE.toString())) return; - } - catch (ResourceNotFoundException e) { + } catch (ResourceNotFoundException e) { System.out.println("Table " + tableName + " is not found. It was deleted."); return; } try { Thread.sleep(1000 * 20); - } - catch (Exception e) { + } catch (Exception e) { } } throw new RuntimeException("Table " + tableName + " was never deleted"); @@ -182,4 +158,4 @@ private static void waitForTableToBeDeleted(String tableName) { } -// snippet-end:[dynamodb.java.codeexample.LowLevelTableExample] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.LowLevelTableExample] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/client/DynamoDBDynamicFaultInjection.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/client/DynamoDBDynamicFaultInjection.java index 69466458b8f..41581f7f258 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/client/DynamoDBDynamicFaultInjection.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/client/DynamoDBDynamicFaultInjection.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.DynamoDBDynamicFaultInjection] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.DynamoDBDynamicFaultInjection] package com.amazonaws.services.dynamodbv2.client; @@ -123,19 +102,17 @@ public static void main(String[] args) throws Exception { // Scan items for movies with a year attribute greater than 1985 Map scanFilter = new HashMap(); Condition condition = new Condition().withComparisonOperator(ComparisonOperator.GT.toString()) - .withAttributeValueList(new AttributeValue().withN("1985")); + .withAttributeValueList(new AttributeValue().withN("1985")); scanFilter.put("year", condition); ScanRequest scanRequest = new ScanRequest(TABLENAME).withScanFilter(scanFilter); ScanResult scanResult = dynamoDBClient.scan(scanRequest); logger.info("Result: " + scanResult); - } - catch (AmazonServiceException ase) { + } catch (AmazonServiceException ase) { logger.error("Service Exception: " + ase); - } - catch (AmazonClientException ace) { + } catch (AmazonClientException ace) { logger.error("Client Exception: " + ace); } @@ -177,8 +154,7 @@ private static void putItem(Map item) { PutItemRequest putItemRequest = new PutItemRequest(TABLENAME, item); PutItemResult putItemResult = dynamoDBClient.putItem(putItemRequest); logger.info("Result: " + putItemResult); - } - catch (Exception e) { + } catch (Exception e) { // TODO: handle exception } } @@ -195,19 +171,18 @@ private static void createTable() { // key ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput().withReadCapacityUnits(10L) - .withWriteCapacityUnits(10L); + .withWriteCapacityUnits(10L); CreateTableRequest request = new CreateTableRequest().withTableName(TABLENAME) - .withAttributeDefinitions(attributeDefinitions).withKeySchema(ks) - .withProvisionedThroughput(provisionedThroughput); + .withAttributeDefinitions(attributeDefinitions).withKeySchema(ks) + .withProvisionedThroughput(provisionedThroughput); try { CreateTableResult createdTableDescription = dynamoDBClient.createTable(request); logger.info("Created Table: " + createdTableDescription); // Wait for it to become active waitForTableToBecomeAvailable(TABLENAME); - } - catch (ResourceInUseException e) { + } catch (ResourceInUseException e) { logger.warn("Table already existed", e); } } @@ -236,8 +211,7 @@ private static void waitForTableToBecomeAvailable(String tableName) { while (System.currentTimeMillis() < endTime) { try { Thread.sleep(1000 * 20); - } - catch (Exception e) { + } catch (Exception e) { } try { DescribeTableRequest request = new DescribeTableRequest().withTableName(tableName); @@ -246,8 +220,7 @@ private static void waitForTableToBecomeAvailable(String tableName) { logger.info(" - current state: " + tableStatus); if (tableStatus.equals(TableStatus.ACTIVE.toString())) return; - } - catch (AmazonServiceException ase) { + } catch (AmazonServiceException ase) { if (ase.getErrorCode().equalsIgnoreCase("ResourceNotFoundException") == false) throw ase; } @@ -258,4 +231,4 @@ private static void waitForTableToBecomeAvailable(String tableName) { } -// snippet-end:[dynamodb.java.codeexample.DynamoDBDynamicFaultInjection] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.DynamoDBDynamicFaultInjection] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/client/FaultInjectionRequestHandler.java b/java/example_code/dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/client/FaultInjectionRequestHandler.java index f7d93782e57..694b82a94c8 100644 --- a/java/example_code/dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/client/FaultInjectionRequestHandler.java +++ b/java/example_code/dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/client/FaultInjectionRequestHandler.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.FaultInjectionRequestHandler] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.FaultInjectionRequestHandler] package com.amazonaws.services.dynamodbv2.client; @@ -78,8 +57,7 @@ public void beforeRequest(Request request) { logger.info("Injecting 500 ms delay"); Thread.sleep(500); - } - catch (InterruptedException ie) { + } catch (InterruptedException ie) { logger.info(ie); throw new RuntimeException(ie); } @@ -114,8 +92,7 @@ public void afterResponse(Request request, Response response) { // Add some delay try { Thread.sleep(500); - } - catch (InterruptedException ie) { + } catch (InterruptedException ie) { logger.info(ie); throw new RuntimeException(ie); } @@ -129,4 +106,4 @@ public void afterError(Request request, Response response, Exception e) { } } -// snippet-end:[dynamodb.java.codeexample.FaultInjectionRequestHandler] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.FaultInjectionRequestHandler] \ No newline at end of file diff --git a/java/example_code/dynamodb/src/test/java/com/amazonaws/services/dynamodbv2/DynamoDBLocalFixture.java b/java/example_code/dynamodb/src/test/java/com/amazonaws/services/dynamodbv2/DynamoDBLocalFixture.java index 2a9377f9851..d30c35718d5 100644 --- a/java/example_code/dynamodb/src/test/java/com/amazonaws/services/dynamodbv2/DynamoDBLocalFixture.java +++ b/java/example_code/dynamodb/src/test/java/com/amazonaws/services/dynamodbv2/DynamoDBLocalFixture.java @@ -1,28 +1,7 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.java.codeexample.DynamoDBLocalFixture] -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[dynamodb.java.codeexample.DynamoDBLocalFixture] package com.amazonaws.services.dynamodbv2; @@ -47,8 +26,7 @@ public static void main(String[] args) throws Exception { dynamodb = DynamoDBEmbedded.create(); // use the DynamoDB API with DynamoDBEmbedded listTables(dynamodb.listTables(), "DynamoDB Embedded"); - } - finally { + } finally { // Shutdown the thread pools in DynamoDB Local / Embedded if (dynamodb != null) { dynamodb.shutdown(); @@ -67,8 +45,7 @@ public static void main(String[] args) throws Exception { // use the DynamoDB API over HTTP listTables(dynamodb.listTables(), "DynamoDB Local over HTTP"); - } - finally { + } finally { // Stop the DynamoDB Local endpoint if (server != null) { server.stop(); @@ -84,4 +61,4 @@ public static void listTables(ListTablesResult result, String method) { } } -// snippet-end:[dynamodb.java.codeexample.DynamoDBLocalFixture] \ No newline at end of file +// snippet-end:[dynamodb.java.codeexample.DynamoDBLocalFixture] \ No newline at end of file diff --git a/java/example_code/ec2/run_example.sh b/java/example_code/ec2/run_example.sh index e0ec237d65d..12bf01499db 100755 --- a/java/example_code/ec2/run_example.sh +++ b/java/example_code/ec2/run_example.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 if [[ -z $* ]] ; then echo 'Supply the name of one of the example classes as an argument.' echo 'If there are arguments to the class, put them in quotes after the class name.' diff --git a/java/example_code/ec2/src/main/java/aws/example/ec2/AllocateAddress.java b/java/example_code/ec2/src/main/java/aws/example/ec2/AllocateAddress.java index 5c8f60f8b5e..0542c94ca0a 100644 --- a/java/example_code/ec2/src/main/java/aws/example/ec2/AllocateAddress.java +++ b/java/example_code/ec2/src/main/java/aws/example/ec2/AllocateAddress.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[AllocateAddress.java demonstrates how to allocate an elastic IP address for an EC2 instance.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-05-22] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.ec2; + import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.ec2.model.AllocateAddressRequest; @@ -33,43 +13,37 @@ /** * Allocates an elastic IP address for an EC2 instance */ -public class AllocateAddress -{ - public static void main(String[] args) - { - final String USAGE = - "To run this example, supply an instance id\n" + - "Ex: AllocateAddress \n"; +public class AllocateAddress { + public static void main(String[] args) { + final String USAGE = "To run this example, supply an instance id\n" + + "Ex: AllocateAddress \n"; - if (args.length != 1) { - System.out.println(USAGE); - System.exit(1); - } + if (args.length != 1) { + System.out.println(USAGE); + System.exit(1); + } - String instance_id = args[0]; + String instance_id = args[0]; - final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); + final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); - AllocateAddressRequest allocate_request = new AllocateAddressRequest() - .withDomain(DomainType.Vpc); + AllocateAddressRequest allocate_request = new AllocateAddressRequest() + .withDomain(DomainType.Vpc); - AllocateAddressResult allocate_response = - ec2.allocateAddress(allocate_request); + AllocateAddressResult allocate_response = ec2.allocateAddress(allocate_request); - String allocation_id = allocate_response.getAllocationId(); + String allocation_id = allocate_response.getAllocationId(); - AssociateAddressRequest associate_request = - new AssociateAddressRequest() - .withInstanceId(instance_id) - .withAllocationId(allocation_id); + AssociateAddressRequest associate_request = new AssociateAddressRequest() + .withInstanceId(instance_id) + .withAllocationId(allocation_id); - AssociateAddressResult associate_response = - ec2.associateAddress(associate_request); + AssociateAddressResult associate_response = ec2.associateAddress(associate_request); - System.out.printf( - "Successfully associated Elastic IP address %s " + - "with instance %s", - associate_response.getAssociationId(), - instance_id); - } + System.out.printf( + "Successfully associated Elastic IP address %s " + + "with instance %s", + associate_response.getAssociationId(), + instance_id); + } } diff --git a/java/example_code/ec2/src/main/java/aws/example/ec2/CreateInstance.java b/java/example_code/ec2/src/main/java/aws/example/ec2/CreateInstance.java index 0613f4e326b..e5d4a0b8d2d 100644 --- a/java/example_code/ec2/src/main/java/aws/example/ec2/CreateInstance.java +++ b/java/example_code/ec2/src/main/java/aws/example/ec2/CreateInstance.java @@ -1,80 +1,71 @@ -//snippet-sourcedescription:[CreateInstance.java demonstrates how to create an EC2 instance.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-05-22] -//snippet-sourceauthor:[soo-aws] -/* Copyright 2010-2019 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. - */ -//snippet-start:[ec2.java.create_instance.complete] -package aws.example.ec2; -import com.amazonaws.services.ec2.AmazonEC2; -import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; -import com.amazonaws.services.ec2.model.InstanceType; -import com.amazonaws.services.ec2.model.RunInstancesRequest; -import com.amazonaws.services.ec2.model.RunInstancesResult; -import com.amazonaws.services.ec2.model.Tag; -import com.amazonaws.services.ec2.model.CreateTagsRequest; -import com.amazonaws.services.ec2.model.CreateTagsResult; - -/** - * Creates an EC2 instance - */ -public class CreateInstance -{ - public static void main(String[] args) - { - final String USAGE = - "To run this example, supply an instance name and AMI image id\n" + - "Ex: CreateInstance \n"; - - if (args.length != 2) { - System.out.println(USAGE); - System.exit(1); - } - - String name = args[0]; - String ami_id = args[1]; - - final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); - - RunInstancesRequest run_request = new RunInstancesRequest() - .withImageId(ami_id) - .withInstanceType(InstanceType.T1Micro) - .withMaxCount(1) - .withMinCount(1); - - RunInstancesResult run_response = ec2.runInstances(run_request); - - String reservation_id = run_response.getReservation().getInstances().get(0).getInstanceId(); - - Tag tag = new Tag() - .withKey("Name") - .withValue(name); - - CreateTagsRequest tag_request = new CreateTagsRequest() - .withResources(reservation_id) - .withTags(tag); - - CreateTagsResult tag_response = ec2.createTags(tag_request); - - System.out.printf( - "Successfully started EC2 instance %s based on AMI %s", - reservation_id, ami_id); - } -} -//snippet-end:[ec2.java.create_instance.complete] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* Copyright 2010-2019 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. + */ +// snippet-start:[ec2.java.create_instance.complete] +package aws.example.ec2; + +import com.amazonaws.services.ec2.AmazonEC2; +import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; +import com.amazonaws.services.ec2.model.InstanceType; +import com.amazonaws.services.ec2.model.RunInstancesRequest; +import com.amazonaws.services.ec2.model.RunInstancesResult; +import com.amazonaws.services.ec2.model.Tag; +import com.amazonaws.services.ec2.model.CreateTagsRequest; +import com.amazonaws.services.ec2.model.CreateTagsResult; + +/** + * Creates an EC2 instance + */ +public class CreateInstance { + public static void main(String[] args) { + final String USAGE = "To run this example, supply an instance name and AMI image id\n" + + "Ex: CreateInstance \n"; + + if (args.length != 2) { + System.out.println(USAGE); + System.exit(1); + } + + String name = args[0]; + String ami_id = args[1]; + + final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); + + RunInstancesRequest run_request = new RunInstancesRequest() + .withImageId(ami_id) + .withInstanceType(InstanceType.T1Micro) + .withMaxCount(1) + .withMinCount(1); + + RunInstancesResult run_response = ec2.runInstances(run_request); + + String reservation_id = run_response.getReservation().getInstances().get(0).getInstanceId(); + + Tag tag = new Tag() + .withKey("Name") + .withValue(name); + + CreateTagsRequest tag_request = new CreateTagsRequest() + .withResources(reservation_id) + .withTags(tag); + + CreateTagsResult tag_response = ec2.createTags(tag_request); + + System.out.printf( + "Successfully started EC2 instance %s based on AMI %s", + reservation_id, ami_id); + } +} +// snippet-end:[ec2.java.create_instance.complete] diff --git a/java/example_code/ec2/src/main/java/aws/example/ec2/CreateKeyPair.java b/java/example_code/ec2/src/main/java/aws/example/ec2/CreateKeyPair.java index b6a041c6c73..ae7f805897a 100644 --- a/java/example_code/ec2/src/main/java/aws/example/ec2/CreateKeyPair.java +++ b/java/example_code/ec2/src/main/java/aws/example/ec2/CreateKeyPair.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[CreateKeyPair.java demonstrates how to create an EC2 key pair.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-05-22] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.ec2; + import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.ec2.model.CreateKeyPairRequest; @@ -30,13 +10,10 @@ /** * Creates an EC2 key pair */ -public class CreateKeyPair -{ - public static void main(String[] args) - { - final String USAGE = - "To run this example, supply a key pair name\n" + - "Ex: CreateKeyPair \n"; +public class CreateKeyPair { + public static void main(String[] args) { + final String USAGE = "To run this example, supply a key pair name\n" + + "Ex: CreateKeyPair \n"; if (args.length != 1) { System.out.println(USAGE); @@ -48,12 +25,12 @@ public static void main(String[] args) final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); CreateKeyPairRequest request = new CreateKeyPairRequest() - .withKeyName(key_name); + .withKeyName(key_name); CreateKeyPairResult response = ec2.createKeyPair(request); System.out.printf( - "Successfully created key pair named %s", - key_name); + "Successfully created key pair named %s", + key_name); } } diff --git a/java/example_code/ec2/src/main/java/aws/example/ec2/CreateSecurityGroup.java b/java/example_code/ec2/src/main/java/aws/example/ec2/CreateSecurityGroup.java index ebf3377ec08..8514493b60e 100644 --- a/java/example_code/ec2/src/main/java/aws/example/ec2/CreateSecurityGroup.java +++ b/java/example_code/ec2/src/main/java/aws/example/ec2/CreateSecurityGroup.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[CreateSecurityGroup.java demonstrates how to create an EC2 security group.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-05-22] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.ec2; + import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest; @@ -34,63 +14,56 @@ /** * Creates an EC2 security group. */ -public class CreateSecurityGroup -{ - public static void main(String[] args) - { - final String USAGE = - "To run this example, supply a group name, group description and vpc id\n" + - "Ex: CreateSecurityGroup \n"; +public class CreateSecurityGroup { + public static void main(String[] args) { + final String USAGE = "To run this example, supply a group name, group description and vpc id\n" + + "Ex: CreateSecurityGroup \n"; - if (args.length != 3) { - System.out.println(USAGE); - System.exit(1); - } + if (args.length != 3) { + System.out.println(USAGE); + System.exit(1); + } - String group_name = args[0]; - String group_desc = args[1]; - String vpc_id = args[2]; + String group_name = args[0]; + String group_desc = args[1]; + String vpc_id = args[2]; - final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); + final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); - CreateSecurityGroupRequest create_request = new - CreateSecurityGroupRequest() - .withGroupName(group_name) - .withDescription(group_desc) - .withVpcId(vpc_id); + CreateSecurityGroupRequest create_request = new CreateSecurityGroupRequest() + .withGroupName(group_name) + .withDescription(group_desc) + .withVpcId(vpc_id); - CreateSecurityGroupResult create_response = - ec2.createSecurityGroup(create_request); + CreateSecurityGroupResult create_response = ec2.createSecurityGroup(create_request); - System.out.printf( - "Successfully created security group named %s", - group_name); + System.out.printf( + "Successfully created security group named %s", + group_name); - IpRange ip_range = new IpRange() - .withCidrIp("0.0.0.0/0"); + IpRange ip_range = new IpRange() + .withCidrIp("0.0.0.0/0"); - IpPermission ip_perm = new IpPermission() - .withIpProtocol("tcp") - .withToPort(80) - .withFromPort(80) - .withIpv4Ranges(ip_range); + IpPermission ip_perm = new IpPermission() + .withIpProtocol("tcp") + .withToPort(80) + .withFromPort(80) + .withIpv4Ranges(ip_range); - IpPermission ip_perm2 = new IpPermission() - .withIpProtocol("tcp") - .withToPort(22) - .withFromPort(22) - .withIpv4Ranges(ip_range); + IpPermission ip_perm2 = new IpPermission() + .withIpProtocol("tcp") + .withToPort(22) + .withFromPort(22) + .withIpv4Ranges(ip_range); - AuthorizeSecurityGroupIngressRequest auth_request = new - AuthorizeSecurityGroupIngressRequest() - .withGroupName(group_name) - .withIpPermissions(ip_perm, ip_perm2); + AuthorizeSecurityGroupIngressRequest auth_request = new AuthorizeSecurityGroupIngressRequest() + .withGroupName(group_name) + .withIpPermissions(ip_perm, ip_perm2); - AuthorizeSecurityGroupIngressResult auth_response = - ec2.authorizeSecurityGroupIngress(auth_request); + AuthorizeSecurityGroupIngressResult auth_response = ec2.authorizeSecurityGroupIngress(auth_request); - System.out.printf( - "Successfully added ingress policy to security group %s", - group_name); - } + System.out.printf( + "Successfully added ingress policy to security group %s", + group_name); + } } diff --git a/java/example_code/ec2/src/main/java/aws/example/ec2/DeleteKeyPair.java b/java/example_code/ec2/src/main/java/aws/example/ec2/DeleteKeyPair.java index 8691331aadc..c171d160c04 100644 --- a/java/example_code/ec2/src/main/java/aws/example/ec2/DeleteKeyPair.java +++ b/java/example_code/ec2/src/main/java/aws/example/ec2/DeleteKeyPair.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[DeleteKeyPair.java demonstrates how to delete a key pair.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-05-22] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.ec2; + import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.ec2.model.DeleteKeyPairRequest; @@ -30,13 +10,10 @@ /** * Deletes a key pair. */ -public class DeleteKeyPair -{ - public static void main(String[] args) - { - final String USAGE = - "To run this example, supply a key pair name\n" + - "Ex: DeleteKeyPair \n"; +public class DeleteKeyPair { + public static void main(String[] args) { + final String USAGE = "To run this example, supply a key pair name\n" + + "Ex: DeleteKeyPair \n"; if (args.length != 1) { System.out.println(USAGE); @@ -48,11 +25,11 @@ public static void main(String[] args) final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); DeleteKeyPairRequest request = new DeleteKeyPairRequest() - .withKeyName(key_name); + .withKeyName(key_name); DeleteKeyPairResult response = ec2.deleteKeyPair(request); System.out.printf( - "Successfully deleted key pair named %s", key_name); + "Successfully deleted key pair named %s", key_name); } } diff --git a/java/example_code/ec2/src/main/java/aws/example/ec2/DeleteSecurityGroup.java b/java/example_code/ec2/src/main/java/aws/example/ec2/DeleteSecurityGroup.java index 27abdc3a87c..6b7c5edc853 100644 --- a/java/example_code/ec2/src/main/java/aws/example/ec2/DeleteSecurityGroup.java +++ b/java/example_code/ec2/src/main/java/aws/example/ec2/DeleteSecurityGroup.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[DeleteSecurityGroup.java demonstrates how to delete an EC2 security group.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-05-22] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.ec2; + import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.ec2.model.DeleteSecurityGroupRequest; @@ -30,13 +10,10 @@ /** * Deletes an EC2 security group */ -public class DeleteSecurityGroup -{ - public static void main(String[] args) - { - final String USAGE = - "To run this example, supply a security group id\n" + - "Ex: DeleteSecurityGroup \n"; +public class DeleteSecurityGroup { + public static void main(String[] args) { + final String USAGE = "To run this example, supply a security group id\n" + + "Ex: DeleteSecurityGroup \n"; if (args.length != 1) { System.out.println(USAGE); @@ -48,11 +25,11 @@ public static void main(String[] args) final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); DeleteSecurityGroupRequest request = new DeleteSecurityGroupRequest() - .withGroupId(group_id); + .withGroupId(group_id); DeleteSecurityGroupResult response = ec2.deleteSecurityGroup(request); System.out.printf( - "Successfully deleted security group with id %s", group_id); + "Successfully deleted security group with id %s", group_id); } } diff --git a/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeAccount.java b/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeAccount.java index 8ecbe403270..f3cd63d4adf 100644 --- a/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeAccount.java +++ b/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeAccount.java @@ -1,26 +1,8 @@ -//snippet-sourcedescription:[DescribeAccount.java demonstrates how to get information about the AWS account.] -//snippet-keyword:[SDK for Java 1.0] -//snippet-keyword:[Code Sample] -//snippet-service:[ec2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[scmacdon-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.ec2; + // snippet-start:[ec2.java1.describe_account.complete] // snippet-start:[ec2.java1.describe_account.import] import com.amazonaws.services.ec2.AmazonEC2; @@ -32,7 +14,6 @@ import java.util.ListIterator; // snippet-end:[ec2.java1.describe_account.import] - public class DescribeAccount { public static void main(String[] args) { @@ -40,26 +21,24 @@ public static void main(String[] args) { // snippet-start:[ec2.java1.describe_account.main] AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); - try{ + try { DescribeAccountAttributesResult accountResults = ec2.describeAccountAttributes(); List accountList = accountResults.getAccountAttributes(); - for (ListIterator iter = accountList.listIterator(); iter.hasNext(); ) { + for (ListIterator iter = accountList.listIterator(); iter.hasNext();) { AccountAttribute attribute = (AccountAttribute) iter.next(); - System.out.print("\n The name of the attribute is "+attribute.getAttributeName()); + System.out.print("\n The name of the attribute is " + attribute.getAttributeName()); List values = attribute.getAttributeValues(); - //iterate through the attribute values - for (ListIterator iterVals = values.listIterator(); iterVals.hasNext(); ) { + // iterate through the attribute values + for (ListIterator iterVals = values.listIterator(); iterVals.hasNext();) { AccountAttributeValue myValue = (AccountAttributeValue) iterVals.next(); - System.out.print("\n The value of the attribute is "+myValue.getAttributeValue()); + System.out.print("\n The value of the attribute is " + myValue.getAttributeValue()); } } System.out.print("Done"); - } - catch (Exception e) - { + } catch (Exception e) { e.getStackTrace(); } // snippet-end:[ec2.java1.describe_account.main] diff --git a/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeAddresses.java b/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeAddresses.java index 181dbc7c679..443df4e6d2f 100644 --- a/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeAddresses.java +++ b/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeAddresses.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[DescribeAddresses.java demonstrates how to get information about all of the elastic IP addresses.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-05-22] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.ec2; + import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.ec2.model.Address; @@ -30,20 +10,18 @@ /** * Describes all elastic IP addresses */ -public class DescribeAddresses -{ - public static void main(String[] args) - { +public class DescribeAddresses { + public static void main(String[] args) { final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); DescribeAddressesResult response = ec2.describeAddresses(); - for(Address address : response.getAddresses()) { + for (Address address : response.getAddresses()) { System.out.printf( "Found address with public IP %s, " + - "domain %s, " + - "allocation id %s " + - "and NIC id %s", + "domain %s, " + + "allocation id %s " + + "and NIC id %s", address.getPublicIp(), address.getDomain(), address.getAllocationId(), diff --git a/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeInstances.java b/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeInstances.java index 062c10eab12..c0311e2c3d8 100644 --- a/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeInstances.java +++ b/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeInstances.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[DescribeInstances.java demonstrates how to get a description of all EC2 instances associated with an AWS account.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-05-22] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.ec2; + import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.ec2.model.DescribeInstancesRequest; @@ -32,36 +12,34 @@ /** * Describes all EC2 instances associated with an AWS account */ -public class DescribeInstances -{ - public static void main(String[] args) - { +public class DescribeInstances { + public static void main(String[] args) { final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); boolean done = false; DescribeInstancesRequest request = new DescribeInstancesRequest(); - while(!done) { + while (!done) { DescribeInstancesResult response = ec2.describeInstances(request); - for(Reservation reservation : response.getReservations()) { - for(Instance instance : reservation.getInstances()) { + for (Reservation reservation : response.getReservations()) { + for (Instance instance : reservation.getInstances()) { System.out.printf( - "Found instance with id %s, " + - "AMI %s, " + - "type %s, " + - "state %s " + - "and monitoring state %s", - instance.getInstanceId(), - instance.getImageId(), - instance.getInstanceType(), - instance.getState().getName(), - instance.getMonitoring().getState()); + "Found instance with id %s, " + + "AMI %s, " + + "type %s, " + + "state %s " + + "and monitoring state %s", + instance.getInstanceId(), + instance.getImageId(), + instance.getInstanceType(), + instance.getState().getName(), + instance.getMonitoring().getState()); } } request.setNextToken(response.getNextToken()); - if(response.getNextToken() == null) { + if (response.getNextToken() == null) { done = true; } } diff --git a/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeKeyPairs.java b/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeKeyPairs.java index c9776159263..37bf388386d 100644 --- a/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeKeyPairs.java +++ b/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeKeyPairs.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[DescribeKeyPairs.java demonstrates how to get a description of all instance key pairs.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-05-22] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.ec2; + import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.ec2.model.DescribeKeyPairsResult; @@ -30,20 +10,18 @@ /** * Describes all instance key pairs */ -public class DescribeKeyPairs -{ - public static void main(String[] args) - { +public class DescribeKeyPairs { + public static void main(String[] args) { final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); DescribeKeyPairsResult response = ec2.describeKeyPairs(); - for(KeyPairInfo key_pair : response.getKeyPairs()) { + for (KeyPairInfo key_pair : response.getKeyPairs()) { System.out.printf( - "Found key pair with name %s " + - "and fingerprint %s", - key_pair.getKeyName(), - key_pair.getKeyFingerprint()); + "Found key pair with name %s " + + "and fingerprint %s", + key_pair.getKeyName(), + key_pair.getKeyFingerprint()); } } } diff --git a/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeRegionsAndZones.java b/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeRegionsAndZones.java index de4a1c5cc7b..ad276c46949 100644 --- a/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeRegionsAndZones.java +++ b/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeRegionsAndZones.java @@ -1,70 +1,61 @@ -//snippet-sourcedescription:[DescribeRegionsAndZones.java demonstrates how to get a description of all regions and zones.] -//snippet-keyword:[SDK for Java 1.0] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-05-22] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 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 aws.example.ec2; -// snippet-start:[ec2.java1.describe_region_and_zones.import] -import com.amazonaws.services.ec2.AmazonEC2; -import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; -import com.amazonaws.services.ec2.model.DescribeRegionsResult; -import com.amazonaws.services.ec2.model.Region; -import com.amazonaws.services.ec2.model.AvailabilityZone; -import com.amazonaws.services.ec2.model.DescribeAvailabilityZonesResult; -// snippet-end:[ec2.java1.describe_region_and_zones.import] - -/** - * Describes all regions and zones - */ -public class DescribeRegionsAndZones -{ - public static void main(String[] args) - { - final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); - -// snippet-start:[ec2.java1.describe_region_and_zones.regions] - DescribeRegionsResult regions_response = ec2.describeRegions(); - - for(Region region : regions_response.getRegions()) { - System.out.printf( - "Found region %s " + - "with endpoint %s", - region.getRegionName(), - region.getEndpoint()); - } -// snippet-end:[ec2.java1.describe_region_and_zones.regions] - -// snippet-start:[ec2.java1.describe_region_and_zones.zones] - DescribeAvailabilityZonesResult zones_response = - ec2.describeAvailabilityZones(); - - for(AvailabilityZone zone : zones_response.getAvailabilityZones()) { - System.out.printf( - "Found availability zone %s " + - "with status %s " + - "in region %s", - zone.getZoneName(), - zone.getState(), - zone.getRegionName()); - } -// snippet-end:[ec2.java1.describe_region_and_zones.zones] - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* + * Copyright 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 aws.example.ec2; + +// snippet-start:[ec2.java1.describe_region_and_zones.import] +import com.amazonaws.services.ec2.AmazonEC2; +import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; +import com.amazonaws.services.ec2.model.DescribeRegionsResult; +import com.amazonaws.services.ec2.model.Region; +import com.amazonaws.services.ec2.model.AvailabilityZone; +import com.amazonaws.services.ec2.model.DescribeAvailabilityZonesResult; +// snippet-end:[ec2.java1.describe_region_and_zones.import] + +/** + * Describes all regions and zones + */ +public class DescribeRegionsAndZones { + public static void main(String[] args) { + final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); + + // snippet-start:[ec2.java1.describe_region_and_zones.regions] + DescribeRegionsResult regions_response = ec2.describeRegions(); + + for (Region region : regions_response.getRegions()) { + System.out.printf( + "Found region %s " + + "with endpoint %s", + region.getRegionName(), + region.getEndpoint()); + } + // snippet-end:[ec2.java1.describe_region_and_zones.regions] + + // snippet-start:[ec2.java1.describe_region_and_zones.zones] + DescribeAvailabilityZonesResult zones_response = ec2.describeAvailabilityZones(); + + for (AvailabilityZone zone : zones_response.getAvailabilityZones()) { + System.out.printf( + "Found availability zone %s " + + "with status %s " + + "in region %s", + zone.getZoneName(), + zone.getState(), + zone.getRegionName()); + } + // snippet-end:[ec2.java1.describe_region_and_zones.zones] + } +} diff --git a/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeSecurityGroups.java b/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeSecurityGroups.java index 7073822703c..bb4e3a06d46 100644 --- a/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeSecurityGroups.java +++ b/java/example_code/ec2/src/main/java/aws/example/ec2/DescribeSecurityGroups.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[DescribeSecurityGroups.java demonstrates how to get a description of all security groups.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-05-22] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.ec2; + import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.ec2.model.DescribeSecurityGroupsRequest; @@ -31,13 +11,10 @@ /** * Describes all security groups */ -public class DescribeSecurityGroups -{ - public static void main(String[] args) - { - final String USAGE = - "To run this example, supply a group id\n" + - "Ex: DescribeSecurityGroups \n"; +public class DescribeSecurityGroups { + public static void main(String[] args) { + final String USAGE = "To run this example, supply a group id\n" + + "Ex: DescribeSecurityGroups \n"; if (args.length != 1) { System.out.println(USAGE); @@ -48,21 +25,19 @@ public static void main(String[] args) final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); - DescribeSecurityGroupsRequest request = - new DescribeSecurityGroupsRequest() + DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest() .withGroupIds(group_id); - DescribeSecurityGroupsResult response = - ec2.describeSecurityGroups(request); + DescribeSecurityGroupsResult response = ec2.describeSecurityGroups(request); - for(SecurityGroup group : response.getSecurityGroups()) { + for (SecurityGroup group : response.getSecurityGroups()) { System.out.printf( - "Found security group with id %s, " + - "vpc id %s " + - "and description %s", - group.getGroupId(), - group.getVpcId(), - group.getDescription()); + "Found security group with id %s, " + + "vpc id %s " + + "and description %s", + group.getGroupId(), + group.getVpcId(), + group.getDescription()); } } } diff --git a/java/example_code/ec2/src/main/java/aws/example/ec2/FindRunningInstances.java b/java/example_code/ec2/src/main/java/aws/example/ec2/FindRunningInstances.java index 0244248b4ae..5a176f82ee1 100644 --- a/java/example_code/ec2/src/main/java/aws/example/ec2/FindRunningInstances.java +++ b/java/example_code/ec2/src/main/java/aws/example/ec2/FindRunningInstances.java @@ -1,26 +1,5 @@ -/** - * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[FindRunningInstances.java demonstrates how to use a Filter to find running instances] -// snippet-service:[ec2] -// snippet-keyword:[Java] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-01-10] -// snippet-sourceauthor:[AWS-scmacdon] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[ec2.java1.running_instances.complete] package aws.example.ec2; @@ -45,22 +24,22 @@ public static void main(String[] args) { AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); try { - //Create the Filter to use to find running instances + // Create the Filter to use to find running instances Filter filter = new Filter("instance-state-name"); filter.withValues("running"); - //Create a DescribeInstancesRequest + // Create a DescribeInstancesRequest DescribeInstancesRequest request = new DescribeInstancesRequest(); request.withFilters(filter); // Find the running instances DescribeInstancesResult response = ec2.describeInstances(request); - for (Reservation reservation : response.getReservations()){ + for (Reservation reservation : response.getReservations()) { for (Instance instance : reservation.getInstances()) { - //Print out the results + // Print out the results System.out.printf( "Found reservation with id %s, " + "AMI %s, " + diff --git a/java/example_code/ec2/src/main/java/aws/example/ec2/MonitorInstance.java b/java/example_code/ec2/src/main/java/aws/example/ec2/MonitorInstance.java index d024c4f05cf..c44f4b0a609 100644 --- a/java/example_code/ec2/src/main/java/aws/example/ec2/MonitorInstance.java +++ b/java/example_code/ec2/src/main/java/aws/example/ec2/MonitorInstance.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[MonitorInstance.java demonstrates how to toggle detailed monitoring for an EC2 instance.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-05-22] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.ec2; + import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.ec2.model.MonitorInstancesRequest; @@ -32,16 +12,13 @@ /** * Toggles detailed monitoring for an EC2 instance */ -public class MonitorInstance -{ - public static void monitorInstance(String instance_id) - { +public class MonitorInstance { + public static void monitorInstance(String instance_id) { final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); - DryRunSupportedRequest dry_request = - () -> { + DryRunSupportedRequest dry_request = () -> { MonitorInstancesRequest request = new MonitorInstancesRequest() - .withInstanceIds(instance_id); + .withInstanceIds(instance_id); return request.getDryRunRequest(); }; @@ -50,8 +27,8 @@ public static void monitorInstance(String instance_id) if (!dry_response.isSuccessful()) { System.out.printf( - "Failed dry run to enable monitoring on instance %s", - instance_id); + "Failed dry run to enable monitoring on instance %s", + instance_id); throw dry_response.getDryRunResponse(); } @@ -62,18 +39,16 @@ public static void monitorInstance(String instance_id) ec2.monitorInstances(request); System.out.printf( - "Successfully enabled monitoring for instance %s", - instance_id); + "Successfully enabled monitoring for instance %s", + instance_id); } - public static void unmonitorInstance(String instance_id) - { + public static void unmonitorInstance(String instance_id) { final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); - DryRunSupportedRequest dry_request = - () -> { + DryRunSupportedRequest dry_request = () -> { UnmonitorInstancesRequest request = new UnmonitorInstancesRequest() - .withInstanceIds(instance_id); + .withInstanceIds(instance_id); return request.getDryRunRequest(); }; @@ -82,28 +57,26 @@ public static void unmonitorInstance(String instance_id) if (!dry_response.isSuccessful()) { System.out.printf( - "Failed dry run to disable monitoring on instance %s", - instance_id); + "Failed dry run to disable monitoring on instance %s", + instance_id); throw dry_response.getDryRunResponse(); } UnmonitorInstancesRequest request = new UnmonitorInstancesRequest() - .withInstanceIds(instance_id); + .withInstanceIds(instance_id); ec2.unmonitorInstances(request); System.out.printf( - "Successfully disabled monitoring for instance %s", - instance_id); + "Successfully disabled monitoring for instance %s", + instance_id); } - public static void main(String[] args) - { - final String USAGE = - "To run this example, supply an instance id and a monitoring " + - "status\n" + - "Ex: MonitorInstance \n"; + public static void main(String[] args) { + final String USAGE = "To run this example, supply an instance id and a monitoring " + + "status\n" + + "Ex: MonitorInstance \n"; if (args.length != 2) { System.out.println(USAGE); diff --git a/java/example_code/ec2/src/main/java/aws/example/ec2/RebootInstance.java b/java/example_code/ec2/src/main/java/aws/example/ec2/RebootInstance.java index 6599ae5955d..c2bf674e767 100644 --- a/java/example_code/ec2/src/main/java/aws/example/ec2/RebootInstance.java +++ b/java/example_code/ec2/src/main/java/aws/example/ec2/RebootInstance.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[RebootInstance.java demonstrates how to reboot and EC2 instance.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-05-22] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.ec2; + import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.ec2.model.RebootInstancesRequest; @@ -30,13 +10,10 @@ /** * Reboots and EC2 instance */ -public class RebootInstance -{ - public static void main(String[] args) - { - final String USAGE = - "To run this example, supply an instance id\n" + - "Ex: RebootInstance \n"; +public class RebootInstance { + public static void main(String[] args) { + final String USAGE = "To run this example, supply an instance id\n" + + "Ex: RebootInstance \n"; if (args.length != 1) { System.out.println(USAGE); @@ -48,11 +25,11 @@ public static void main(String[] args) final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); RebootInstancesRequest request = new RebootInstancesRequest() - .withInstanceIds(instance_id); + .withInstanceIds(instance_id); RebootInstancesResult response = ec2.rebootInstances(request); System.out.printf( - "Successfully rebooted instance %s", instance_id); + "Successfully rebooted instance %s", instance_id); } } diff --git a/java/example_code/ec2/src/main/java/aws/example/ec2/ReleaseAddress.java b/java/example_code/ec2/src/main/java/aws/example/ec2/ReleaseAddress.java index 1071e316b7c..bb0951002bd 100644 --- a/java/example_code/ec2/src/main/java/aws/example/ec2/ReleaseAddress.java +++ b/java/example_code/ec2/src/main/java/aws/example/ec2/ReleaseAddress.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[ReleaseAddress.java demonstrates how to release an elastic IP address.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-05-22] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.ec2; + import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.ec2.model.ReleaseAddressRequest; @@ -30,13 +10,10 @@ /** * Releases an elastic IP address */ -public class ReleaseAddress -{ - public static void main(String[] args) - { - final String USAGE = - "To run this example, supply an allocation ID.\n" + - "Ex: ReleaseAddress \n"; +public class ReleaseAddress { + public static void main(String[] args) { + final String USAGE = "To run this example, supply an allocation ID.\n" + + "Ex: ReleaseAddress \n"; if (args.length != 1) { System.out.println(USAGE); @@ -48,11 +25,11 @@ public static void main(String[] args) final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); ReleaseAddressRequest request = new ReleaseAddressRequest() - .withAllocationId(alloc_id); + .withAllocationId(alloc_id); ReleaseAddressResult response = ec2.releaseAddress(request); System.out.printf( - "Successfully released elastic IP address %s", alloc_id); + "Successfully released elastic IP address %s", alloc_id); } } diff --git a/java/example_code/ec2/src/main/java/aws/example/ec2/StartStopInstance.java b/java/example_code/ec2/src/main/java/aws/example/ec2/StartStopInstance.java index 29d78cc96c5..d0d33e14329 100644 --- a/java/example_code/ec2/src/main/java/aws/example/ec2/StartStopInstance.java +++ b/java/example_code/ec2/src/main/java/aws/example/ec2/StartStopInstance.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[StartStopInstance.java demonstrates how to start or stop an EC2 instance.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-service:[ec2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-05-22] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.ec2; + import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import com.amazonaws.services.ec2.model.DryRunResult; @@ -32,70 +12,63 @@ /** * Starts or stops and EC2 instance */ -public class StartStopInstance -{ - public static void startInstance(String instance_id) - { +public class StartStopInstance { + public static void startInstance(String instance_id) { final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); - DryRunSupportedRequest dry_request = - () -> { + DryRunSupportedRequest dry_request = () -> { StartInstancesRequest request = new StartInstancesRequest() - .withInstanceIds(instance_id); + .withInstanceIds(instance_id); return request.getDryRunRequest(); }; DryRunResult dry_response = ec2.dryRun(dry_request); - if(!dry_response.isSuccessful()) { + if (!dry_response.isSuccessful()) { System.out.printf( - "Failed dry run to start instance %s", instance_id); + "Failed dry run to start instance %s", instance_id); throw dry_response.getDryRunResponse(); } StartInstancesRequest request = new StartInstancesRequest() - .withInstanceIds(instance_id); + .withInstanceIds(instance_id); ec2.startInstances(request); System.out.printf("Successfully started instance %s", instance_id); } - public static void stopInstance(String instance_id) - { + public static void stopInstance(String instance_id) { final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); - DryRunSupportedRequest dry_request = - () -> { + DryRunSupportedRequest dry_request = () -> { StopInstancesRequest request = new StopInstancesRequest() - .withInstanceIds(instance_id); + .withInstanceIds(instance_id); return request.getDryRunRequest(); }; DryRunResult dry_response = ec2.dryRun(dry_request); - if(!dry_response.isSuccessful()) { + if (!dry_response.isSuccessful()) { System.out.printf( - "Failed dry run to stop instance %s", instance_id); + "Failed dry run to stop instance %s", instance_id); throw dry_response.getDryRunResponse(); } StopInstancesRequest request = new StopInstancesRequest() - .withInstanceIds(instance_id); + .withInstanceIds(instance_id); ec2.stopInstances(request); System.out.printf("Successfully stop instance %s", instance_id); } - public static void main(String[] args) - { - final String USAGE = - "To run this example, supply an instance id and start or stop\n" + - "Ex: StartStopInstance \n"; + public static void main(String[] args) { + final String USAGE = "To run this example, supply an instance id and start or stop\n" + + "Ex: StartStopInstance \n"; if (args.length != 1) { System.out.println(USAGE); @@ -106,13 +79,13 @@ public static void main(String[] args) boolean start; - if(args[1].equals("start")) { + if (args[1].equals("start")) { start = true; } else { start = false; } - if(start) { + if (start) { startInstance(instance_id); } else { stopInstance(instance_id); diff --git a/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/CatchDeleteError.java b/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/CatchDeleteError.java index e51a5320e24..cecb8aa38ee 100644 --- a/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/CatchDeleteError.java +++ b/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/CatchDeleteError.java @@ -1,26 +1,5 @@ -//snippet-sourcedescription:[CatchDeleteError.java demonstrates how to try to delete a job and catch an error.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Elastic Transcoder] -//snippet-service:[elastictranscoder] -//snippet-sourcetype:[snippet] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[elastictranscoder.java.catch_delete_error.import] try { DeleteJobRequest request = new DeleteJobRequest(jobId); diff --git a/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/HlsJobCreationSample.java b/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/HlsJobCreationSample.java index 4d1ab5bbb77..2709900ff2d 100644 --- a/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/HlsJobCreationSample.java +++ b/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/HlsJobCreationSample.java @@ -1,26 +1,5 @@ -//snippet-sourcedescription:[HlsJobCreationSample.java demonstrates how to create an HLS job.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Elastic Transcoder] -//snippet-service:[elastictranscoder] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[elastictranscoder.java.create_hls_job.import] package com.amazonaws.services.elastictranscoder.samples; @@ -38,100 +17,104 @@ /** * The purpose of this sample is to show how to create an HLS job and HLS - * playlist file which can be used to play an adaptive bitrate stream. HLS + * playlist file which can be used to play an adaptive bitrate stream. HLS * playlists can be played in the browser using tools such as jwplayer or using * media players such as VLC. */ public class HlsJobCreationSample { - // This is the ID of the Elastic Transcoder pipeline that was created when - // setting up your AWS environment: - // http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/sample-code.html#java-pipeline - private static final String PIPELINE_ID = "Enter your pipeline id here."; - - // This is the name of the input key that you would like to transcode. - private static final String INPUT_KEY = "Enter your input key here."; - - // HLS Presets that will be used to create an adaptive bitrate playlist. - private static final String HLS_64K_AUDIO_PRESET_ID = "1351620000001-200071"; - private static final String HLS_0400K_PRESET_ID = "1351620000001-200050"; - private static final String HLS_0600K_PRESET_ID = "1351620000001-200040"; - private static final String HLS_1000K_PRESET_ID = "1351620000001-200030"; - private static final String HLS_1500K_PRESET_ID = "1351620000001-200020"; - private static final String HLS_2000K_PRESET_ID = "1351620000001-200010"; - - // HLS Segment duration that will be targeted. - private static final String SEGMENT_DURATION = "2"; - - // All outputs will have this prefix prepended to their output key. - private static final String OUTPUT_KEY_PREFIX = "elastic-transcoder-samples/output/hls/"; - - // Clients are built using the default credentials provider chain. This - // will attempt to get your credentials in the following order: - // 1. Environment variables (AWS_ACCESS_KEY and AWS_SECRET_KEY). - // 2. Java system properties (AwsCredentials.properties). - // 3. Instance profile credentials on EC2 instances. - private static final AmazonElasticTranscoder amazonElasticTranscoder = new AmazonElasticTranscoderClient(); - - public static void main(String[] args) throws Exception { - - Job job = createElasticTranscoderHlsJob(); - System.out.println("HLS job has been created: " + job); - } - - /** - * Creates a job which outputs an HLS playlist for adaptive bitrate playback. - * @return Job that was created by Elastic Transcoder. - * @throws Exception - */ - private static Job createElasticTranscoderHlsJob() throws Exception { - - // Setup the job input using the provided input key. - JobInput input = new JobInput() - .withKey(INPUT_KEY); - - // Setup the job outputs using the HLS presets. - String outputKey = TranscoderSampleUtilities.inputKeyToOutputKey(INPUT_KEY); - CreateJobOutput hlsAudio = new CreateJobOutput() - .withKey("hlsAudio/" + outputKey) - .withPresetId(HLS_64K_AUDIO_PRESET_ID) - .withSegmentDuration(SEGMENT_DURATION); - CreateJobOutput hls0400k = new CreateJobOutput() - .withKey("hls0400k/" + outputKey) - .withPresetId(HLS_0400K_PRESET_ID) - .withSegmentDuration(SEGMENT_DURATION); - CreateJobOutput hls0600k = new CreateJobOutput() - .withKey("hls0600k/" + outputKey) - .withPresetId(HLS_0600K_PRESET_ID) - .withSegmentDuration(SEGMENT_DURATION); - CreateJobOutput hls1000k = new CreateJobOutput() - .withKey("hls1000k/" + outputKey) - .withPresetId(HLS_1000K_PRESET_ID) - .withSegmentDuration(SEGMENT_DURATION); - CreateJobOutput hls1500k = new CreateJobOutput() - .withKey("hls1500k/" + outputKey) - .withPresetId(HLS_1500K_PRESET_ID) - .withSegmentDuration(SEGMENT_DURATION); - CreateJobOutput hls2000k = new CreateJobOutput() - .withKey("hls2000k/" + outputKey) - .withPresetId(HLS_2000K_PRESET_ID) - .withSegmentDuration(SEGMENT_DURATION); - List outputs = Arrays.asList(hlsAudio, hls0400k, hls0600k, hls1000k, hls1500k, hls2000k); - - // Setup master playlist which can be used to play using adaptive bitrate. - CreateJobPlaylist playlist = new CreateJobPlaylist() - .withName("hls_" + outputKey) - .withFormat("HLSv3") - .withOutputKeys(hlsAudio.getKey(), hls0400k.getKey(), hls0600k.getKey(), hls1000k.getKey(), hls1500k.getKey(), hls2000k.getKey()); - - // Create the job. - CreateJobRequest createJobRequest = new CreateJobRequest() - .withPipelineId(PIPELINE_ID) - .withInput(input) - .withOutputKeyPrefix(OUTPUT_KEY_PREFIX + outputKey + "/") - .withOutputs(outputs) - .withPlaylists(playlist); - return amazonElasticTranscoder.createJob(createJobRequest).getJob(); - } + // This is the ID of the Elastic Transcoder pipeline that was created when + // setting up your AWS environment: + // http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/sample-code.html#java-pipeline + private static final String PIPELINE_ID = "Enter your pipeline id here."; + + // This is the name of the input key that you would like to transcode. + private static final String INPUT_KEY = "Enter your input key here."; + + // HLS Presets that will be used to create an adaptive bitrate playlist. + private static final String HLS_64K_AUDIO_PRESET_ID = "1351620000001-200071"; + private static final String HLS_0400K_PRESET_ID = "1351620000001-200050"; + private static final String HLS_0600K_PRESET_ID = "1351620000001-200040"; + private static final String HLS_1000K_PRESET_ID = "1351620000001-200030"; + private static final String HLS_1500K_PRESET_ID = "1351620000001-200020"; + private static final String HLS_2000K_PRESET_ID = "1351620000001-200010"; + + // HLS Segment duration that will be targeted. + private static final String SEGMENT_DURATION = "2"; + + // All outputs will have this prefix prepended to their output key. + private static final String OUTPUT_KEY_PREFIX = "elastic-transcoder-samples/output/hls/"; + + // Clients are built using the default credentials provider chain. This + // will attempt to get your credentials in the following order: + // 1. Environment variables (AWS_ACCESS_KEY and AWS_SECRET_KEY). + // 2. Java system properties (AwsCredentials.properties). + // 3. Instance profile credentials on EC2 instances. + private static final AmazonElasticTranscoder amazonElasticTranscoder = new AmazonElasticTranscoderClient(); + + public static void main(String[] args) throws Exception { + + Job job = createElasticTranscoderHlsJob(); + System.out.println("HLS job has been created: " + job); + } + + /** + * Creates a job which outputs an HLS playlist for adaptive bitrate playback. + * + * @return Job that was created by Elastic Transcoder. + * @throws Exception + */ + private static Job createElasticTranscoderHlsJob() throws Exception { + + // Setup the job input using the provided input key. + JobInput input = new JobInput() + .withKey(INPUT_KEY); + + // Setup the job outputs using the HLS presets. + String outputKey = TranscoderSampleUtilities.inputKeyToOutputKey(INPUT_KEY); + CreateJobOutput hlsAudio = new CreateJobOutput() + .withKey("hlsAudio/" + outputKey) + .withPresetId(HLS_64K_AUDIO_PRESET_ID) + .withSegmentDuration(SEGMENT_DURATION); + CreateJobOutput hls0400k = new CreateJobOutput() + .withKey("hls0400k/" + outputKey) + .withPresetId(HLS_0400K_PRESET_ID) + .withSegmentDuration(SEGMENT_DURATION); + CreateJobOutput hls0600k = new CreateJobOutput() + .withKey("hls0600k/" + outputKey) + .withPresetId(HLS_0600K_PRESET_ID) + .withSegmentDuration(SEGMENT_DURATION); + CreateJobOutput hls1000k = new CreateJobOutput() + .withKey("hls1000k/" + outputKey) + .withPresetId(HLS_1000K_PRESET_ID) + .withSegmentDuration(SEGMENT_DURATION); + CreateJobOutput hls1500k = new CreateJobOutput() + .withKey("hls1500k/" + outputKey) + .withPresetId(HLS_1500K_PRESET_ID) + .withSegmentDuration(SEGMENT_DURATION); + CreateJobOutput hls2000k = new CreateJobOutput() + .withKey("hls2000k/" + outputKey) + .withPresetId(HLS_2000K_PRESET_ID) + .withSegmentDuration(SEGMENT_DURATION); + List outputs = Arrays.asList(hlsAudio, hls0400k, hls0600k, hls1000k, hls1500k, + hls2000k); + + // Setup master playlist which can be used to play using adaptive bitrate. + CreateJobPlaylist playlist = new CreateJobPlaylist() + .withName("hls_" + outputKey) + .withFormat("HLSv3") + .withOutputKeys(hlsAudio.getKey(), hls0400k.getKey(), hls0600k.getKey(), + hls1000k.getKey(), + hls1500k.getKey(), hls2000k.getKey()); + + // Create the job. + CreateJobRequest createJobRequest = new CreateJobRequest() + .withPipelineId(PIPELINE_ID) + .withInput(input) + .withOutputKeyPrefix(OUTPUT_KEY_PREFIX + outputKey + "/") + .withOutputs(outputs) + .withPlaylists(playlist); + return amazonElasticTranscoder.createJob(createJobRequest).getJob(); + } } // snippet-end:[elastictranscoder.java.create_hls_job.import] diff --git a/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/JobStatusNotificationsSample.java b/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/JobStatusNotificationsSample.java index 5c9b6c86958..41bcba16468 100644 --- a/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/JobStatusNotificationsSample.java +++ b/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/JobStatusNotificationsSample.java @@ -1,26 +1,5 @@ -//snippet-sourcedescription:[JobStatusNotificationsSample.java demonstrates how to use notifications to track the status of a job.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Elastic Transcoder] -//snippet-service:[elastictranscoder] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[elastictranscoder.java.job_status_notification_sample.import] package com.amazonaws.services.elastictranscoder.samples; @@ -39,10 +18,9 @@ import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClient; - /** * The purpose of this sample is to show how job status notifications can be - * used to receive job status updates using an event-driven model. Using + * used to receive job status updates using an event-driven model. Using * notifications allows you to track job status of transcoding jobs in a * scalable fashion. * @@ -66,87 +44,91 @@ public class JobStatusNotificationsSample { // AWS environment. // http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/sample-code.html#java-sqs private static final String SQS_QUEUE_URL = "Enter your queue url here."; - + // This is the name of the input key that you would like to transcode. private static final String INPUT_KEY = "Enter your input key here."; - + // This will generate a 480p 16:9 mp4 output. private static final String PRESET_ID = "1351620000001-000020"; - + // All outputs will have this prefix prepended to their output key. private static final String OUTPUT_KEY_PREFIX = "elastic-transcoder-samples/output/"; - - // Clients are built using the default credentials provider chain. This + + // Clients are built using the default credentials provider chain. This // will attempt to get your credentials in the following order: - // 1. Environment variables (AWS_ACCESS_KEY and AWS_SECRET_KEY). - // 2. Java system properties (AwsCredentials.properties). - // 3. Instance profile credentials on EC2 instances. + // 1. Environment variables (AWS_ACCESS_KEY and AWS_SECRET_KEY). + // 2. Java system properties (AwsCredentials.properties). + // 3. Instance profile credentials on EC2 instances. private static final AmazonSQS amazonSqs = new AmazonSQSClient(); private static final AmazonElasticTranscoder amazonElasticTranscoder = new AmazonElasticTranscoderClient(); - + public static void main(String[] args) throws Exception { - + // Setup our notification worker. - SqsQueueNotificationWorker sqsQueueNotificationWorker = new SqsQueueNotificationWorker(amazonSqs, SQS_QUEUE_URL); + SqsQueueNotificationWorker sqsQueueNotificationWorker = new SqsQueueNotificationWorker(amazonSqs, + SQS_QUEUE_URL); Thread notificationThread = new Thread(sqsQueueNotificationWorker); notificationThread.start(); - + // Create a job in Elastic Transcoder. String jobId = createElasticTranscoderJob(); - + // Wait for the job we created to complete. System.out.println("Waiting for job to complete: " + jobId); waitForJobToComplete(jobId, sqsQueueNotificationWorker); } - + /** * Creates a job in Elastic Transcoder using the configured pipeline, input * key, preset, and output key prefix. + * * @return Job ID of the job that was created in Elastic Transcoder. * @throws Exception */ private static String createElasticTranscoderJob() throws Exception { - + // Setup the job input using the provided input key. JobInput input = new JobInput() - .withKey(INPUT_KEY); - + .withKey(INPUT_KEY); + // Setup the job output using the provided input key to generate an output key. List outputs = new ArrayList(); CreateJobOutput output = new CreateJobOutput() - .withKey(TranscoderSampleUtilities.inputKeyToOutputKey(INPUT_KEY)) - .withPresetId(PRESET_ID); + .withKey(TranscoderSampleUtilities.inputKeyToOutputKey(INPUT_KEY)) + .withPresetId(PRESET_ID); outputs.add(output); - + // Create a job on the specified pipeline and return the job ID. CreateJobRequest createJobRequest = new CreateJobRequest() - .withPipelineId(PIPELINE_ID) - .withOutputKeyPrefix(OUTPUT_KEY_PREFIX) - .withInput(input) - .withOutputs(outputs); + .withPipelineId(PIPELINE_ID) + .withOutputKeyPrefix(OUTPUT_KEY_PREFIX) + .withInput(input) + .withOutputs(outputs); return amazonElasticTranscoder.createJob(createJobRequest).getJob().getId(); } - + /** * Waits for the specified job to complete by adding a handler to the SQS - * notification worker that is polling for status updates. This method + * notification worker that is polling for status updates. This method * will block until the specified job completes. + * * @param jobId * @param sqsQueueNotificationWorker * @throws InterruptedException */ - private static void waitForJobToComplete(final String jobId, SqsQueueNotificationWorker sqsQueueNotificationWorker) throws InterruptedException { - + private static void waitForJobToComplete(final String jobId, SqsQueueNotificationWorker sqsQueueNotificationWorker) + throws InterruptedException { + // Create a handler that will wait for this specific job to complete. JobStatusNotificationHandler handler = new JobStatusNotificationHandler() { - + @Override public void handle(JobStatusNotification jobStatusNotification) { if (jobStatusNotification.getJobId().equals(jobId)) { System.out.println(jobStatusNotification); - + if (jobStatusNotification.getState().isTerminalState()) { - synchronized(this) { + synchronized (this) { this.notifyAll(); } } @@ -154,12 +136,12 @@ public void handle(JobStatusNotification jobStatusNotification) { } }; sqsQueueNotificationWorker.addHandler(handler); - + // Wait for job to complete. - synchronized(handler) { + synchronized (handler) { handler.wait(); } - + // When job completes, shutdown the sqs notification worker. sqsQueueNotificationWorker.shutdown(); } diff --git a/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/model/JobStatusNotification.java b/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/model/JobStatusNotification.java index 82775757a06..fc4ce2b8c8a 100644 --- a/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/model/JobStatusNotification.java +++ b/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/model/JobStatusNotification.java @@ -1,26 +1,5 @@ -//snippet-sourcedescription:[JobStatusNotification.java provides a model for job status notifications.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Elastic Transcoder] -//snippet-service:[elastictranscoder] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[elastictranscoder.java.job_status_notification.import] package com.amazonaws.services.elastictranscoder.samples.model; @@ -30,10 +9,10 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.ObjectMapper; -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) public class JobStatusNotification { - @JsonIgnoreProperties(ignoreUnknown=true) + @JsonIgnoreProperties(ignoreUnknown = true) public static class JobInput { private String key; @@ -50,8 +29,8 @@ public String toString() { return "JobInput [key=" + key + "]"; } } - - @JsonIgnoreProperties(ignoreUnknown=true) + + @JsonIgnoreProperties(ignoreUnknown = true) public static class JobOutput { private String id; private String presetId; @@ -60,55 +39,55 @@ public static class JobOutput { private String statusDetail; private int errorCode; - + public String getId() { return id; } - + public void setId(String id) { this.id = id; } - + public String getPresetId() { return presetId; } - + public void setPresetId(String presetId) { this.presetId = presetId; } - + public String getKey() { return key; } - + public void setKey(String key) { this.key = key; } - + public String getStatus() { return status; } - + public void setStatus(String status) { this.status = status; } - + public String getStatusDetail() { return statusDetail; } - + public void setStatusDetail(String statusDetail) { this.statusDetail = statusDetail; } - + public int getErrorCode() { return errorCode; } - + public void setErrorCode(int errorCode) { this.errorCode = errorCode; } - + @Override public String toString() { return "JobOutput [id=" + id + ", presetId=" + presetId + ", key=" @@ -116,19 +95,19 @@ public String toString() { + statusDetail + ", errorCode=" + errorCode + "]"; } } - + public static enum JobState { PROGRESSING, COMPLETED, ERROR; - + public boolean isTerminalState() { return this.equals(JobState.COMPLETED) || this.equals(JobState.ERROR); } } - + private static final ObjectMapper mapper = new ObjectMapper(); - + private JobState state; private int errorCode; private String version; @@ -137,71 +116,71 @@ public boolean isTerminalState() { private JobInput input; private String outputKeyPrefix; private List outputs; - + public JobState getState() { return state; } - + public void setState(JobState state) { this.state = state; } - + public int getErrorCode() { return errorCode; } - + public void setErrorCode(int errorCode) { this.errorCode = errorCode; } - + public String getVersion() { return version; } - + public void setVersion(String version) { this.version = version; } - + public String getJobId() { return jobId; } - + public void setJobId(String jobId) { this.jobId = jobId; } - + public String getPipelineId() { return pipelineId; } - + public void setPipelineId(String pipelineId) { this.pipelineId = pipelineId; } - + public JobInput getInput() { return input; } - + public void setInput(JobInput input) { this.input = input; } - + public String getOutputKeyPrefix() { return outputKeyPrefix; } - + public void setOutputKeyPrefix(String outputKeyPrefix) { this.outputKeyPrefix = outputKeyPrefix; } - + public List getOutputs() { return outputs; } - + public void setOutputs(List outputs) { this.outputs = outputs; } - + @Override public String toString() { return "JobStatusNotification [state=" + state + ", errorCode=" diff --git a/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/model/JobStatusNotificationHandler.java b/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/model/JobStatusNotificationHandler.java index 46e23d7d6cb..3acfbeda4e8 100644 --- a/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/model/JobStatusNotificationHandler.java +++ b/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/model/JobStatusNotificationHandler.java @@ -1,26 +1,5 @@ -//snippet-sourcedescription:[JobStatusNotificationHandler.java provides a handler for job notifications.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Elastic Transcoder] -//snippet-service:[elastictranscoder] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[elastictranscoder.java.job_status_notification_handler.import] package com.amazonaws.services.elastictranscoder.samples.model; diff --git a/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/model/Notification.java b/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/model/Notification.java index 254537438a9..6c8dfd7649a 100644 --- a/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/model/Notification.java +++ b/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/model/Notification.java @@ -1,33 +1,12 @@ -//snippet-sourcedescription:[Notification.java provides a model for job notifications.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Elastic Transcoder] -//snippet-service:[elastictranscoder] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[elastictranscoder.java.notification.import] package com.amazonaws.services.elastictranscoder.samples.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) public class Notification { private String type; @@ -40,97 +19,97 @@ public class Notification { private String signature; private String signingCertURL; private String unsubscribeURL; - - @JsonProperty(value="Type") + + @JsonProperty(value = "Type") public String getType() { return type; } - + public void setType(String type) { this.type = type; } - - @JsonProperty(value="MessageId") + + @JsonProperty(value = "MessageId") public String getMessageId() { return messageId; } - + public void setMessageId(String messageId) { this.messageId = messageId; } - - @JsonProperty(value="TopicArn") + + @JsonProperty(value = "TopicArn") public String getTopicArn() { return topicArn; } - + public void setTopicArn(String topicArn) { this.topicArn = topicArn; } - - @JsonProperty(value="Subject") + + @JsonProperty(value = "Subject") public String getSubject() { return subject; } - + public void setSubject(String subject) { this.subject = subject; } - - @JsonProperty(value="Message") + + @JsonProperty(value = "Message") public MESSAGE_TYPE getMessage() { return message; } - + public void setNotification(MESSAGE_TYPE message) { this.message = message; } - - @JsonProperty(value="Timestamp") + + @JsonProperty(value = "Timestamp") public String getTimestamp() { return timestamp; } - + public void setTimestamp(String timestamp) { this.timestamp = timestamp; } - - @JsonProperty(value="SignatureVersion") + + @JsonProperty(value = "SignatureVersion") public String getSignatureVersion() { return signatureVersion; } - + public void setSignatureVersion(String signatureVersion) { this.signatureVersion = signatureVersion; } - - @JsonProperty(value="Signature") + + @JsonProperty(value = "Signature") public String getSignature() { return signature; } - + public void setSignature(String signature) { this.signature = signature; } - - @JsonProperty(value="SigningCertURL") + + @JsonProperty(value = "SigningCertURL") public String getSigningCertURL() { return signingCertURL; } - + public void setSigningCertURL(String signingCertURL) { this.signingCertURL = signingCertURL; } - - @JsonProperty(value="UnsubscribeURL") + + @JsonProperty(value = "UnsubscribeURL") public String getUnsubscribeURL() { return unsubscribeURL; } - + public void setUnsubscribeURL(String unsubscribeURL) { this.unsubscribeURL = unsubscribeURL; } - + @Override public String toString() { return "Notification [type=" + type + ", messageId=" + messageId diff --git a/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/utils/SqsQueueNotificationWorker.java b/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/utils/SqsQueueNotificationWorker.java index 03d2d23c9fe..9e19acbc7ea 100644 --- a/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/utils/SqsQueueNotificationWorker.java +++ b/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/utils/SqsQueueNotificationWorker.java @@ -1,26 +1,5 @@ -//snippet-sourcedescription:[SqsQueueNotificationWorker.java provides a worker for handling job notifications.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Elastic Transcoder] -//snippet-service:[elastictranscoder] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[elastictranscoder.java.sqs_queue_notification_worker.import] package com.amazonaws.services.elastictranscoder.samples.utils; @@ -49,50 +28,50 @@ public class SqsQueueNotificationWorker implements Runnable { private static final int VISIBILITY_TIMEOUT = 15; private static final int WAIT_TIME_SECONDS = 15; private static final ObjectMapper mapper = new ObjectMapper(); - + private AmazonSQS amazonSqs; private String queueUrl; private List handlers; - + private volatile boolean shutdown = false; - + public SqsQueueNotificationWorker(AmazonSQS amazonSqs, String queueUrl) { this.amazonSqs = amazonSqs; this.queueUrl = queueUrl; this.handlers = new ArrayList(); } - + public void addHandler(JobStatusNotificationHandler jobStatusNotificationHandler) { - synchronized(handlers) { + synchronized (handlers) { this.handlers.add(jobStatusNotificationHandler); } } - + public void removeHandler(JobStatusNotificationHandler jobStatusNotificationHandler) { - synchronized(handlers) { + synchronized (handlers) { this.handlers.remove(jobStatusNotificationHandler); } } - + @Override public void run() { ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest() - .withQueueUrl(queueUrl) - .withMaxNumberOfMessages(MAX_NUMBER_OF_MESSAGES) - .withVisibilityTimeout(VISIBILITY_TIMEOUT) - .withWaitTimeSeconds(WAIT_TIME_SECONDS); - + .withQueueUrl(queueUrl) + .withMaxNumberOfMessages(MAX_NUMBER_OF_MESSAGES) + .withVisibilityTimeout(VISIBILITY_TIMEOUT) + .withWaitTimeSeconds(WAIT_TIME_SECONDS); + while (!shutdown) { - // Long pole the SQS queue. This will return as soon as a message + // Long pole the SQS queue. This will return as soon as a message // is received, or when WAIT_TIME_SECONDS has elapsed. List messages = amazonSqs.receiveMessage(receiveMessageRequest).getMessages(); if (messages == null) { // If there were no messages during this poll period, SQS - // will return this list as null. Continue polling. + // will return this list as null. Continue polling. continue; } - - synchronized(handlers) { + + synchronized (handlers) { for (Message message : messages) { try { // Parse notification and call handlers. @@ -103,16 +82,19 @@ public void run() { } catch (IOException e) { System.out.println("Failed to convert notification: " + e.getMessage()); } - + // Delete the message from the queue. - amazonSqs.deleteMessage(new DeleteMessageRequest().withQueueUrl(queueUrl).withReceiptHandle(message.getReceiptHandle())); + amazonSqs.deleteMessage(new DeleteMessageRequest().withQueueUrl(queueUrl) + .withReceiptHandle(message.getReceiptHandle())); } } } } - + private JobStatusNotification parseNotification(Message message) throws IOException { - Notification notification = mapper.readValue(message.getBody(), new TypeReference>() {}); + Notification notification = mapper.readValue(message.getBody(), + new TypeReference>() { + }); return notification.getMessage(); } diff --git a/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/utils/TranscoderSampleUtilities.java b/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/utils/TranscoderSampleUtilities.java index d5282a366d7..5ee752f0398 100644 --- a/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/utils/TranscoderSampleUtilities.java +++ b/java/example_code/elastictranscoder/src/main/java/aws/example/elastictranscoder/utils/TranscoderSampleUtilities.java @@ -1,26 +1,5 @@ -//snippet-sourcedescription:[TranscoderSampleUtilities.java provides basic useful utils for transcoding jobs.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Elastic Transcoder] -//snippet-service:[elastictranscoder] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[elastictranscoder.java.sample_utilities.import] package com.amazonaws.services.elastictranscoder.samples.utils; @@ -31,31 +10,34 @@ public final class TranscoderSampleUtilities { private static final char[] HEX_ENCODING = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; - + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + /** * Method converts a byte array into a hex string. + * * @param input * @return String representing hex encoded byte array. */ public static String toHexString(byte[] input) { StringBuilder builder = new StringBuilder(input.length * 2); for (byte b : input) { - builder.append(HEX_ENCODING[((int)b & 0xff) >> 4]); + builder.append(HEX_ENCODING[((int) b & 0xff) >> 4]); builder.append(HEX_ENCODING[b & 0x0f]); } return builder.toString(); } - + /** * Method converts an input key into an output key but computing * BASE16(SHA256(UTF-8(inputKey))). + * * @param inputKey * @return Output key generated from the input key. * @throws NoSuchAlgorithmException * @throws UnsupportedEncodingException */ - public static String inputKeyToOutputKey(String inputKey) throws NoSuchAlgorithmException, UnsupportedEncodingException { + public static String inputKeyToOutputKey(String inputKey) + throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest digest = MessageDigest.getInstance("SHA-256"); return toHexString(digest.digest(inputKey.getBytes("UTF-8"))); } diff --git a/java/example_code/emr/create-spark-cluster.java b/java/example_code/emr/create-spark-cluster.java index 0818fc97811..3fd4ea7816d 100755 --- a/java/example_code/emr/create-spark-cluster.java +++ b/java/example_code/emr/create-spark-cluster.java @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[create-spark-cluster.java demonstrates how to create a cluster with Spark installed.] -// snippet-service:[elasticmapreduce] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon EMR] -// snippet-keyword:[Code Sample] -// snippet-keyword:[RunJobFlowRequest] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] // snippet-start:[emr.java.createcluster.spark] import com.amazonaws.AmazonClientException; @@ -35,49 +14,48 @@ public class Main { - public static void main(String[] args) { - AWSCredentials credentials_profile = null; - try { - credentials_profile = new ProfileCredentialsProvider("default").getCredentials(); - } catch (Exception e) { - throw new AmazonClientException( - "Cannot load credentials from .aws/credentials file. " + - "Make sure that the credentials file exists and the profile name is specified within it.", - e); - } - - AmazonElasticMapReduce emr = AmazonElasticMapReduceClientBuilder.standard() - .withCredentials(new AWSStaticCredentialsProvider(credentials_profile)) - .withRegion(Regions.US_WEST_1) - .build(); - - // create a step to enable debugging in the AWS Management Console - StepFactory stepFactory = new StepFactory(); - StepConfig enabledebugging = new StepConfig() - .withName("Enable debugging") - .withActionOnFailure("TERMINATE_JOB_FLOW") - .withHadoopJarStep(stepFactory.newEnableDebuggingStep()); - - Application spark = new Application().withName("Spark"); + public static void main(String[] args) { + AWSCredentials credentials_profile = null; + try { + credentials_profile = new ProfileCredentialsProvider("default").getCredentials(); + } catch (Exception e) { + throw new AmazonClientException( + "Cannot load credentials from .aws/credentials file. " + + "Make sure that the credentials file exists and the profile name is specified within it.", + e); + } + + AmazonElasticMapReduce emr = AmazonElasticMapReduceClientBuilder.standard() + .withCredentials(new AWSStaticCredentialsProvider(credentials_profile)) + .withRegion(Regions.US_WEST_1) + .build(); + + // create a step to enable debugging in the AWS Management Console + StepFactory stepFactory = new StepFactory(); + StepConfig enabledebugging = new StepConfig() + .withName("Enable debugging") + .withActionOnFailure("TERMINATE_JOB_FLOW") + .withHadoopJarStep(stepFactory.newEnableDebuggingStep()); - RunJobFlowRequest request = new RunJobFlowRequest() - .withName("Spark Cluster") - .withReleaseLabel("emr-5.20.0") - .withSteps(enabledebugging) - .withApplications(spark) - .withLogUri("s3://path/to/my/logs/") - .withServiceRole("EMR_DefaultRole") - .withJobFlowRole("EMR_EC2_DefaultRole") - .withInstances(new JobFlowInstancesConfig() - .withEc2SubnetId("subnet-12ab3c45") - .withEc2KeyName("myEc2Key") - .withInstanceCount(3) - .withKeepJobFlowAliveWhenNoSteps(true) - .withMasterInstanceType("m4.large") - .withSlaveInstanceType("m4.large") - ); - RunJobFlowResult result = emr.runJobFlow(request); - System.out.println("The cluster ID is " + result.toString()); - } + Application spark = new Application().withName("Spark"); + + RunJobFlowRequest request = new RunJobFlowRequest() + .withName("Spark Cluster") + .withReleaseLabel("emr-5.20.0") + .withSteps(enabledebugging) + .withApplications(spark) + .withLogUri("s3://path/to/my/logs/") + .withServiceRole("EMR_DefaultRole") + .withJobFlowRole("EMR_EC2_DefaultRole") + .withInstances(new JobFlowInstancesConfig() + .withEc2SubnetId("subnet-12ab3c45") + .withEc2KeyName("myEc2Key") + .withInstanceCount(3) + .withKeepJobFlowAliveWhenNoSteps(true) + .withMasterInstanceType("m4.large") + .withSlaveInstanceType("m4.large")); + RunJobFlowResult result = emr.runJobFlow(request); + System.out.println("The cluster ID is " + result.toString()); + } } // snippet-end:[emr.java.createcluster.spark] diff --git a/java/example_code/emr/create_cluster.java b/java/example_code/emr/create_cluster.java index b635267d62b..8de570b4346 100755 --- a/java/example_code/emr/create_cluster.java +++ b/java/example_code/emr/create_cluster.java @@ -1,29 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[create_cluster.java demonstrates how to create a long-running Amazon EMR cluster with a list of applications installed and debugging enabled.] -// snippet-service:[elasticmapreduce] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon EMR] -// snippet-keyword:[Code Sample] -// snippet-keyword:[RunJobFlowRequest] -// snippet-keyword:[AmazonElasticMapReduceClientBuilder] -// snippet-keyword:[newEnableDebuggingStep] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] // snippet-start:[emr.java.create-cluster.runjobflow] import com.amazonaws.AmazonClientException; import com.amazonaws.auth.AWSCredentials; @@ -37,54 +14,58 @@ public class Main { public static void main(String[] args) { - AWSCredentialsProvider profile = null; + AWSCredentialsProvider profile = null; try { - credentials_profile = new ProfileCredentialsProvider("default"); // specifies any named profile in .aws/credentials as the credentials provider - } catch (Exception e) { - throw new AmazonClientException( - "Cannot load credentials from .aws/credentials file. " + - "Make sure that the credentials file exists and that the profile name is defined within it.", - e); - } - - // create an EMR client using the credentials and region specified in order to create the cluster + credentials_profile = new ProfileCredentialsProvider("default"); // specifies any named profile in + // .aws/credentials as the credentials provider + } catch (Exception e) { + throw new AmazonClientException( + "Cannot load credentials from .aws/credentials file. " + + "Make sure that the credentials file exists and that the profile name is defined within it.", + e); + } + + // create an EMR client using the credentials and region specified in order to + // create the cluster AmazonElasticMapReduce emr = AmazonElasticMapReduceClientBuilder.standard() - .withCredentials(credentials_profile) - .withRegion(Regions.US_WEST_1) - .build(); - - // create a step to enable debugging in the AWS Management Console - StepFactory stepFactory = new StepFactory(); + .withCredentials(credentials_profile) + .withRegion(Regions.US_WEST_1) + .build(); + + // create a step to enable debugging in the AWS Management Console + StepFactory stepFactory = new StepFactory(); StepConfig enabledebugging = new StepConfig() - .withName("Enable debugging") - .withActionOnFailure("TERMINATE_JOB_FLOW") - .withHadoopJarStep(stepFactory.newEnableDebuggingStep()); - - // specify applications to be installed and configured when EMR creates the cluster + .withName("Enable debugging") + .withActionOnFailure("TERMINATE_JOB_FLOW") + .withHadoopJarStep(stepFactory.newEnableDebuggingStep()); + + // specify applications to be installed and configured when EMR creates the + // cluster Application hive = new Application().withName("Hive"); Application spark = new Application().withName("Spark"); Application ganglia = new Application().withName("Ganglia"); Application zeppelin = new Application().withName("Zeppelin"); - + // create the cluster RunJobFlowRequest request = new RunJobFlowRequest() - .withName("MyClusterCreatedFromJava") - .withReleaseLabel("emr-5.20.0") // specifies the EMR release version label, we recommend the latest release - .withSteps(enabledebugging) - .withApplications(hive,spark,ganglia,zeppelin) - .withLogUri("s3://path/to/my/emr/logs") // a URI in S3 for log files is required when debugging is enabled - .withServiceRole("EMR_DefaultRole") // replace the default with a custom IAM service role if one is used - .withJobFlowRole("EMR_EC2_DefaultRole") // replace the default with a custom EMR role for the EC2 instance profile if one is used - .withInstances(new JobFlowInstancesConfig() - .withEc2SubnetId("subnet-12ab34c56") - .withEc2KeyName("myEc2Key") - .withInstanceCount(3) - .withKeepJobFlowAliveWhenNoSteps(true) - .withMasterInstanceType("m4.large") - .withSlaveInstanceType("m4.large")); + .withName("MyClusterCreatedFromJava") + .withReleaseLabel("emr-5.20.0") // specifies the EMR release version label, we recommend the latest release + .withSteps(enabledebugging) + .withApplications(hive, spark, ganglia, zeppelin) + .withLogUri("s3://path/to/my/emr/logs") // a URI in S3 for log files is required when debugging is enabled + .withServiceRole("EMR_DefaultRole") // replace the default with a custom IAM service role if one is used + .withJobFlowRole("EMR_EC2_DefaultRole") // replace the default with a custom EMR role for the EC2 instance + // profile if one is used + .withInstances(new JobFlowInstancesConfig() + .withEc2SubnetId("subnet-12ab34c56") + .withEc2KeyName("myEc2Key") + .withInstanceCount(3) + .withKeepJobFlowAliveWhenNoSteps(true) + .withMasterInstanceType("m4.large") + .withSlaveInstanceType("m4.large")); - RunJobFlowResult result = emr.runJobFlow(request); - System.out.println("The cluster ID is " + result.toString()); + RunJobFlowResult result = emr.runJobFlow(request); + System.out.println("The cluster ID is " + result.toString()); } diff --git a/java/example_code/emr/custom-emrfs-materials.java b/java/example_code/emr/custom-emrfs-materials.java index bb62549673e..b09e9a5896d 100755 --- a/java/example_code/emr/custom-emrfs-materials.java +++ b/java/example_code/emr/custom-emrfs-materials.java @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[custom-emrfs-materials.java demonstrates how to create a cluster, specifying values in the emrfs-site configuration classification for a custom encryption materials provider.] -// snippet-service:[elasticmapreduce] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon EMR] -// snippet-keyword:[Code Sample] -// snippet-keyword:[withClassification] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] // snippet-start:[emr.java.create-cluster.emrfsconfiguration] import java.util.HashMap; import java.util.Map; @@ -35,52 +14,52 @@ public class Main { public static void main(String[] args) { - AWSCredentials credentials_profile = null; + AWSCredentials credentials_profile = null; try { credentials_profile = new ProfileCredentialsProvider("default").getCredentials(); - } catch (Exception e) { - throw new AmazonClientException( - "Cannot load credentials from .aws/credentials file. " + - "Make sure that the credentials file exists and the profile name is specified within it.", - e); - } - + } catch (Exception e) { + throw new AmazonClientException( + "Cannot load credentials from .aws/credentials file. " + + "Make sure that the credentials file exists and the profile name is specified within it.", + e); + } + AmazonElasticMapReduce emr = AmazonElasticMapReduceClientBuilder.standard() - .withCredentials(new AWSStaticCredentialsProvider(credentials_profile)) - .withRegion(Regions.US_WEST_1) - .build(); - - Map emrfsProperties = new HashMap(); - emrfsProperties.put("fs.s3.cse.encryptionMaterialsProvider.uri","s3://mybucket/MyCustomEncryptionMaterialsProvider.jar"); - emrfsProperties.put("fs.s3.cse.enabled","true"); - emrfsProperties.put("fs.s3.consistent","true"); - emrfsProperties.put("fs.s3.cse.encryptionMaterialsProvider","full.class.name.of.EncryptionMaterialsProvider"); + .withCredentials(new AWSStaticCredentialsProvider(credentials_profile)) + .withRegion(Regions.US_WEST_1) + .build(); + + Map emrfsProperties = new HashMap(); + emrfsProperties.put("fs.s3.cse.encryptionMaterialsProvider.uri", + "s3://mybucket/MyCustomEncryptionMaterialsProvider.jar"); + emrfsProperties.put("fs.s3.cse.enabled", "true"); + emrfsProperties.put("fs.s3.consistent", "true"); + emrfsProperties.put("fs.s3.cse.encryptionMaterialsProvider", "full.class.name.of.EncryptionMaterialsProvider"); Configuration myEmrfsConfig = new Configuration() - .withClassification("emrfs-site") - .withProperties(emrfsProperties); - + .withClassification("emrfs-site") + .withProperties(emrfsProperties); + Application hive = new Application().withName("Hive"); Application spark = new Application().withName("Spark"); Application ganglia = new Application().withName("Ganglia"); Application zeppelin = new Application().withName("Zeppelin"); RunJobFlowRequest request = new RunJobFlowRequest() - .withName("ClusterWithCustomEMRFSEncryptionMaterialsProvider") - .withReleaseLabel("emr-5.20.0") - .withApplications(hive,spark,ganglia,zeppelin) - .withConfigurations(myEmrfsConfig) - .withServiceRole("EMR_DefaultRole") - .withJobFlowRole("EMR_EC2_DefaultRole") - .withLogUri("s3://path/to/emr/logs") - .withInstances(new JobFlowInstancesConfig() - .withEc2KeyName("myEc2Key") - .withInstanceCount(3) - .withKeepJobFlowAliveWhenNoSteps(true) - .withMasterInstanceType("m4.large") - .withSlaveInstanceType("m4.large") - ); - + .withName("ClusterWithCustomEMRFSEncryptionMaterialsProvider") + .withReleaseLabel("emr-5.20.0") + .withApplications(hive, spark, ganglia, zeppelin) + .withConfigurations(myEmrfsConfig) + .withServiceRole("EMR_DefaultRole") + .withJobFlowRole("EMR_EC2_DefaultRole") + .withLogUri("s3://path/to/emr/logs") + .withInstances(new JobFlowInstancesConfig() + .withEc2KeyName("myEc2Key") + .withInstanceCount(3) + .withKeepJobFlowAliveWhenNoSteps(true) + .withMasterInstanceType("m4.large") + .withSlaveInstanceType("m4.large")); + RunJobFlowResult result = emr.runJobFlow(request); System.out.println("The cluster ID is " + result.toString()); } diff --git a/java/example_code/emr/emr-add-steps.java b/java/example_code/emr/emr-add-steps.java index 41c7f229f4f..3ad4ad0374d 100755 --- a/java/example_code/emr/emr-add-steps.java +++ b/java/example_code/emr/emr-add-steps.java @@ -1,30 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[emr-add-steps.java demonstrates how to add steps to a running EMR cluster. Steps perform work for data processing jobs.] -// snippet-service:[elasticmapreduce] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon EMR] -// snippet-keyword:[Code Sample] -// snippet-keyword:[StepFactory] -// snippet-keyword:[newScriptRunnerStep] -// snippet-keyword:[HadoopJarStepConfig] -// snippet-keyword:[AddJobFlowStepsRequest] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] // snippet-start:[emr.java.add_steps.bashandjar] import com.amazonaws.AmazonClientException; import com.amazonaws.auth.AWSCredentials; @@ -38,40 +14,40 @@ public class Main { public static void main(String[] args) { - AWSCredentials credentials_profile = null; + AWSCredentials credentials_profile = null; try { credentials_profile = new ProfileCredentialsProvider("default").getCredentials(); - } catch (Exception e) { - throw new AmazonClientException( - "Cannot load credentials from .aws/credentials file. " + - "Make sure that the credentials file exists and the profile name is specified within it.", - e); - } - + } catch (Exception e) { + throw new AmazonClientException( + "Cannot load credentials from .aws/credentials file. " + + "Make sure that the credentials file exists and the profile name is specified within it.", + e); + } + AmazonElasticMapReduce emr = AmazonElasticMapReduceClientBuilder.standard() - .withCredentials(new AWSStaticCredentialsProvider(credentials_profile)) - .withRegion(Regions.US_WEST_1) - .build(); - + .withCredentials(new AWSStaticCredentialsProvider(credentials_profile)) + .withRegion(Regions.US_WEST_1) + .build(); + // Run a bash script using a predefined step in the StepFactory helper class - StepFactory stepFactory = new StepFactory(); - StepConfig runBashScript = new StepConfig() - .withName("Run a bash script") - .withHadoopJarStep(stepFactory.newScriptRunnerStep("s3://jeffgoll/emr-scripts/create_users.sh")) - .withActionOnFailure("CONTINUE"); + StepFactory stepFactory = new StepFactory(); + StepConfig runBashScript = new StepConfig() + .withName("Run a bash script") + .withHadoopJarStep(stepFactory.newScriptRunnerStep("s3://jeffgoll/emr-scripts/create_users.sh")) + .withActionOnFailure("CONTINUE"); + + // Run a custom jar file as a step + HadoopJarStepConfig hadoopConfig1 = new HadoopJarStepConfig() + .withJar("s3://path/to/my/jarfolder") // replace with the location of the jar to run as a step + .withMainClass("com.my.Main1") // optional main class, this can be omitted if jar above has a manifest + .withArgs("--verbose"); // optional list of arguments to pass to the jar + StepConfig myCustomJarStep = new StepConfig("RunHadoopJar", hadoopConfig1); - // Run a custom jar file as a step - HadoopJarStepConfig hadoopConfig1 = new HadoopJarStepConfig() - .withJar("s3://path/to/my/jarfolder") // replace with the location of the jar to run as a step - .withMainClass("com.my.Main1") // optional main class, this can be omitted if jar above has a manifest - .withArgs("--verbose"); // optional list of arguments to pass to the jar - StepConfig myCustomJarStep = new StepConfig("RunHadoopJar", hadoopConfig1); + AddJobFlowStepsResult result = emr.addJobFlowSteps(new AddJobFlowStepsRequest() + .withJobFlowId("j-xxxxxxxxxxxx") // replace with cluster id to run the steps + .withSteps(runBashScript, myCustomJarStep)); - AddJobFlowStepsResult result = emr.addJobFlowSteps(new AddJobFlowStepsRequest() - .withJobFlowId("j-xxxxxxxxxxxx") // replace with cluster id to run the steps - .withSteps(runBashScript,myCustomJarStep)); - - System.out.println(result.getStepIds()); + System.out.println(result.getStepIds()); } } diff --git a/java/example_code/emr/emr-flink-cluster-transient-step.java b/java/example_code/emr/emr-flink-cluster-transient-step.java index 067b4cf023b..604688c880e 100755 --- a/java/example_code/emr/emr-flink-cluster-transient-step.java +++ b/java/example_code/emr/emr-flink-cluster-transient-step.java @@ -1,28 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[emr-flink-cluster-transient-step.java demonstrates how to create a Flink cluster, and then run a step that shuts down the cluster when it completes.] -// snippet-service:[elasticmapreduce] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon EMR] -// snippet-keyword:[Code Sample] -// snippet-keyword:[RunJobFlowRequest] -// snippet-keyword:[StepConfig] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[emr.java.createflinkcluster.runstep] import java.util.ArrayList; import java.util.List; @@ -37,52 +15,54 @@ public class Main_test { public static void main(String[] args) { - AWSCredentials credentials_profile = null; + AWSCredentials credentials_profile = null; try { credentials_profile = new ProfileCredentialsProvider("default").getCredentials(); - } catch (Exception e) { - throw new AmazonClientException( - "Cannot load credentials from .aws/credentials file. " + - "Make sure that the credentials file exists and the profile name is specified within it.", - e); - } - + } catch (Exception e) { + throw new AmazonClientException( + "Cannot load credentials from .aws/credentials file. " + + "Make sure that the credentials file exists and the profile name is specified within it.", + e); + } + AmazonElasticMapReduce emr = AmazonElasticMapReduceClientBuilder.standard() - .withCredentials(new AWSStaticCredentialsProvider(credentials_profile)) - .withRegion(Regions.US_WEST_1) - .build(); - + .withCredentials(new AWSStaticCredentialsProvider(credentials_profile)) + .withRegion(Regions.US_WEST_1) + .build(); + List stepConfigs = new ArrayList(); - HadoopJarStepConfig flinkWordCountConf = new HadoopJarStepConfig() - .withJar("command-runner.jar") - .withArgs("bash","-c", "flink", "run", "-m", "yarn-cluster", "-yn", "2", "/usr/lib/flink/examples/streaming/WordCount.jar", "--input", "s3://path/to/input-file.txt", "--output", "s3://path/to/output/"); - - StepConfig flinkRunWordCountStep = new StepConfig() - .withName("Flink add a wordcount step and terminate") - .withActionOnFailure("CONTINUE") - .withHadoopJarStep(flinkWordCountConf); - - stepConfigs.add(flinkRunWordCountStep); - - Application flink = new Application().withName("Flink"); - - RunJobFlowRequest request = new RunJobFlowRequest() - .withName("flink-transient") - .withReleaseLabel("emr-5.20.0") - .withApplications(flink) - .withServiceRole("EMR_DefaultRole") - .withJobFlowRole("EMR_EC2_DefaultRole") - .withLogUri("s3://path/to/my/logfiles") - .withInstances(new JobFlowInstancesConfig() - .withEc2KeyName("myEc2Key") - .withEc2SubnetId("subnet-12ab3c45") - .withInstanceCount(3) - .withKeepJobFlowAliveWhenNoSteps(false) - .withMasterInstanceType("m4.large") - .withSlaveInstanceType("m4.large")) - .withSteps(stepConfigs); - - RunJobFlowResult result = emr.runJobFlow(request); + HadoopJarStepConfig flinkWordCountConf = new HadoopJarStepConfig() + .withJar("command-runner.jar") + .withArgs("bash", "-c", "flink", "run", "-m", "yarn-cluster", "-yn", "2", + "/usr/lib/flink/examples/streaming/WordCount.jar", "--input", "s3://path/to/input-file.txt", "--output", + "s3://path/to/output/"); + + StepConfig flinkRunWordCountStep = new StepConfig() + .withName("Flink add a wordcount step and terminate") + .withActionOnFailure("CONTINUE") + .withHadoopJarStep(flinkWordCountConf); + + stepConfigs.add(flinkRunWordCountStep); + + Application flink = new Application().withName("Flink"); + + RunJobFlowRequest request = new RunJobFlowRequest() + .withName("flink-transient") + .withReleaseLabel("emr-5.20.0") + .withApplications(flink) + .withServiceRole("EMR_DefaultRole") + .withJobFlowRole("EMR_EC2_DefaultRole") + .withLogUri("s3://path/to/my/logfiles") + .withInstances(new JobFlowInstancesConfig() + .withEc2KeyName("myEc2Key") + .withEc2SubnetId("subnet-12ab3c45") + .withInstanceCount(3) + .withKeepJobFlowAliveWhenNoSteps(false) + .withMasterInstanceType("m4.large") + .withSlaveInstanceType("m4.large")) + .withSteps(stepConfigs); + + RunJobFlowResult result = emr.runJobFlow(request); System.out.println("The cluster ID is " + result.toString()); } diff --git a/java/example_code/emr/emr-flink-step.java b/java/example_code/emr/emr-flink-step.java index e833fb8748c..8db0824863b 100755 --- a/java/example_code/emr/emr-flink-step.java +++ b/java/example_code/emr/emr-flink-step.java @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[emr-flink-step.java demonstrates how to submit work as a step to a long-running Flink cluster using the YARN application ID.] -// snippet-service:[elasticmapreduce] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon EMR] -// snippet-keyword:[Code Sample] -// snippet-keyword:[RunJobFlowRequest] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] // snippet-start:[emr.java.runstep.flink] List stepConfigs = new ArrayList(); diff --git a/java/example_code/emr/enable-debugging.java b/java/example_code/emr/enable-debugging.java index 8de2bfdd167..607a20ab353 100755 --- a/java/example_code/emr/enable-debugging.java +++ b/java/example_code/emr/enable-debugging.java @@ -1,29 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[enable-debugging.java demonstrates how to use the StepFactory helper class to configure a step for debugging that you can specify using .withSteps when you create a cluster using RunJobFlowRequest.] -// snippet-service:[elasticmapreduce] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon EMR] -// snippet-keyword:[Code Sample] -// snippet-keyword:[stepFactory] -// snippet-keyword:[enableDebugging] -// snippet-keyword:[StepConfig] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] // snippet-start:[emr.java.stepfactory.enabledebugging] StepFactory stepFactory = new StepFactory(); StepConfig enabledebugging = new StepConfig() diff --git a/java/example_code/emr/hbase-snapshot-export.java b/java/example_code/emr/hbase-snapshot-export.java index fd603adddd2..927987ac6b4 100755 --- a/java/example_code/emr/hbase-snapshot-export.java +++ b/java/example_code/emr/hbase-snapshot-export.java @@ -1,28 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[hbase-snapshot-export.java demonstrates how to configure a step that exports a snapshot and copies it to Amazon S3.] -// snippet-service:[elasticmapreduce] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon EMR] -// snippet-keyword:[Code Sample] -// snippet-keyword:[HadoopJarStepConfig] -// snippet-keyword:[HBase snapshot] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] // snippet-start:[emr.java.hbase.snapshotexport] HadoopJarStepConfig hbaseImportSnapshotConf = new HadoopJarStepConfig() .withJar("command-runner.jar") diff --git a/java/example_code/emr/hbase-snapshot-import.java b/java/example_code/emr/hbase-snapshot-import.java index 0c929aa83c1..77a493bac91 100755 --- a/java/example_code/emr/hbase-snapshot-import.java +++ b/java/example_code/emr/hbase-snapshot-import.java @@ -1,28 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[hbase-snapshot-import.java demonstrates how to configure a step that imports a snapshot from Amazon S3 using the HBase export command.] -// snippet-service:[elasticmapreduce] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon EMR] -// snippet-keyword:[Code Sample] -// snippet-keyword:[HadoopJarStepConfig] -// snippet-keyword:[HBase snapshot] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] // snippet-start:[emr.java.hbase.snapshotimport] HadoopJarStepConfig hbaseImportSnapshotConf = new HadoopJarStepConfig() .withJar("command-runner.jar") diff --git a/java/example_code/emr/hbase-snapshot-restore.java b/java/example_code/emr/hbase-snapshot-restore.java index b839bd6edc1..52de9c89fea 100755 --- a/java/example_code/emr/hbase-snapshot-restore.java +++ b/java/example_code/emr/hbase-snapshot-restore.java @@ -1,28 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[hbase-snapshot-restore.java demonstrates how to configure a step that restores a table from a snapshot.] -// snippet-service:[elasticmapreduce] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon EMR] -// snippet-keyword:[Code Sample] -// snippet-keyword:[HadoopJarStepConfig] -// snippet-keyword:[HBase snapshot] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] // snippet-start:[emr.java.hbase.snapshotrestoretable] HadoopJarStepConfig hbaseRestoreSnapshotConf = new HadoopJarStepConfig() .withJar("command-runner.jar") diff --git a/java/example_code/emr/hbase-snapshot.java b/java/example_code/emr/hbase-snapshot.java index afc2d6679f7..80110317186 100755 --- a/java/example_code/emr/hbase-snapshot.java +++ b/java/example_code/emr/hbase-snapshot.java @@ -1,28 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[hbase-snapshot.java demonstrates how to configure a step to create an HBase snapshot from a specified table.] -// snippet-service:[elasticmapreduce] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon EMR] -// snippet-keyword:[Code Sample] -// snippet-keyword:[HadoopJarStepConfig] -// snippet-keyword:[HBase snapshot] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] // snippet-start:[emr.java.hbase.snapshotstep] HadoopJarStepConfig hbaseSnapshotConf = new HadoopJarStepConfig() .withJar("command-runner.jar") diff --git a/java/example_code/emr/runjobflow-configurationclassification.java b/java/example_code/emr/runjobflow-configurationclassification.java index 7889e5e2264..0084210d548 100755 --- a/java/example_code/emr/runjobflow-configurationclassification.java +++ b/java/example_code/emr/runjobflow-configurationclassification.java @@ -1,28 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[runjobflow-configurationclassification.java demonstrates how to specify configuration classification properties when creating a cluster using RunJobFlowRequest.] -// snippet-service:[elasticmapreduce] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon EMR] -// snippet-keyword:[Code Sample] -// snippet-keyword:[RunJobFlowRequest] -// snippet-keyword:[withConfigurations] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] // snippet-start:[emr.java.create-cluster.specifyconfigurationclassification] Application hive = new Application().withName("Hive"); diff --git a/java/example_code/emr/runjobflow-spotinstances.java b/java/example_code/emr/runjobflow-spotinstances.java index 2ef95ea05a4..38ae1cffd2a 100755 --- a/java/example_code/emr/runjobflow-spotinstances.java +++ b/java/example_code/emr/runjobflow-spotinstances.java @@ -1,28 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[runjobflow-spotinstances.java demonstrates how to specify the Spot instance purchasing option for instance groups using RunJobFlowRequest.] -// snippet-service:[elasticmapreduce] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon EMR] -// snippet-keyword:[Code Sample] -// snippet-keyword:[RunJobFlowRequest] -// snippet-keyword: [InstanceGroupConfig] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] // snippet-start:[emr.java.createcluster.specifyspotinstances] InstanceGroupConfig instanceGroupConfigMaster = new InstanceGroupConfig() .withInstanceCount(1) diff --git a/java/example_code/glacier/run_example.sh b/java/example_code/glacier/run_example.sh index c0dc1387c75..6b695f73e20 100755 --- a/java/example_code/glacier/run_example.sh +++ b/java/example_code/glacier/run_example.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 if [[ -z $* ]] ; then echo 'Supply the name of one of the example classes as an argument.' echo 'If there are arguments to the class, put them in quotes after the class name.' diff --git a/java/example_code/glacier/src/main/java/aws/example/glacier/ListVaults.java b/java/example_code/glacier/src/main/java/aws/example/glacier/ListVaults.java index 5b9dcd63f3e..63e6a43783f 100644 --- a/java/example_code/glacier/src/main/java/aws/example/glacier/ListVaults.java +++ b/java/example_code/glacier/src/main/java/aws/example/glacier/ListVaults.java @@ -1,26 +1,7 @@ -//snippet-sourcedescription:[ListVaults.java demonstrates how to list your Amazon Glacier vaults.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Glacier] -//snippet-service:[glacier] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.glacier; + import com.amazonaws.AmazonServiceException; import com.amazonaws.services.glacier.AmazonGlacier; import com.amazonaws.services.glacier.AmazonGlacierClientBuilder; @@ -35,10 +16,8 @@ * This code expects that you have AWS credentials set up per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ -public class ListVaults -{ - public static void main(String[] args) - { +public class ListVaults { + public static void main(String[] args) { final AmazonGlacier glacier = AmazonGlacierClientBuilder.defaultClient(); ListVaultsRequest request = new ListVaultsRequest(); @@ -48,7 +27,7 @@ public static void main(String[] args) while (!list_complete) { ListVaultsResult result = glacier.listVaults(request); List vault_list = result.getVaultList(); - for (DescribeVaultOutput v: vault_list) { + for (DescribeVaultOutput v : vault_list) { total_vaults += 1; System.out.println("* " + v.getVaultName()); } diff --git a/java/example_code/guardduty/run_example.sh b/java/example_code/guardduty/run_example.sh index 6df720997e8..3f033513038 100755 --- a/java/example_code/guardduty/run_example.sh +++ b/java/example_code/guardduty/run_example.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 if [[ -z $* ]] ; then echo 'Supply the name of one of the example classes as an argument.' echo 'If there are arguments to the class, put them in quotes after the class name.' diff --git a/java/example_code/guardduty/src/main/java/aws/example/guardduty/ListDetectors.java b/java/example_code/guardduty/src/main/java/aws/example/guardduty/ListDetectors.java index 1682acc62a8..f4cb4d1710b 100644 --- a/java/example_code/guardduty/src/main/java/aws/example/guardduty/ListDetectors.java +++ b/java/example_code/guardduty/src/main/java/aws/example/guardduty/ListDetectors.java @@ -1,55 +1,34 @@ -//snippet-sourcedescription:[ListDetectors.java demonstrates how to list GuardDuty Detectors in the current AWS Region.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon GuardDuty] -//snippet-service:[guardduty] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-26] -//snippet-sourceauthor:[Keith Walker] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.guardduty; + import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.guardduty.AmazonGuardDuty; import com.amazonaws.services.guardduty.AmazonGuardDutyClientBuilder; import com.amazonaws.services.guardduty.model.*; + /** * List GuardDuty Detectors in the current AWS Region */ public class ListDetectors { public static void main(String[] args) { - AmazonGuardDuty guardduty = - AmazonGuardDutyClientBuilder.defaultClient(); + AmazonGuardDuty guardduty = AmazonGuardDutyClientBuilder.defaultClient(); try { ListDetectorsRequest request = new ListDetectorsRequest(); ListDetectorsResult response = guardduty.listDetectors(request); - for (String detectorId : response.getDetectorIds()) - { - System.out.println("DetectorId: " + detectorId ); + for (String detectorId : response.getDetectorIds()) { + System.out.println("DetectorId: " + detectorId); } } catch (AmazonServiceException ase) { - System.out.println("Caught Exception: " + ase.getMessage()); - System.out.println("Response Status Code: " + ase.getStatusCode()); - System.out.println("Error Code: " + ase.getErrorCode()); - System.out.println("Request ID: " + ase.getRequestId()); + System.out.println("Caught Exception: " + ase.getMessage()); + System.out.println("Response Status Code: " + ase.getStatusCode()); + System.out.println("Error Code: " + ase.getErrorCode()); + System.out.println("Request ID: " + ase.getRequestId()); } } diff --git a/java/example_code/guardduty/src/main/java/aws/example/guardduty/ListFindingsWithFindingCriteria.java b/java/example_code/guardduty/src/main/java/aws/example/guardduty/ListFindingsWithFindingCriteria.java index bdbd2b3d61b..6c253e9a073 100644 --- a/java/example_code/guardduty/src/main/java/aws/example/guardduty/ListFindingsWithFindingCriteria.java +++ b/java/example_code/guardduty/src/main/java/aws/example/guardduty/ListFindingsWithFindingCriteria.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[ListFindingsWithFindingCriteria.java demonstrates how to list all GuardDuty findings that match the specified finding criteria.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon GuardDuty] -//snippet-service:[guardduty] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-26] -//snippet-sourceauthor:[Keith Walker] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.guardduty; + import java.util.ArrayList; import java.util.List; import com.amazonaws.AmazonClientException; @@ -29,14 +9,14 @@ import com.amazonaws.services.guardduty.AmazonGuardDuty; import com.amazonaws.services.guardduty.AmazonGuardDutyClientBuilder; import com.amazonaws.services.guardduty.model.*; + /** * List all GuardDuty Findings that match the specified FindingCriteria */ public class ListFindingsWithFindingCriteria { public static void main(String[] args) { - AmazonGuardDuty guardduty = - AmazonGuardDutyClientBuilder.defaultClient(); + AmazonGuardDuty guardduty = AmazonGuardDutyClientBuilder.defaultClient(); // Set detectorId to the detectorId returned by GuardDuty's // ListDetectors() for your current AWS Account/Region @@ -53,19 +33,19 @@ public static void main(String[] args) { try { ListFindingsRequest request = new ListFindingsRequest() - .withDetectorId(detectorId) - .withFindingCriteria(criteria); + .withDetectorId(detectorId) + .withFindingCriteria(criteria); ListFindingsResult response = guardduty.listFindings(request); for (String finding : response.getFindingIds()) { - System.out.println("FindingId: " + finding); + System.out.println("FindingId: " + finding); } } catch (AmazonServiceException ase) { - System.out.println("Caught Exception: " + ase.getMessage()); - System.out.println("Response Status Code: " + ase.getStatusCode()); - System.out.println("Error Code: " + ase.getErrorCode()); - System.out.println("Request ID: " + ase.getRequestId()); + System.out.println("Caught Exception: " + ase.getMessage()); + System.out.println("Response Status Code: " + ase.getStatusCode()); + System.out.println("Error Code: " + ase.getErrorCode()); + System.out.println("Request ID: " + ase.getRequestId()); } } diff --git a/java/example_code/iam/run_example.sh b/java/example_code/iam/run_example.sh index bb60d7c4d68..ade413ffc57 100755 --- a/java/example_code/iam/run_example.sh +++ b/java/example_code/iam/run_example.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 if [[ -z $* ]] ; then echo 'Supply the name of one of the example classes as an argument.' echo 'If there are arguments to the class, put them in quotes after the class name.' diff --git a/java/example_code/iam/src/main/java/aws/example/iam/AccessKeyLastUsed.java b/java/example_code/iam/src/main/java/aws/example/iam/AccessKeyLastUsed.java index 2c9ac554de2..9334de17870 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/AccessKeyLastUsed.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/AccessKeyLastUsed.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[AccessKeyLastUsed.java demonstrates how to get the time that an access key was last used.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.iam; + import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.identitymanagement.model.GetAccessKeyLastUsedRequest; @@ -33,9 +13,8 @@ public class AccessKeyLastUsed { public static void main(String[] args) { - final String USAGE = - "To run this example, supply an access key id\n" + - "Ex: AccessKeyLastUsed \n"; + final String USAGE = "To run this example, supply an access key id\n" + + "Ex: AccessKeyLastUsed \n"; if (args.length != 1) { System.out.println(USAGE); @@ -44,11 +23,10 @@ public static void main(String[] args) { String access_id = args[0]; - final AmazonIdentityManagement iam = - AmazonIdentityManagementClientBuilder.defaultClient(); + final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); GetAccessKeyLastUsedRequest request = new GetAccessKeyLastUsedRequest() - .withAccessKeyId(access_id); + .withAccessKeyId(access_id); GetAccessKeyLastUsedResult response = iam.getAccessKeyLastUsed(request); diff --git a/java/example_code/iam/src/main/java/aws/example/iam/AttachRolePolicy.java b/java/example_code/iam/src/main/java/aws/example/iam/AttachRolePolicy.java index d672d9833db..c2bc0f9267c 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/AttachRolePolicy.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/AttachRolePolicy.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[AttachRolePolicy.java demonstrates how to attach a policy to a role.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.iam; + import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.identitymanagement.model.AttachRolePolicyRequest; @@ -34,13 +14,11 @@ public class AttachRolePolicy { - public static final String POLICY_ARN = - "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess"; + public static final String POLICY_ARN = "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess"; public static void main(String[] args) { - final String USAGE = - "To run this example, supply a role name\n" + - "Ex: AttachRolePolicy \n"; + final String USAGE = "To run this example, supply a role name\n" + + "Ex: AttachRolePolicy \n"; if (args.length != 1) { System.out.println(USAGE); @@ -49,20 +27,17 @@ public static void main(String[] args) { String role_name = args[0]; - final AmazonIdentityManagement iam = - AmazonIdentityManagementClientBuilder.defaultClient(); + final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); - ListAttachedRolePoliciesRequest request = - new ListAttachedRolePoliciesRequest() + ListAttachedRolePoliciesRequest request = new ListAttachedRolePoliciesRequest() .withRoleName(role_name); List matching_policies = new ArrayList<>(); boolean done = false; - while(!done) { - ListAttachedRolePoliciesResult response = - iam.listAttachedRolePolicies(request); + while (!done) { + ListAttachedRolePoliciesResult response = iam.listAttachedRolePolicies(request); matching_policies.addAll( response.getAttachedPolicies() @@ -70,7 +45,7 @@ public static void main(String[] args) { .filter(p -> p.getPolicyName().equals(role_name)) .collect(Collectors.toList())); - if(!response.getIsTruncated()) { + if (!response.getIsTruncated()) { done = true; } request.setMarker(response.getMarker()); @@ -82,8 +57,7 @@ public static void main(String[] args) { return; } - AttachRolePolicyRequest attach_request = - new AttachRolePolicyRequest() + AttachRolePolicyRequest attach_request = new AttachRolePolicyRequest() .withRoleName(role_name) .withPolicyArn(POLICY_ARN); diff --git a/java/example_code/iam/src/main/java/aws/example/iam/ConstructUrlFederatedUsers.java b/java/example_code/iam/src/main/java/aws/example/iam/ConstructUrlFederatedUsers.java index cdbc70e9dff..98e7ace6316 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/ConstructUrlFederatedUsers.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/ConstructUrlFederatedUsers.java @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[ConstructUrlFederatedUsers.java demonstrates how to programmatically construct a URL that gives federated users direct access to the AWS Management Console.] -// snippet-service:[iam] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[AWS Identity and Access Management (IAM)] -// snippet-keyword:[Code Sample] -// snippet-keyword:[AssumeRole] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-22] -// snippet-sourceauthor:[stephswo (AWS)] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[iam.java.ConstructUrlFederatedUsers.complete] import java.net.URLEncoder; @@ -38,7 +17,6 @@ import com.amazonaws.services.securitytoken.model.GetFederationTokenRequest; import com.amazonaws.services.securitytoken.model.GetFederationTokenResult; - /** * Constructs a URL for federated users */ @@ -46,87 +24,84 @@ public class ConstructUrl { public static void main(String[] args) { - /* Calls to AWS STS API operations must be signed using the access key ID - and secret access key of an IAM user or using existing temporary - credentials. The credentials should not be embedded in code. For - this example, the code looks for the credentials in a - standard configuration file. - */ - AWSCredentials credentials = - new PropertiesCredentials( - AwsConsoleApp.class.getResourceAsStream("AwsCredentials.properties")); - - AWSSecurityTokenServiceClient stsClient = - new AWSSecurityTokenServiceClient(credentials); - - GetFederationTokenRequest getFederationTokenRequest = - new GetFederationTokenRequest(); + /* + * Calls to AWS STS API operations must be signed using the access key ID + * and secret access key of an IAM user or using existing temporary + * credentials. The credentials should not be embedded in code. For + * this example, the code looks for the credentials in a + * standard configuration file. + */ + AWSCredentials credentials = new PropertiesCredentials( + AwsConsoleApp.class.getResourceAsStream("AwsCredentials.properties")); + + AWSSecurityTokenServiceClient stsClient = new AWSSecurityTokenServiceClient(credentials); + + GetFederationTokenRequest getFederationTokenRequest = new GetFederationTokenRequest(); getFederationTokenRequest.setDurationSeconds(1800); getFederationTokenRequest.setName("UserName"); - - // A sample policy for accessing Amazon Simple Notification Service (Amazon SNS) in the console. - + + // A sample policy for accessing Amazon Simple Notification Service (Amazon SNS) + // in the console. + String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sns:*\"," + - "\"Effect\":\"Allow\",\"Resource\":\"*\"}]}"; - + "\"Effect\":\"Allow\",\"Resource\":\"*\"}]}"; + getFederationTokenRequest.setPolicy(policy); - - GetFederationTokenResult federationTokenResult = - stsClient.getFederationToken(getFederationTokenRequest); - + + GetFederationTokenResult federationTokenResult = stsClient.getFederationToken(getFederationTokenRequest); + Credentials federatedCredentials = federationTokenResult.getCredentials(); - + // The issuer parameter specifies your internal sign-in // page, for example https://mysignin.internal.mycompany.com/. // The console parameter specifies the URL to the destination console of the - // AWS Management Console. This example goes to Amazon SNS. + // AWS Management Console. This example goes to Amazon SNS. // The signin parameter is the URL to send the request to. - + String issuerURL = "https://mysignin.internal.mycompany.com/"; String consoleURL = "https://console.aws.amazon.com/sns"; String signInURL = "https://signin.aws.amazon.com/federation"; - + // Create the sign-in token using temporary credentials, - // including the access key ID, secret access key, and security token. + // including the access key ID, secret access key, and security token. String sessionJson = String.format( - "{\"%1$s\":\"%2$s\",\"%3$s\":\"%4$s\",\"%5$s\":\"%6$s\"}", - "sessionId", federatedCredentials.getAccessKeyId(), - "sessionKey", federatedCredentials.getSecretAccessKey(), - "sessionToken", federatedCredentials.getSessionToken()); - + "{\"%1$s\":\"%2$s\",\"%3$s\":\"%4$s\",\"%5$s\":\"%6$s\"}", + "sessionId", federatedCredentials.getAccessKeyId(), + "sessionKey", federatedCredentials.getSecretAccessKey(), + "sessionToken", federatedCredentials.getSessionToken()); + // Construct the sign-in request with the request sign-in token action, a - // 12-hour console session duration, and the JSON document with temporary + // 12-hour console session duration, and the JSON document with temporary // credentials as parameters. - - String getSigninTokenURL = signInURL + - "?Action=getSigninToken" + - "&DurationSeconds=43200" + - "&SessionType=json&Session=" + - URLEncoder.encode(sessionJson,"UTF-8"); - + + String getSigninTokenURL = signInURL + + "?Action=getSigninToken" + + "&DurationSeconds=43200" + + "&SessionType=json&Session=" + + URLEncoder.encode(sessionJson, "UTF-8"); + URL url = new URL(getSigninTokenURL); - + // Send the request to the AWS federation endpoint to get the sign-in token - URLConnection conn = url.openConnection (); - - BufferedReader bufferReader = new BufferedReader(new - InputStreamReader(conn.getInputStream())); + URLConnection conn = url.openConnection(); + + BufferedReader bufferReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String returnContent = bufferReader.readLine(); - + String signinToken = new JSONObject(returnContent).getString("SigninToken"); - - String signinTokenParameter = "&SigninToken=" + URLEncoder.encode(signinToken,"UTF-8"); - + + String signinTokenParameter = "&SigninToken=" + URLEncoder.encode(signinToken, "UTF-8"); + // The issuer parameter is optional, but recommended. Use it to direct users // to your sign-in page when their session expires. - + String issuerParameter = "&Issuer=" + URLEncoder.encode(issuerURL, "UTF-8"); - + // Finally, present the completed URL for the AWS console session to the user - - String destinationParameter = "&Destination=" + URLEncoder.encode(consoleURL,"UTF-8"); + + String destinationParameter = "&Destination=" + URLEncoder.encode(consoleURL, "UTF-8"); String loginURL = signInURL + "?Action=login" + - signinTokenParameter + issuerParameter + destinationParameter; + signinTokenParameter + issuerParameter + destinationParameter; } } // snippet-end:[iam.java.ConstructUrlFederatedUsers.complete] diff --git a/java/example_code/iam/src/main/java/aws/example/iam/CreateAccessKey.java b/java/example_code/iam/src/main/java/aws/example/iam/CreateAccessKey.java index 0535173e507..84e95135861 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/CreateAccessKey.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/CreateAccessKey.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[CreateAccessKey.java demonstrates how to create a new access key for an IAM user.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.iam; + import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.identitymanagement.model.CreateAccessKeyRequest; @@ -34,9 +14,8 @@ public class CreateAccessKey { public static void main(String[] args) { - final String USAGE = - "To run this example, supply an IAM user\n" + - "Ex: CreateAccessKey \n"; + final String USAGE = "To run this example, supply an IAM user\n" + + "Ex: CreateAccessKey \n"; if (args.length != 1) { System.out.println(USAGE); @@ -45,11 +24,10 @@ public static void main(String[] args) { String user = args[0]; - final AmazonIdentityManagement iam = - AmazonIdentityManagementClientBuilder.defaultClient(); + final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); CreateAccessKeyRequest request = new CreateAccessKeyRequest() - .withUserName(user); + .withUserName(user); CreateAccessKeyResult response = iam.createAccessKey(request); diff --git a/java/example_code/iam/src/main/java/aws/example/iam/CreateAccountAlias.java b/java/example_code/iam/src/main/java/aws/example/iam/CreateAccountAlias.java index 1547ad62f8f..baa779e4980 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/CreateAccountAlias.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/CreateAccountAlias.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[CreateAccountAlias.java demonstrates how to create an alias for an AWS account.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.iam; + import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.identitymanagement.model.CreateAccountAliasRequest; @@ -33,9 +13,8 @@ public class CreateAccountAlias { public static void main(String[] args) { - final String USAGE = - "To run this example, supply an alias\n" + - "Ex: CreateAccountAlias \n"; + final String USAGE = "To run this example, supply an alias\n" + + "Ex: CreateAccountAlias \n"; if (args.length != 1) { System.out.println(USAGE); @@ -44,11 +23,10 @@ public static void main(String[] args) { String alias = args[0]; - final AmazonIdentityManagement iam = - AmazonIdentityManagementClientBuilder.defaultClient(); + final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); CreateAccountAliasRequest request = new CreateAccountAliasRequest() - .withAccountAlias(alias); + .withAccountAlias(alias); CreateAccountAliasResult response = iam.createAccountAlias(request); diff --git a/java/example_code/iam/src/main/java/aws/example/iam/CreatePolicy.java b/java/example_code/iam/src/main/java/aws/example/iam/CreatePolicy.java index ffc164d6c90..be8454d9c21 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/CreatePolicy.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/CreatePolicy.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[CreatePolicy.java demonstrates how to create a fixed policy with a provided policy name.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.iam; + import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.identitymanagement.model.CreatePolicyRequest; @@ -32,52 +12,49 @@ */ public class CreatePolicy { - public static final String POLICY_DOCUMENT = - "{" + - " \"Version\": \"2012-10-17\"," + - " \"Statement\": [" + - " {" + - " \"Effect\": \"Allow\"," + - " \"Action\": \"logs:CreateLogGroup\"," + - " \"Resource\": \"%s\"" + - " }," + - " {" + - " \"Effect\": \"Allow\"," + - " \"Action\": [" + - " \"dynamodb:DeleteItem\"," + - " \"dynamodb:GetItem\"," + - " \"dynamodb:PutItem\"," + - " \"dynamodb:Scan\"," + - " \"dynamodb:UpdateItem\"" + - " ]," + - " \"Resource\": \"RESOURCE_ARN\"" + - " }" + - " ]" + - "}"; - - public static void main(String[] args) { - - final String USAGE = - "To run this example, supply a policy name\n" + - "Ex: CreatePolicy \n"; - - if (args.length != 1) { - System.out.println(USAGE); - System.exit(1); + public static final String POLICY_DOCUMENT = "{" + + " \"Version\": \"2012-10-17\"," + + " \"Statement\": [" + + " {" + + " \"Effect\": \"Allow\"," + + " \"Action\": \"logs:CreateLogGroup\"," + + " \"Resource\": \"%s\"" + + " }," + + " {" + + " \"Effect\": \"Allow\"," + + " \"Action\": [" + + " \"dynamodb:DeleteItem\"," + + " \"dynamodb:GetItem\"," + + " \"dynamodb:PutItem\"," + + " \"dynamodb:Scan\"," + + " \"dynamodb:UpdateItem\"" + + " ]," + + " \"Resource\": \"RESOURCE_ARN\"" + + " }" + + " ]" + + "}"; + + public static void main(String[] args) { + + final String USAGE = "To run this example, supply a policy name\n" + + "Ex: CreatePolicy \n"; + + if (args.length != 1) { + System.out.println(USAGE); + System.exit(1); + } + + String policy_name = args[0]; + + final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); + + CreatePolicyRequest request = new CreatePolicyRequest() + .withPolicyName(policy_name) + .withPolicyDocument(POLICY_DOCUMENT); + + CreatePolicyResult response = iam.createPolicy(request); + + System.out.println("Successfully created policy: " + + response.getPolicy().getPolicyName()); } - - String policy_name = args[0]; - - final AmazonIdentityManagement iam = - AmazonIdentityManagementClientBuilder.defaultClient(); - - CreatePolicyRequest request = new CreatePolicyRequest() - .withPolicyName(policy_name) - .withPolicyDocument(POLICY_DOCUMENT); - - CreatePolicyResult response = iam.createPolicy(request); - - System.out.println("Successfully created policy: " + - response.getPolicy().getPolicyName()); - } } diff --git a/java/example_code/iam/src/main/java/aws/example/iam/CreateUser.java b/java/example_code/iam/src/main/java/aws/example/iam/CreateUser.java index 5b59f9d505b..13d8d6ff2b2 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/CreateUser.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/CreateUser.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[CreateUser.java demonstrates how to create an IAM user.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.iam; + import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.identitymanagement.model.CreateUserRequest; @@ -34,9 +14,8 @@ public class CreateUser { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a username\n" + - "Ex: CreateUser \n"; + final String USAGE = "To run this example, supply a username\n" + + "Ex: CreateUser \n"; if (args.length != 1) { System.out.println(USAGE); @@ -45,11 +24,10 @@ public static void main(String[] args) { String username = args[0]; - final AmazonIdentityManagement iam = - AmazonIdentityManagementClientBuilder.defaultClient(); + final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); CreateUserRequest request = new CreateUserRequest() - .withUserName(username); + .withUserName(username); CreateUserResult response = iam.createUser(request); diff --git a/java/example_code/iam/src/main/java/aws/example/iam/DeleteAccessKey.java b/java/example_code/iam/src/main/java/aws/example/iam/DeleteAccessKey.java index 24b92fbce3b..883b4a3d8dd 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/DeleteAccessKey.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/DeleteAccessKey.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[DeleteAccessKey.java demonstrates how to delete an access key from an IAM user.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.iam; + import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.identitymanagement.model.DeleteAccessKeyRequest; @@ -33,9 +13,8 @@ public class DeleteAccessKey { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a username and access key id\n" + - "Ex: DeleteAccessKey \n"; + final String USAGE = "To run this example, supply a username and access key id\n" + + "Ex: DeleteAccessKey \n"; if (args.length != 2) { System.out.println(USAGE); @@ -45,12 +24,11 @@ public static void main(String[] args) { String username = args[0]; String access_key = args[1]; - final AmazonIdentityManagement iam = - AmazonIdentityManagementClientBuilder.defaultClient(); + final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); DeleteAccessKeyRequest request = new DeleteAccessKeyRequest() - .withAccessKeyId(access_key) - .withUserName(username); + .withAccessKeyId(access_key) + .withUserName(username); DeleteAccessKeyResult response = iam.deleteAccessKey(request); diff --git a/java/example_code/iam/src/main/java/aws/example/iam/DeleteAccountAlias.java b/java/example_code/iam/src/main/java/aws/example/iam/DeleteAccountAlias.java index 43bed59d41c..4855ed4d716 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/DeleteAccountAlias.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/DeleteAccountAlias.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[DeleteAccountAlias.java demonstrates how to delete an alias from an AWS account.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.iam; + import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.identitymanagement.model.DeleteAccountAliasRequest; @@ -33,9 +13,8 @@ public class DeleteAccountAlias { public static void main(String[] args) { - final String USAGE = - "To run this example, supply an account alias\n" + - "Ex: DeleteAccountAlias \n"; + final String USAGE = "To run this example, supply an account alias\n" + + "Ex: DeleteAccountAlias \n"; if (args.length != 1) { System.out.println(USAGE); @@ -44,11 +23,10 @@ public static void main(String[] args) { String alias = args[0]; - final AmazonIdentityManagement iam = - AmazonIdentityManagementClientBuilder.defaultClient(); + final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); DeleteAccountAliasRequest request = new DeleteAccountAliasRequest() - .withAccountAlias(alias); + .withAccountAlias(alias); DeleteAccountAliasResult response = iam.deleteAccountAlias(request); diff --git a/java/example_code/iam/src/main/java/aws/example/iam/DeleteServerCertificate.java b/java/example_code/iam/src/main/java/aws/example/iam/DeleteServerCertificate.java index 67ec881d903..25abfc6d9d8 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/DeleteServerCertificate.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/DeleteServerCertificate.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[DeleteServerCertificate.java demonstrates how to delete an IAM server certificate.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.iam; + import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.identitymanagement.model.DeleteServerCertificateRequest; @@ -33,9 +13,8 @@ public class DeleteServerCertificate { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a certificate name\n" + - "Ex: DeleteServerCertificate \n"; + final String USAGE = "To run this example, supply a certificate name\n" + + "Ex: DeleteServerCertificate \n"; if (args.length != 1) { System.out.println(USAGE); @@ -44,15 +23,12 @@ public static void main(String[] args) { String cert_name = args[0]; - final AmazonIdentityManagement iam = - AmazonIdentityManagementClientBuilder.defaultClient(); + final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); - DeleteServerCertificateRequest request = - new DeleteServerCertificateRequest() + DeleteServerCertificateRequest request = new DeleteServerCertificateRequest() .withServerCertificateName(cert_name); - DeleteServerCertificateResult response = - iam.deleteServerCertificate(request); + DeleteServerCertificateResult response = iam.deleteServerCertificate(request); System.out.println("Successfully deleted server certificate " + cert_name); diff --git a/java/example_code/iam/src/main/java/aws/example/iam/DeleteUser.java b/java/example_code/iam/src/main/java/aws/example/iam/DeleteUser.java index c0ed0af1f36..7a3a3368642 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/DeleteUser.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/DeleteUser.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[DeleteUser.java demonstrates how to delete an IAM user. This is only possible for users with no associated resources.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.iam; + import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.identitymanagement.model.DeleteConflictException; @@ -34,9 +14,8 @@ public class DeleteUser { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a username\n" + - "Ex: DeleteUser \n"; + final String USAGE = "To run this example, supply a username\n" + + "Ex: DeleteUser \n"; if (args.length != 1) { System.out.println(USAGE); @@ -45,11 +24,10 @@ public static void main(String[] args) { String username = args[0]; - final AmazonIdentityManagement iam = - AmazonIdentityManagementClientBuilder.defaultClient(); + final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); DeleteUserRequest request = new DeleteUserRequest() - .withUserName(username); + .withUserName(username); try { iam.deleteUser(request); diff --git a/java/example_code/iam/src/main/java/aws/example/iam/DetachRolePolicy.java b/java/example_code/iam/src/main/java/aws/example/iam/DetachRolePolicy.java index f61e0bd10b7..f524877eb06 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/DetachRolePolicy.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/DetachRolePolicy.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[DetachRolePolicy.java demonstrates how to detache a policy from a role.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.iam; + import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.identitymanagement.model.DetachRolePolicyRequest; @@ -33,9 +13,8 @@ public class DetachRolePolicy { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a role name and policy arn\n" + - "Ex: DetachRolePolicy >\n"; + final String USAGE = "To run this example, supply a role name and policy arn\n" + + "Ex: DetachRolePolicy >\n"; if (args.length != 1) { System.out.println(USAGE); @@ -45,12 +24,11 @@ public static void main(String[] args) { String role_name = args[0]; String policy_arn = args[1]; - final AmazonIdentityManagement iam = - AmazonIdentityManagementClientBuilder.defaultClient(); + final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); DetachRolePolicyRequest request = new DetachRolePolicyRequest() - .withRoleName(role_name) - .withPolicyArn(policy_arn); + .withRoleName(role_name) + .withPolicyArn(policy_arn); DetachRolePolicyResult response = iam.detachRolePolicy(request); diff --git a/java/example_code/iam/src/main/java/aws/example/iam/GetPolicy.java b/java/example_code/iam/src/main/java/aws/example/iam/GetPolicy.java index e0ba993666d..a1942375588 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/GetPolicy.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/GetPolicy.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[GetPolicy.java demonstrates how to get the details of an IAM policy.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.iam; + import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.identitymanagement.model.GetPolicyRequest; @@ -34,9 +14,8 @@ public class GetPolicy { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a policy arn\n" + - "Ex: GetPolicy \n"; + final String USAGE = "To run this example, supply a policy arn\n" + + "Ex: GetPolicy \n"; if (args.length != 1) { System.out.println(USAGE); @@ -45,11 +24,10 @@ public static void main(String[] args) { String policy_arn = args[0]; - final AmazonIdentityManagement iam = - AmazonIdentityManagementClientBuilder.defaultClient(); + final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); GetPolicyRequest request = new GetPolicyRequest() - .withPolicyArn(policy_arn); + .withPolicyArn(policy_arn); GetPolicyResult response = iam.getPolicy(request); diff --git a/java/example_code/iam/src/main/java/aws/example/iam/GetServerCertificate.java b/java/example_code/iam/src/main/java/aws/example/iam/GetServerCertificate.java index 67d62767542..a2ad09042e5 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/GetServerCertificate.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/GetServerCertificate.java @@ -1,58 +1,50 @@ -//snippet-sourcedescription:[GetServerCertificate.java demonstrates how to get a server certificate.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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 aws.example.iam; -import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; -import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; -import com.amazonaws.services.identitymanagement.model.GetServerCertificateRequest; -import com.amazonaws.services.identitymanagement.model.GetServerCertificateResult; - -/** - * Gets a server certificate - */ -public class GetServerCertificate { - - public static void main(String[] args) { - - final String USAGE = - "To run this example, supply a certificate name\n" + - "Ex: GetServerCertificate \n"; - - if (args.length != 1) { - System.out.println(USAGE); - System.exit(1); - } - - String cert_name = args[0]; - - final AmazonIdentityManagement iam = - AmazonIdentityManagementClientBuilder.defaultClient(); - - GetServerCertificateRequest request = new GetServerCertificateRequest() - .withServerCertificateName(cert_name); - - GetServerCertificateResult response = iam.getServerCertificate(request); - - System.out.format("Successfully retrieved certificate with body %s", - response.getServerCertificate().getCertificateBody()); - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* + * Copyright 2010-2019 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 aws.example.iam; + +import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; +import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; +import com.amazonaws.services.identitymanagement.model.GetServerCertificateRequest; +import com.amazonaws.services.identitymanagement.model.GetServerCertificateResult; + +/** + * Gets a server certificate + */ +public class GetServerCertificate { + + public static void main(String[] args) { + + final String USAGE = "To run this example, supply a certificate name\n" + + "Ex: GetServerCertificate \n"; + + if (args.length != 1) { + System.out.println(USAGE); + System.exit(1); + } + + String cert_name = args[0]; + + final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); + + GetServerCertificateRequest request = new GetServerCertificateRequest() + .withServerCertificateName(cert_name); + + GetServerCertificateResult response = iam.getServerCertificate(request); + + System.out.format("Successfully retrieved certificate with body %s", + response.getServerCertificate().getCertificateBody()); + } +} diff --git a/java/example_code/iam/src/main/java/aws/example/iam/ListAccessKeys.java b/java/example_code/iam/src/main/java/aws/example/iam/ListAccessKeys.java index f06f12ebf87..316f16995a2 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/ListAccessKeys.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/ListAccessKeys.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[ListAccessKeys.java demonstrates how to list all access keys associated with an IAM user.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.iam; + import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.identitymanagement.model.AccessKeyMetadata; @@ -34,9 +14,8 @@ public class ListAccessKeys { public static void main(String[] args) { - final String USAGE = - "To run this example, supply an IAM username\n" + - "Ex: ListAccessKeys \n"; + final String USAGE = "To run this example, supply an IAM username\n" + + "Ex: ListAccessKeys \n"; if (args.length != 1) { System.out.println(USAGE); @@ -45,8 +24,7 @@ public static void main(String[] args) { String username = args[0]; - final AmazonIdentityManagement iam = - AmazonIdentityManagementClientBuilder.defaultClient(); + final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); boolean done = false; ListAccessKeysRequest request = new ListAccessKeysRequest() @@ -56,8 +34,7 @@ public static void main(String[] args) { ListAccessKeysResult response = iam.listAccessKeys(request); - for (AccessKeyMetadata metadata : - response.getAccessKeyMetadata()) { + for (AccessKeyMetadata metadata : response.getAccessKeyMetadata()) { System.out.format("Retrieved access key %s", metadata.getAccessKeyId()); } diff --git a/java/example_code/iam/src/main/java/aws/example/iam/ListAccountAliases.java b/java/example_code/iam/src/main/java/aws/example/iam/ListAccountAliases.java index 8460f139cdb..15b98fde2a3 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/ListAccountAliases.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/ListAccountAliases.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[ListAccountAliases.java demonstrates how to list all aliases associated with an AWS account.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.iam; + import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.identitymanagement.model.ListAccountAliasesResult; @@ -32,8 +12,7 @@ public class ListAccountAliases { public static void main(String[] args) { - final AmazonIdentityManagement iam = - AmazonIdentityManagementClientBuilder.defaultClient(); + final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); ListAccountAliasesResult response = iam.listAccountAliases(); diff --git a/java/example_code/iam/src/main/java/aws/example/iam/ListServerCertificates.java b/java/example_code/iam/src/main/java/aws/example/iam/ListServerCertificates.java index bcce722ee39..13695b16690 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/ListServerCertificates.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/ListServerCertificates.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[ListServerCertificates.java demonstrates how to list all server certificates associated with an AWS account.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.iam; + import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.identitymanagement.model.ListServerCertificatesRequest; @@ -34,27 +14,23 @@ public class ListServerCertificates { public static void main(String[] args) { - final AmazonIdentityManagement iam = - AmazonIdentityManagementClientBuilder.defaultClient(); + final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); boolean done = false; - ListServerCertificatesRequest request = - new ListServerCertificatesRequest(); + ListServerCertificatesRequest request = new ListServerCertificatesRequest(); - while(!done) { + while (!done) { - ListServerCertificatesResult response = - iam.listServerCertificates(request); + ListServerCertificatesResult response = iam.listServerCertificates(request); - for(ServerCertificateMetadata metadata : - response.getServerCertificateMetadataList()) { + for (ServerCertificateMetadata metadata : response.getServerCertificateMetadataList()) { System.out.printf("Retrieved server certificate %s", metadata.getServerCertificateName()); } request.setMarker(response.getMarker()); - if(!response.getIsTruncated()) { + if (!response.getIsTruncated()) { done = true; } } diff --git a/java/example_code/iam/src/main/java/aws/example/iam/ListUsers.java b/java/example_code/iam/src/main/java/aws/example/iam/ListUsers.java index 0455452d8c4..fecb75756be 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/ListUsers.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/ListUsers.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[ListUsers.java demonstrates how to list all IAM users on an AWS account.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.iam; + import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.identitymanagement.model.ListUsersRequest; @@ -34,22 +14,21 @@ public class ListUsers { public static void main(String[] args) { - final AmazonIdentityManagement iam = - AmazonIdentityManagementClientBuilder.defaultClient(); + final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); boolean done = false; ListUsersRequest request = new ListUsersRequest(); - while(!done) { + while (!done) { ListUsersResult response = iam.listUsers(request); - for(User user : response.getUsers()) { + for (User user : response.getUsers()) { System.out.format("Retrieved user %s", user.getUserName()); } request.setMarker(response.getMarker()); - if(!response.getIsTruncated()) { + if (!response.getIsTruncated()) { done = true; } } diff --git a/java/example_code/iam/src/main/java/aws/example/iam/UpdateAccessKey.java b/java/example_code/iam/src/main/java/aws/example/iam/UpdateAccessKey.java index ef350fea14f..6a1b9caae51 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/UpdateAccessKey.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/UpdateAccessKey.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[UpdateAccessKey.java demonstrates how to update the status of an IAM user's access key.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.iam; + import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.identitymanagement.model.UpdateAccessKeyRequest; @@ -32,33 +12,32 @@ */ public class UpdateAccessKey { - public static void main(String[] args) { + public static void main(String[] args) { - final String USAGE = - "To run this example, supply a username, access key id and status\n" + - "Ex: UpdateAccessKey \n"; + final String USAGE = "To run this example, supply a username, access key id and status\n" + + "Ex: UpdateAccessKey \n"; - if (args.length != 3) { - System.out.println(USAGE); - System.exit(1); - } + if (args.length != 3) { + System.out.println(USAGE); + System.exit(1); + } - String username = args[0]; - String access_id = args[1]; - String status = args[2]; + String username = args[0]; + String access_id = args[1]; + String status = args[2]; - final AmazonIdentityManagement iam = - AmazonIdentityManagementClientBuilder.defaultClient(); + final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); - UpdateAccessKeyRequest request = new UpdateAccessKeyRequest() - .withAccessKeyId(access_id) - .withUserName(username) - .withStatus(status); + UpdateAccessKeyRequest request = new UpdateAccessKeyRequest() + .withAccessKeyId(access_id) + .withUserName(username) + .withStatus(status); - UpdateAccessKeyResult response = iam.updateAccessKey(request); + UpdateAccessKeyResult response = iam.updateAccessKey(request); - System.out.printf( - "Successfully updated status of access key %s to" + - "status %s for user %s", access_id, status, username); - } + System.out.printf( + "Successfully updated status of access key %s to" + + "status %s for user %s", + access_id, status, username); + } } diff --git a/java/example_code/iam/src/main/java/aws/example/iam/UpdateServerCertificate.java b/java/example_code/iam/src/main/java/aws/example/iam/UpdateServerCertificate.java index e20a32170b9..df99e808b80 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/UpdateServerCertificate.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/UpdateServerCertificate.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[UpdateServerCertificate.java demonstrates how to update a server certificate name.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.iam; + import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.identitymanagement.model.UpdateServerCertificateRequest; @@ -33,10 +13,9 @@ public class UpdateServerCertificate { public static void main(String[] args) { - final String USAGE = - "To run this example, supply the current certificate name and\n" + - "a new name. Ex:\n\n" + - "UpdateServerCertificate \n"; + final String USAGE = "To run this example, supply the current certificate name and\n" + + "a new name. Ex:\n\n" + + "UpdateServerCertificate \n"; if (args.length != 2) { System.out.println(USAGE); @@ -46,16 +25,13 @@ public static void main(String[] args) { String cur_name = args[0]; String new_name = args[1]; - final AmazonIdentityManagement iam = - AmazonIdentityManagementClientBuilder.defaultClient(); + final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); - UpdateServerCertificateRequest request = - new UpdateServerCertificateRequest() + UpdateServerCertificateRequest request = new UpdateServerCertificateRequest() .withServerCertificateName(cur_name) .withNewServerCertificateName(new_name); - UpdateServerCertificateResult response = - iam.updateServerCertificate(request); + UpdateServerCertificateResult response = iam.updateServerCertificate(request); System.out.printf("Successfully updated server certificate to name %s", new_name); diff --git a/java/example_code/iam/src/main/java/aws/example/iam/UpdateUser.java b/java/example_code/iam/src/main/java/aws/example/iam/UpdateUser.java index 434174b1b01..782badbf8f1 100644 --- a/java/example_code/iam/src/main/java/aws/example/iam/UpdateUser.java +++ b/java/example_code/iam/src/main/java/aws/example/iam/UpdateUser.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[UpdateUser.java demonstrates how to update an IAM user's username.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.iam; + import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder; import com.amazonaws.services.identitymanagement.model.UpdateUserRequest; @@ -33,10 +13,9 @@ public class UpdateUser { public static void main(String[] args) { - final String USAGE = - "To run this example, supply the current username and a new\n" + - "username. Ex:\n\n" + - "UpdateUser \n"; + final String USAGE = "To run this example, supply the current username and a new\n" + + "username. Ex:\n\n" + + "UpdateUser \n"; if (args.length != 1) { System.out.println(USAGE); @@ -46,12 +25,11 @@ public static void main(String[] args) { String cur_name = args[0]; String new_name = args[1]; - final AmazonIdentityManagement iam = - AmazonIdentityManagementClientBuilder.defaultClient(); + final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); UpdateUserRequest request = new UpdateUserRequest() - .withUserName(cur_name) - .withNewUserName(new_name); + .withUserName(cur_name) + .withNewUserName(new_name); UpdateUserResult response = iam.updateUser(request); diff --git a/java/example_code/kda/kda-java-firehose.java b/java/example_code/kda/kda-java-firehose.java index 9020aa6a3d8..ae49f5bd23f 100644 --- a/java/example_code/kda/kda-java-firehose.java +++ b/java/example_code/kda/kda-java-firehose.java @@ -1,24 +1,6 @@ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -// snippet-sourcedescription:[kinesisanalytics.java.example.firehose-sink demonstrates how to send data from a Kinesis Data Analytics application to a Firehose Flink sink.] -// snippet-service:[kinesisanalytics] -// snippet-keyword:[java] -// snippet-keyword:[Amazon Kinesis Data Analytics] -// snippet-keyword:[Code Sample] -// snippet-keyword:[none] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-29] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[kinesisanalytics.java.example.firehose-sink] package com.amazonaws.services.kinesisanalytics; @@ -38,8 +20,6 @@ import java.util.Map; import java.util.Properties; - - public class StreamingJob { private static final String region = "us-east-1"; @@ -54,7 +34,8 @@ private static DataStream createSourceFromStaticConfig(StreamExecutionEn return env.addSource(new FlinkKinesisConsumer<>(inputStreamName, new SimpleStringSchema(), inputProperties)); } - private static DataStream createSourceFromApplicationProperties(StreamExecutionEnvironment env) throws IOException { + private static DataStream createSourceFromApplicationProperties(StreamExecutionEnvironment env) + throws IOException { Map applicationProperties = KinesisAnalyticsRuntime.getApplicationProperties(); return env.addSource(new FlinkKinesisConsumer<>(inputStreamName, new SimpleStringSchema(), applicationProperties.get("ConsumerConfigProperties"))); @@ -62,26 +43,30 @@ private static DataStream createSourceFromApplicationProperties(StreamEx private static FlinkKinesisFirehoseProducer createFirehoseSinkFromStaticConfig() { /* - * com.amazonaws.services.kinesisanalytics.flink.connectors.config.ProducerConfigConstants + * com.amazonaws.services.kinesisanalytics.flink.connectors.config. + * ProducerConfigConstants * lists of all of the properties that firehose sink can be configured with. */ Properties outputProperties = new Properties(); outputProperties.setProperty(ConsumerConfigConstants.AWS_REGION, region); - FlinkKinesisFirehoseProducer sink = new FlinkKinesisFirehoseProducer<>(outputStreamName, new SimpleStringSchema(), outputProperties); + FlinkKinesisFirehoseProducer sink = new FlinkKinesisFirehoseProducer<>(outputStreamName, + new SimpleStringSchema(), outputProperties); ProducerConfigConstants config = new ProducerConfigConstants(); return sink; } private static FlinkKinesisFirehoseProducer createFirehoseSinkFromApplicationProperties() throws IOException { /* - * com.amazonaws.services.kinesisanalytics.flink.connectors.config.ProducerConfigConstants + * com.amazonaws.services.kinesisanalytics.flink.connectors.config. + * ProducerConfigConstants * lists of all of the properties that firehose sink can be configured with. */ Map applicationProperties = KinesisAnalyticsRuntime.getApplicationProperties(); - FlinkKinesisFirehoseProducer sink = new FlinkKinesisFirehoseProducer<>(outputStreamName, new SimpleStringSchema(), + FlinkKinesisFirehoseProducer sink = new FlinkKinesisFirehoseProducer<>(outputStreamName, + new SimpleStringSchema(), applicationProperties.get("ProducerConfigProperties")); return sink; } @@ -90,17 +75,19 @@ public static void main(String[] args) throws Exception { // set up the streaming execution environment final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); - - /* if you would like to use runtime configuration properties, uncomment the lines below - * DataStream input = createSourceFromApplicationProperties(env); - */ + /* + * if you would like to use runtime configuration properties, uncomment the + * lines below + * DataStream input = createSourceFromApplicationProperties(env); + */ DataStream input = createSourceFromStaticConfig(env); // Kinesis Firehose sink input.addSink(createFirehoseSinkFromStaticConfig()); - // If you would like to use runtime configuration properties, uncomment the lines below + // If you would like to use runtime configuration properties, uncomment the + // lines below // input.addSink(createFirehoseSinkFromApplicationProperties()); env.execute("Flink Streaming Java API Skeleton"); diff --git a/java/example_code/kda/kda-java-streams.java b/java/example_code/kda/kda-java-streams.java index b052c7ffc7a..c85013a7cdd 100644 --- a/java/example_code/kda/kda-java-streams.java +++ b/java/example_code/kda/kda-java-streams.java @@ -1,24 +1,6 @@ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -// snippet-sourcedescription:[kinesisanalytics.java.example.streams-sink demonstrates how to send data from a Kinesis Data Analytics application to a Kinesis Streams Flink sink.] -// snippet-service:[kinesisanalytics] -// snippet-keyword:[java] -// snippet-keyword:[Amazon Kinesis Data Analytics] -// snippet-keyword:[Code Sample] -// snippet-keyword:[none] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-29] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[kinesisanalytics.java.example.streams-sink] package com.amazonaws.services.kinesisanalytics; @@ -35,8 +17,6 @@ import java.util.Map; import java.util.Properties; - - public class StreamingJob { private static final String region = "us-east-1"; @@ -50,8 +30,9 @@ private static DataStream createSourceFromStaticConfig(StreamExecutionEn return env.addSource(new FlinkKinesisConsumer<>(inputStreamName, new SimpleStringSchema(), inputProperties)); } - - private static DataStream createSourceFromApplicationProperties(StreamExecutionEnvironment env) throws IOException { + + private static DataStream createSourceFromApplicationProperties(StreamExecutionEnvironment env) + throws IOException { Map applicationProperties = KinesisAnalyticsRuntime.getApplicationProperties(); return env.addSource(new FlinkKinesisConsumer<>(inputStreamName, new SimpleStringSchema(), applicationProperties.get("ConsumerConfigProperties"))); @@ -67,7 +48,7 @@ private static FlinkKinesisProducer createSinkFromStaticConfig() { sink.setDefaultPartition("0"); return sink; } - + private static FlinkKinesisProducer createSinkFromApplicationProperties() throws IOException { Map applicationProperties = KinesisAnalyticsRuntime.getApplicationProperties(); FlinkKinesisProducer sink = new FlinkKinesisProducer<>(new SimpleStringSchema(), @@ -82,18 +63,20 @@ public static void main(String[] args) throws Exception { // set up the streaming execution environment final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); - - /* if you would like to use runtime configuration properties, uncomment the lines below + /* + * if you would like to use runtime configuration properties, uncomment the + * lines below * DataStream input = createSourceFromApplicationProperties(env); */ - - DataStream input = createSourceFromStaticConfig(env); + DataStream input = createSourceFromStaticConfig(env); - /* if you would like to use runtime configuration properties, uncomment the lines below + /* + * if you would like to use runtime configuration properties, uncomment the + * lines below * input.addSink(createSinkFromApplicationProperties()) */ - + input.addSink(createSinkFromStaticConfig()); env.execute("Flink Streaming Java API Skeleton"); diff --git a/java/example_code/kms/run_example.sh b/java/example_code/kms/run_example.sh index 79c73b8bfb0..6c19377f597 100755 --- a/java/example_code/kms/run_example.sh +++ b/java/example_code/kms/run_example.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 if [[ -z $* ]] ; then echo 'Supply the name of one of the example classes as an argument.' echo 'If there are arguments to the class, put them in quotes after the class name.' diff --git a/java/example_code/kms/src/main/java/aws/example/kms/CreateAlias.java b/java/example_code/kms/src/main/java/aws/example/kms/CreateAlias.java index fd3908afc34..e94175d2b02 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/CreateAlias.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/CreateAlias.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[ ListAliases.java demonstrates how to create an alias. The alias must be unique in the account and region. If you create an alias for a CMK that already has an alias, CreateAlias creates another alias to the same CMK. It does not replace the existing alias.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-09] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; @@ -16,11 +9,10 @@ public class CreateAlias { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a key id or ARN and an alias name\n" + - "Usage: CreateAlias \n" + - "Example: CreateAlias 1234abcd-12ab-34cd-56ef-1234567890ab " + - "alias/projectKey1\n"; + final String USAGE = "To run this example, supply a key id or ARN and an alias name\n" + + "Usage: CreateAlias \n" + + "Example: CreateAlias 1234abcd-12ab-34cd-56ef-1234567890ab " + + "alias/projectKey1\n"; if (args.length != 2) { System.out.println(USAGE); diff --git a/java/example_code/kms/src/main/java/aws/example/kms/CreateClient.java b/java/example_code/kms/src/main/java/aws/example/kms/CreateClient.java index f8c8061b49d..b36d4c78012 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/CreateClient.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/CreateClient.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[CreateClient.java demonstrates how to create a client for KMS.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-08] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; diff --git a/java/example_code/kms/src/main/java/aws/example/kms/CreateCustomerMasterKey.java b/java/example_code/kms/src/main/java/aws/example/kms/CreateCustomerMasterKey.java index 557e081a923..a76611288d8 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/CreateCustomerMasterKey.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/CreateCustomerMasterKey.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[CreateCustomerMasterKey.java demonstrates how to create a customer master key (CMK).] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-08] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; @@ -27,10 +20,8 @@ public static void main(String[] args) { CreateKeyResult result = kmsClient.createKey(req); System.out.printf( - "Created a customer master key with id \"%s\"%n", - result.getKeyMetadata().getArn() - ); + "Created a customer master key with id \"%s\"%n", + result.getKeyMetadata().getArn()); } } - diff --git a/java/example_code/kms/src/main/java/aws/example/kms/CreateGrant.java b/java/example_code/kms/src/main/java/aws/example/kms/CreateGrant.java index a44b4f3814a..e828e255cbe 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/CreateGrant.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/CreateGrant.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[CreateGrant.java demonstrates how to add a grant to a CMK that specifies the CMK's use.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-08] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; @@ -18,12 +11,11 @@ public class CreateGrant { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a key id or ARN, a grantee principal" + - ", and an operation\n" + - "Usage: CreateGrant \n" + - "Example: CreateGrant 1234abcd-12ab-34cd-56ef-1234567890ab " + - "arn:aws:iam::111122223333:user/Alice Encrypt\n"; + final String USAGE = "To run this example, supply a key id or ARN, a grantee principal" + + ", and an operation\n" + + "Usage: CreateGrant \n" + + "Example: CreateGrant 1234abcd-12ab-34cd-56ef-1234567890ab " + + "arn:aws:iam::111122223333:user/Alice Encrypt\n"; if (args.length != 3) { System.out.println(USAGE); diff --git a/java/example_code/kms/src/main/java/aws/example/kms/DecryptDataKey.java b/java/example_code/kms/src/main/java/aws/example/kms/DecryptDataKey.java index 4ab0e0f9892..0b67cc92efa 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/DecryptDataKey.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/DecryptDataKey.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[DecryptDataKey.java demonstrates how to decrypt a data key.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-08] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; @@ -23,8 +16,7 @@ public static void main(String[] args) { // ByteBuffer ciphertextBlob = ByteBuffer.wrap( - new byte[]{Byte.parseByte("Place your ciphertext here")} - ); + new byte[] { Byte.parseByte("Place your ciphertext here") }); DecryptRequest req = new DecryptRequest().withCiphertextBlob(ciphertextBlob); ByteBuffer plainText = kmsClient.decrypt(req).getPlaintext(); diff --git a/java/example_code/kms/src/main/java/aws/example/kms/DeleteAlias.java b/java/example_code/kms/src/main/java/aws/example/kms/DeleteAlias.java index 98b6e2e4f0a..7d6746c29ec 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/DeleteAlias.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/DeleteAlias.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[DeleteAlias.java demonstrates how to delete an alias.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-09] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; @@ -16,10 +9,9 @@ public class DeleteAlias { public static void main(String[] args) { - final String USAGE = - "To run this example, supply an alias name\n" + - "Usage: DeleteAlias \n" + - "Example: DeleteAlias alias/projectKey1\n"; + final String USAGE = "To run this example, supply an alias name\n" + + "Usage: DeleteAlias \n" + + "Example: DeleteAlias alias/projectKey1\n"; if (args.length != 1) { System.out.println(USAGE); diff --git a/java/example_code/kms/src/main/java/aws/example/kms/DisableCustomerMasterKey.java b/java/example_code/kms/src/main/java/aws/example/kms/DisableCustomerMasterKey.java index deefcd14656..88f4b8fecf2 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/DisableCustomerMasterKey.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/DisableCustomerMasterKey.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[DisableCustomerMasterKey.java demonstrates how to disable a different customer master key (CMK).] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-08] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; @@ -16,10 +9,9 @@ public class DisableCustomerMasterKey { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a key id or ARN\n" + - "Usage: DisableCustomerMasterKey \n" + - "Example: DisableCustomerMasterKey 1234abcd-12ab-34cd-56ef-1234567890ab\n"; + final String USAGE = "To run this example, supply a key id or ARN\n" + + "Usage: DisableCustomerMasterKey \n" + + "Example: DisableCustomerMasterKey 1234abcd-12ab-34cd-56ef-1234567890ab\n"; if (args.length != 1) { System.out.println(USAGE); @@ -37,4 +29,3 @@ public static void main(String[] args) { } } - diff --git a/java/example_code/kms/src/main/java/aws/example/kms/EnableCustomerMasterKey.java b/java/example_code/kms/src/main/java/aws/example/kms/EnableCustomerMasterKey.java index a9b571ffb42..475de1510dc 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/EnableCustomerMasterKey.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/EnableCustomerMasterKey.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[EnableCustomerMasterKey.java demonstrates how to enable a disabled customer master key (CMK).] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-08] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; @@ -16,10 +9,9 @@ public class EnableCustomerMasterKey { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a key id or ARN\n" + - "Usage: EnableCustomerMasterKey \n" + - "Example: EnableCustomerMasterKey 1234abcd-12ab-34cd-56ef-1234567890ab\n"; + final String USAGE = "To run this example, supply a key id or ARN\n" + + "Usage: EnableCustomerMasterKey \n" + + "Example: EnableCustomerMasterKey 1234abcd-12ab-34cd-56ef-1234567890ab\n"; if (args.length != 1) { System.out.println(USAGE); @@ -37,4 +29,3 @@ public static void main(String[] args) { } } - diff --git a/java/example_code/kms/src/main/java/aws/example/kms/EncryptDataKey.java b/java/example_code/kms/src/main/java/aws/example/kms/EncryptDataKey.java index 409e18c8e59..779dffe878e 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/EncryptDataKey.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/EncryptDataKey.java @@ -1,16 +1,8 @@ -//snippet-sourcedescription:[EncryptDataKey.java demonstrates how to encrypt data keys] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-08] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; - import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClientBuilder; import com.amazonaws.services.kms.model.EncryptRequest; @@ -25,7 +17,7 @@ public static void main(String[] args) { // // Replace the following fictitious CMK ARN with a valid CMK ID or ARN String keyId = "1234abcd-12ab-34cd-56ef-1234567890ab"; - ByteBuffer plaintext = ByteBuffer.wrap(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}); + ByteBuffer plaintext = ByteBuffer.wrap(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }); EncryptRequest req = new EncryptRequest().withKeyId(keyId).withPlaintext(plaintext); ByteBuffer ciphertext = kmsClient.encrypt(req).getCiphertextBlob(); diff --git a/java/example_code/kms/src/main/java/aws/example/kms/GenerateDataKey.java b/java/example_code/kms/src/main/java/aws/example/kms/GenerateDataKey.java index c4c762583ae..a63ae53a398 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/GenerateDataKey.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/GenerateDataKey.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[GenerateDataKey.java demonstrates how to generate a data key for KMS. This operation returns plaintext and encrypted copies of the data key that it creates.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-08] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; @@ -20,11 +13,10 @@ public class GenerateDataKey { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a key id or ARN and a KeySpec\n" + - "Usage: GenerateDataKey \n" + - "Example: GenerateDataKey 1234abcd-12ab-34cd-56ef-1234567890ab" + - " AES_256\n"; + final String USAGE = "To run this example, supply a key id or ARN and a KeySpec\n" + + "Usage: GenerateDataKey \n" + + "Example: GenerateDataKey 1234abcd-12ab-34cd-56ef-1234567890ab" + + " AES_256\n"; if (args.length != 2) { System.out.println(USAGE); @@ -49,11 +41,9 @@ public static void main(String[] args) { ByteBuffer encryptedKey = dataKeyResult.getCiphertextBlob(); System.out.printf( - "Successfully generated an encrypted data key: %s%n", - Base64.getEncoder().encodeToString(encryptedKey.array()) - ); + "Successfully generated an encrypted data key: %s%n", + Base64.getEncoder().encodeToString(encryptedKey.array())); } } - diff --git a/java/example_code/kms/src/main/java/aws/example/kms/GetKeyPolicy.java b/java/example_code/kms/src/main/java/aws/example/kms/GetKeyPolicy.java index 31c6d9cf4e7..960a45f0553 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/GetKeyPolicy.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/GetKeyPolicy.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[GetKeyPolicy.java demonstrates how to get the key policy for a customer master key (CMK).] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-08] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; @@ -17,10 +10,9 @@ public class GetKeyPolicy { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a key id or ARN\n" + - "Usage: GetKeyPolicy \n" + - "Example: GetKeyPolicy 1234abcd-12ab-34cd-56ef-1234567890ab\n"; + final String USAGE = "To run this example, supply a key id or ARN\n" + + "Usage: GetKeyPolicy \n" + + "Example: GetKeyPolicy 1234abcd-12ab-34cd-56ef-1234567890ab\n"; if (args.length != 1) { System.out.println(USAGE); @@ -41,4 +33,3 @@ public static void main(String[] args) { } } - diff --git a/java/example_code/kms/src/main/java/aws/example/kms/ListAliases.java b/java/example_code/kms/src/main/java/aws/example/kms/ListAliases.java index d56352e72aa..23656207987 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/ListAliases.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/ListAliases.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[ ListAliases.java demonstrates how to list aliases in the account and region.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-09] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; @@ -27,7 +20,7 @@ public static void main(String[] args) { String nextMarker = null; do { ListAliasesRequest req = new ListAliasesRequest() - .withMarker(nextMarker).withLimit(limit); + .withMarker(nextMarker).withLimit(limit); ListAliasesResult result = kmsClient.listAliases(req); for (AliasListEntry alias : result.getAliases()) { System.out.printf("Found an alias named \"%s\".%n", alias.getAliasName()); diff --git a/java/example_code/kms/src/main/java/aws/example/kms/ListCustomerMasterKeys.java b/java/example_code/kms/src/main/java/aws/example/kms/ListCustomerMasterKeys.java index 0108f685c8e..99a8906d662 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/ListCustomerMasterKeys.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/ListCustomerMasterKeys.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[ListCustomerMasterKeys.java demonstrates how to get the IDs and ARNs of the customer master keys (CMK).] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-08] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; diff --git a/java/example_code/kms/src/main/java/aws/example/kms/ListKeyPolicies.java b/java/example_code/kms/src/main/java/aws/example/kms/ListKeyPolicies.java index f4962432552..6b0c405763c 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/ListKeyPolicies.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/ListKeyPolicies.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[ListKeyPolicies.java demonstrates how to dget the names of key policies for a customer master key.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-08] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; @@ -17,10 +10,9 @@ public class ListKeyPolicies { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a key id or ARN\n" + - "Usage: ListKeyPolicies \n" + - "Example: ListKeyPolicies 1234abcd-12ab-34cd-56ef-1234567890ab\n"; + final String USAGE = "To run this example, supply a key id or ARN\n" + + "Usage: ListKeyPolicies \n" + + "Example: ListKeyPolicies 1234abcd-12ab-34cd-56ef-1234567890ab\n"; if (args.length != 1) { System.out.println(USAGE); @@ -36,7 +28,7 @@ public static void main(String[] args) { String nextMarker = null; do { ListKeyPoliciesRequest req = new ListKeyPoliciesRequest() - .withMarker(nextMarker).withKeyId(keyId); + .withMarker(nextMarker).withKeyId(keyId); ListKeyPoliciesResult result = kmsClient.listKeyPolicies(req); for (String policyName : result.getPolicyNames()) { System.out.printf("Found a policy named \"%s\".%n", policyName); diff --git a/java/example_code/kms/src/main/java/aws/example/kms/ReencryptDataKey.java b/java/example_code/kms/src/main/java/aws/example/kms/ReencryptDataKey.java index d6fe6017415..575d4af7f4d 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/ReencryptDataKey.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/ReencryptDataKey.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[ReencryptDataKey.java demonstrates how to decrypt an encrypted data key, and then immediately re-encrypt the data key under a different customer master key (CMK).] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-08] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; @@ -21,8 +14,7 @@ public static void main(String[] args) { AWSKMS kmsClient = AWSKMSClientBuilder.standard().build(); // Re-encrypt a data key - ByteBuffer sourceCiphertextBlob = ByteBuffer.wrap(new byte[]{Byte.parseByte("Place your ciphertext here")}); - + ByteBuffer sourceCiphertextBlob = ByteBuffer.wrap(new byte[] { Byte.parseByte("Place your ciphertext here") }); // Replace the following fictitious CMK ARN with a valid CMK ID or ARN String destinationKeyId = "1234abcd-12ab-34cd-56ef-1234567890ab"; @@ -33,4 +25,3 @@ public static void main(String[] args) { ByteBuffer destinationCipherTextBlob = kmsClient.reEncrypt(req).getCiphertextBlob(); } } - diff --git a/java/example_code/kms/src/main/java/aws/example/kms/RetireGrant.java b/java/example_code/kms/src/main/java/aws/example/kms/RetireGrant.java index 15dfed3ca11..243eda057fd 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/RetireGrant.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/RetireGrant.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[RetireGrant.java demonstrates how to retire a grant for an AWS KMS customer master key.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-08] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; diff --git a/java/example_code/kms/src/main/java/aws/example/kms/RevokeGrant.java b/java/example_code/kms/src/main/java/aws/example/kms/RevokeGrant.java index e1a86d6aa06..91792d372fa 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/RevokeGrant.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/RevokeGrant.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[RevokeGrant.java demonstrates how to evoke a grant to an AWS KMS customer master key.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-08] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; @@ -16,10 +9,9 @@ public class RevokeGrant { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a key id or ARN and a grant id\n" + - "Usage: RevokeGrant \n" + - "Example: RevokeGrant 1234abcd-12ab-34cd-56ef-1234567890ab grant1\n"; + final String USAGE = "To run this example, supply a key id or ARN and a grant id\n" + + "Usage: RevokeGrant \n" + + "Example: RevokeGrant 1234abcd-12ab-34cd-56ef-1234567890ab grant1\n"; if (args.length != 2) { System.out.println(USAGE); diff --git a/java/example_code/kms/src/main/java/aws/example/kms/SetKeyPolicy.java b/java/example_code/kms/src/main/java/aws/example/kms/SetKeyPolicy.java index ec03cba1096..109c336edde 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/SetKeyPolicy.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/SetKeyPolicy.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[SetKeyPolicy.java demonstrates how to establish or change a key policy for a CMK.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-08] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; @@ -40,9 +33,9 @@ public static void main(String[] args) { " }]" + "}"; - PutKeyPolicyRequest req = new PutKeyPolicyRequest().withKeyId(keyId).withPolicy(policy).withPolicyName(policyName); + PutKeyPolicyRequest req = new PutKeyPolicyRequest().withKeyId(keyId).withPolicy(policy) + .withPolicyName(policyName); kmsClient.putKeyPolicy(req); } } - diff --git a/java/example_code/kms/src/main/java/aws/example/kms/UpdateAlias.java b/java/example_code/kms/src/main/java/aws/example/kms/UpdateAlias.java index cc54c42614c..4e81f6c993a 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/UpdateAlias.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/UpdateAlias.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[UpdateAlias.java demonstrates how to associate an existing alias with a different CMK.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-09] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; @@ -16,11 +9,10 @@ public class UpdateAlias { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a key id or ARN and an alias name\n" + - "Usage: UpdateAlias \n" + - "Example: UpdateAlias 1234abcd-12ab-34cd-56ef-1234567890ab " + - "alias/projectKey1\n"; + final String USAGE = "To run this example, supply a key id or ARN and an alias name\n" + + "Usage: UpdateAlias \n" + + "Example: UpdateAlias 1234abcd-12ab-34cd-56ef-1234567890ab " + + "alias/projectKey1\n"; if (args.length != 2) { System.out.println(USAGE); diff --git a/java/example_code/kms/src/main/java/aws/example/kms/ViewCustomerMasterKey.java b/java/example_code/kms/src/main/java/aws/example/kms/ViewCustomerMasterKey.java index 9005e424657..33432efc42d 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/ViewCustomerMasterKey.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/ViewCustomerMasterKey.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[ViewCustomerMasterKey.java demonstrates get detailed information about a customer master key (CMK).] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-08] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; @@ -18,10 +11,9 @@ public class ViewCustomerMasterKey { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a key id or ARN\n" + - "Usage: ViewCustomerMasterKey \n" + - "Example: ViewCustomerMasterKey 1234abcd-12ab-34cd-56ef-1234567890ab\n"; + final String USAGE = "To run this example, supply a key id or ARN\n" + + "Usage: ViewCustomerMasterKey \n" + + "Example: ViewCustomerMasterKey 1234abcd-12ab-34cd-56ef-1234567890ab\n"; if (args.length != 1) { System.out.println(USAGE); @@ -50,4 +42,3 @@ public static void main(String[] args) { } } - diff --git a/java/example_code/kms/src/main/java/aws/example/kms/ViewGrants.java b/java/example_code/kms/src/main/java/aws/example/kms/ViewGrants.java index 9f999b0ac7f..515ef4a38e5 100644 --- a/java/example_code/kms/src/main/java/aws/example/kms/ViewGrants.java +++ b/java/example_code/kms/src/main/java/aws/example/kms/ViewGrants.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[ViewGrants.java demonstrates how to get detailed information about the grants on an AWS KMS customer master key .] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon KMS] -//snippet-service:[kms] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-04-08] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.kms; @@ -18,10 +11,9 @@ public class ViewGrants { public static void main(String[] args) { - final String USAGE = - "To run this example, supply a key id or ARN\n" + - "Usage: ViewGrants \n" + - "Example: ViewGrants 1234abcd-12ab-34cd-56ef-1234567890ab\n"; + final String USAGE = "To run this example, supply a key id or ARN\n" + + "Usage: ViewGrants \n" + + "Example: ViewGrants 1234abcd-12ab-34cd-56ef-1234567890ab\n"; if (args.length != 1) { System.out.println(USAGE); @@ -42,8 +34,8 @@ public static void main(String[] args) { ListGrantsResult result = kmsClient.listGrants(request); for (GrantListEntry grant : result.getGrants()) { System.out.printf("Found grant \"%s\" with grantee principal " + - "%s, operations %s, and constraints %s.%n", grant.getGrantId(), - grant.getGranteePrincipal(), grant.getOperations(), grant.getConstraints()); + "%s, operations %s, and constraints %s.%n", grant.getGrantId(), + grant.getGranteePrincipal(), grant.getOperations(), grant.getConstraints()); } nextMarker = result.getNextMarker(); } while (nextMarker != null); diff --git a/java/example_code/lambda/src/main/java/com/example/lambda/DeleteFunction.java b/java/example_code/lambda/src/main/java/com/example/lambda/DeleteFunction.java index ae80718ba94..0be26ee47fc 100644 --- a/java/example_code/lambda/src/main/java/com/example/lambda/DeleteFunction.java +++ b/java/example_code/lambda/src/main/java/com/example/lambda/DeleteFunction.java @@ -1,27 +1,5 @@ -/** - * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[DeleteFunction.java demonstrates how to delete an AWS Lambda function by using the LambdaClient object] -// snippet-service:[Lambda] -// snippet-keyword:[Java] -// snippet-keyword:[Amazon Lambda] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-11-19] -// snippet-sourceauthor:[AWS-scmacdon] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lambda.java1.DeleteFunction.complete] package com.example.lambda; @@ -54,7 +32,7 @@ public static void main(String[] args) { DeleteFunctionRequest delFunc = new DeleteFunctionRequest(); delFunc.withFunctionName(functionName); - //Delete the function + // Delete the function awsLambda.deleteFunction(delFunc); System.out.println("The function is deleted"); diff --git a/java/example_code/lambda/src/main/java/com/example/lambda/LambdaInvokeFunction.java b/java/example_code/lambda/src/main/java/com/example/lambda/LambdaInvokeFunction.java index c4dd2e4be6b..eabdb9ab739 100644 --- a/java/example_code/lambda/src/main/java/com/example/lambda/LambdaInvokeFunction.java +++ b/java/example_code/lambda/src/main/java/com/example/lambda/LambdaInvokeFunction.java @@ -1,30 +1,8 @@ -/** - * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[LambdaInvoke.java demonstrates how to invoke an AWS Lambda function by using the AWSLambda object] -// snippet-service:[Lambda] -// snippet-keyword:[Java] -// snippet-keyword:[Amazon Lambda] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-11-19] -// snippet-sourceauthor:[AWS-scmacdon] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lambda.java1.LambdaInvoke.complete] -package com.example.lambda ; +package com.example.lambda; // snippet-start:[lambda.java1.invoke.import] import com.amazonaws.auth.profile.ProfileCredentialsProvider; @@ -38,14 +16,14 @@ import java.nio.charset.StandardCharsets; // snippet-end:[lambda.java1.invoke.import] - public class LambdaInvokeFunction { public static void main(String[] args) { - /* - Function names appear as arn:aws:lambda:us-west-2:335556330391:function:HelloFunction - you can retrieve the value by looking at the function in the AWS Console + /* + * Function names appear as + * arn:aws:lambda:us-west-2:335556330391:function:HelloFunction + * you can retrieve the value by looking at the function in the AWS Console */ if (args.length < 1) { System.out.println("Please specify a function name"); @@ -72,7 +50,7 @@ public static void main(String[] args) { String ans = new String(invokeResult.getPayload().array(), StandardCharsets.UTF_8); - //write out the return value + // write out the return value System.out.println(ans); } catch (ServiceException e) { diff --git a/java/example_code/lambda/src/main/java/com/example/lambda/ListFunctions.java b/java/example_code/lambda/src/main/java/com/example/lambda/ListFunctions.java index 6a0238f202b..dadd65c8bbe 100644 --- a/java/example_code/lambda/src/main/java/com/example/lambda/ListFunctions.java +++ b/java/example_code/lambda/src/main/java/com/example/lambda/ListFunctions.java @@ -1,27 +1,5 @@ -/** - * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[ListLambdaFunctions.java demonstrates how to list all functions specific to the account by using the AWSLambda object] -// snippet-service:[Lambda] -// snippet-keyword:[Java] -// snippet-keyword:[Amazon Lambda] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-11-19] -// snippet-sourceauthor:[AWS-scmacdon] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lambda.java1.ListLambdaFunctions.complete] package com.example.lambda; @@ -38,7 +16,6 @@ import java.util.List; // snippet-end:[lambda.java1.list.import] - public class ListFunctions { public static void main(String[] args) { @@ -55,10 +32,10 @@ public static void main(String[] args) { List list = functionResult.getFunctions(); - for (Iterator iter = list.iterator(); iter.hasNext(); ) { - FunctionConfiguration config = (FunctionConfiguration)iter.next(); + for (Iterator iter = list.iterator(); iter.hasNext();) { + FunctionConfiguration config = (FunctionConfiguration) iter.next(); - System.out.println("The function name is "+config.getFunctionName()); + System.out.println("The function name is " + config.getFunctionName()); } } catch (ServiceException e) { diff --git a/java/example_code/mediastore/run_example.sh b/java/example_code/mediastore/run_example.sh index 616f3eb4ebc..76f3a07a3d1 100755 --- a/java/example_code/mediastore/run_example.sh +++ b/java/example_code/mediastore/run_example.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 if [[ -z $* ]] ; then echo 'Supply the name of one of the example classes as an argument.' echo 'If there are arguments to the class, put them in quotes after the class name.' diff --git a/java/example_code/mediastore/src/main/java/aws/example/mediastore/CreateContainer.java b/java/example_code/mediastore/src/main/java/aws/example/mediastore/CreateContainer.java index b6bfdde367d..5df0220f0b2 100644 --- a/java/example_code/mediastore/src/main/java/aws/example/mediastore/CreateContainer.java +++ b/java/example_code/mediastore/src/main/java/aws/example/mediastore/CreateContainer.java @@ -1,25 +1,7 @@ -//snippet-sourcedescription:[CreateContainer.java demonstrates how to create an AWS Elemental MediaStore container.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[mediastore] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-11-06] -//snippet-sourceauthor:[rhcarvalho] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.mediastore; + import com.amazonaws.services.mediastore.AWSMediaStore; import com.amazonaws.services.mediastore.AWSMediaStoreClientBuilder; import com.amazonaws.services.mediastore.model.Container; @@ -33,15 +15,13 @@ * This code expects that you have AWS credentials set up per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ -public class CreateContainer -{ - public static void main(String[] args) - { +public class CreateContainer { + public static void main(String[] args) { final String USAGE = "\n" + - "CreateContainer - create an AWS Elemental MediaStore container\n\n" + - "Usage: CreateContainer \n\n" + - "Where:\n" + - " name - the name of the container to create.\n"; + "CreateContainer - create an AWS Elemental MediaStore container\n\n" + + "Usage: CreateContainer \n\n" + + "Where:\n" + + " name - the name of the container to create.\n"; if (args.length < 1) { System.out.println(USAGE); @@ -62,7 +42,7 @@ public static void main(String[] args) public static Container createContainer(String name) { final AWSMediaStore mediastore = AWSMediaStoreClientBuilder.defaultClient(); final CreateContainerRequest request = new CreateContainerRequest() - .withContainerName(name.trim()); + .withContainerName(name.trim()); try { final CreateContainerResult result = mediastore.createContainer(request); return result.getContainer(); diff --git a/java/example_code/mediastore/src/main/java/aws/example/mediastore/ListContainers.java b/java/example_code/mediastore/src/main/java/aws/example/mediastore/ListContainers.java index 99dd00284ab..0465512e062 100755 --- a/java/example_code/mediastore/src/main/java/aws/example/mediastore/ListContainers.java +++ b/java/example_code/mediastore/src/main/java/aws/example/mediastore/ListContainers.java @@ -1,25 +1,7 @@ -//snippet-sourcedescription:[ListContainers.java demonstrates how to list your AWS Elemental MediaStore containers.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[mediastore] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-11-06] -//snippet-sourceauthor:[rhcarvalho] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.mediastore; + import com.amazonaws.services.mediastore.AWSMediaStore; import com.amazonaws.services.mediastore.AWSMediaStoreClientBuilder; import com.amazonaws.services.mediastore.model.Container; @@ -33,10 +15,8 @@ * This code expects that you have AWS credentials set up per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ -public class ListContainers -{ - public static void main(String[] args) - { +public class ListContainers { + public static void main(String[] args) { final AWSMediaStore mediastore = AWSMediaStoreClientBuilder.defaultClient(); final ListContainersResult result = mediastore.listContainers(new ListContainersRequest()); final List containers = result.getContainers(); diff --git a/java/example_code/mediastore/src/main/java/aws/example/mediastore/ListItems.java b/java/example_code/mediastore/src/main/java/aws/example/mediastore/ListItems.java index c37a12d5b9d..566cc55c955 100755 --- a/java/example_code/mediastore/src/main/java/aws/example/mediastore/ListItems.java +++ b/java/example_code/mediastore/src/main/java/aws/example/mediastore/ListItems.java @@ -1,25 +1,7 @@ -//snippet-sourcedescription:[ListItems.java demonstrates how to list objects and folders within an AWS Elemental MediaStore container.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[mediastore] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-11-06] -//snippet-sourceauthor:[rhcarvalho] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.mediastore; + import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration; import com.amazonaws.regions.DefaultAwsRegionProviderChain; import com.amazonaws.services.mediastore.AWSMediaStore; @@ -40,14 +22,12 @@ * This code expects that you have AWS credentials set up per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ -public class ListItems -{ - public static void main(String[] args) - { +public class ListItems { + public static void main(String[] args) { final String USAGE = "\n" + - "To run this example, supply the name of a container and an optional path!\n" + - "\n" + - "Ex: ListItems [path]\n"; + "To run this example, supply the name of a container and an optional path!\n" + + "\n" + + "Ex: ListItems [path]\n"; if (args.length < 1) { System.out.println(USAGE); @@ -72,15 +52,15 @@ public static void main(String[] args) final EndpointConfiguration endpointConfig = new EndpointConfiguration(endpoint, region); final AWSMediaStoreData mediastoredata = AWSMediaStoreDataClientBuilder - .standard() - .withEndpointConfiguration(endpointConfig) - .build(); + .standard() + .withEndpointConfiguration(endpointConfig) + .build(); final ListItemsRequest request = new ListItemsRequest() - .withPath(path); + .withPath(path); ListItemsResult result = mediastoredata.listItems(request); List items = result.getItems(); - for (Item i: items) { + for (Item i : items) { System.out.printf("* (%s)\t%s\n", i.getType(), i.getName()); } } @@ -88,7 +68,7 @@ public static void main(String[] args) public static String getContainerEndpoint(String name) { final AWSMediaStore mediastore = AWSMediaStoreClientBuilder.defaultClient(); final DescribeContainerRequest request = new DescribeContainerRequest() - .withContainerName(name.trim()); + .withContainerName(name.trim()); try { final DescribeContainerResult result = mediastore.describeContainer(request); return result.getContainer().getEndpoint(); diff --git a/java/example_code/mediastore/src/main/java/aws/example/mediastore/PutObject.java b/java/example_code/mediastore/src/main/java/aws/example/mediastore/PutObject.java index a95f2a715bb..9a9677ec785 100755 --- a/java/example_code/mediastore/src/main/java/aws/example/mediastore/PutObject.java +++ b/java/example_code/mediastore/src/main/java/aws/example/mediastore/PutObject.java @@ -1,25 +1,7 @@ -//snippet-sourcedescription:[PutObject.java demonstrates how to upload a file to an AWS Elemental MediaStore container.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[mediastore] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-06] -//snippet-sourceauthor:[rhcarvalho] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.mediastore; + import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration; import com.amazonaws.regions.DefaultAwsRegionProviderChain; import com.amazonaws.services.mediastore.AWSMediaStore; @@ -41,15 +23,13 @@ * This code expects that you have AWS credentials set up per: * http://docs.aws.amazon.com/java-sdk/latest/developer-guide/setup-credentials.html */ -public class PutObject -{ - public static void main(String[] args) - { +public class PutObject { + public static void main(String[] args) { final String USAGE = "\n" + - "To run this example, supply the name of a container and a file to\n" + - "upload to it.\n" + - "\n" + - "Ex: PutObject \n"; + "To run this example, supply the name of a container and a file to\n" + + "upload to it.\n" + + "\n" + + "Ex: PutObject \n"; if (args.length < 2) { System.out.println(USAGE); @@ -71,7 +51,8 @@ public static void main(String[] args) } } - public static PutObjectResult putObject(String containerName, String filePath, InputStream body) throws IOException { + public static PutObjectResult putObject(String containerName, String filePath, InputStream body) + throws IOException { final String endpoint = getContainerEndpoint(containerName); if (endpoint == null || endpoint.isEmpty()) { System.err.println("Could not determine container endpoint!"); @@ -81,13 +62,13 @@ public static PutObjectResult putObject(String containerName, String filePath, I final EndpointConfiguration endpointConfig = new EndpointConfiguration(endpoint, region); final AWSMediaStoreData mediastoredata = AWSMediaStoreDataClientBuilder - .standard() - .withEndpointConfiguration(endpointConfig) - .build(); + .standard() + .withEndpointConfiguration(endpointConfig) + .build(); final PutObjectRequest request = new PutObjectRequest() - .withContentType("application/octet-stream") - .withBody(body) - .withPath(filePath); + .withContentType("application/octet-stream") + .withBody(body) + .withPath(filePath); try { return mediastoredata.putObject(request); @@ -101,7 +82,7 @@ public static PutObjectResult putObject(String containerName, String filePath, I public static String getContainerEndpoint(String name) { final AWSMediaStore mediastore = AWSMediaStoreClientBuilder.defaultClient(); final DescribeContainerRequest request = new DescribeContainerRequest() - .withContainerName(name.trim()); + .withContainerName(name.trim()); try { final DescribeContainerResult result = mediastore.describeContainer(request); return result.getContainer().getEndpoint(); diff --git a/java/example_code/pinpoint-email/pinpoint_send_email_message_email_api.java b/java/example_code/pinpoint-email/pinpoint_send_email_message_email_api.java index 16d642f140c..9c0c4a89c64 100644 --- a/java/example_code/pinpoint-email/pinpoint_send_email_message_email_api.java +++ b/java/example_code/pinpoint-email/pinpoint_send_email_message_email_api.java @@ -1,30 +1,10 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[pinpoint_send_email_message_email_api demonstrates how to send a transactional email message by using the Amazon Pinpoint Email API.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Pinpoint Email API] -// snippet-keyword:[Code Sample] -// snippet-keyword:[SendEmail] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2019-01-20] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[pinpoint.java.pinpoint_send_email_message_email_api.complete] package com.amazonaws.samples; + import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -42,113 +22,101 @@ public class SendMessage { - // The AWS Region that you want to use to send the email. For a list of - // AWS Regions where the Amazon Pinpoint Email API is available, see - // https://docs.aws.amazon.com/pinpoint-email/latest/APIReference - static final String region = "us-west-2"; - - // The "From" address. This address has to be verified in Amazon - // Pinpoint in the region you're using to send email. - static final String senderAddress = "sender@example.com"; - - // The address on the "To" line. If your Amazon Pinpoint account is in - // the sandbox, this address also has to be verified. - static final String toAddress = "recipient@example.com"; - - // CC and BCC addresses. If your account is in the sandbox, these - // addresses have to be verified. - // In this example, there are several CC recipients. Each address is separated - // with a comma. We convert this string to an ArrayList later in the example. - static final String ccAddress = "cc_recipient0@example.com, cc_recipient1@example.com"; - static final String bccAddress = "bcc_recipient@example.com"; - - // The configuration set that you want to use to send the email. - static final String configurationSet = "ConfigSet"; - - // The subject line of the email. - static final String subject = "Amazon Pinpoint Email API test"; - - // The email body for recipients with non-HTML email clients. - static final String textBody = "Amazon Pinpoint Email Test (Java)\r\n" - + "This email was sent using the Amazon Pinpoint " - + "Email API using the AWS SDK for Java."; - - // The body of the email for recipients whose email clients support - // HTML content. - static final String htmlBody = "

Amazon Pinpoint test (AWS SDK for Java)

" - + "

This email was sent through the " - + "Amazon Pinpoint Email API using the " - + "AWS SDK for Java"; - - // The message tags that you want to apply to the email. - static final String tagKey0 = "key0"; - static final String tagValue0 = "value0"; - static final String tagKey1 = "key1"; - static final String tagValue1 = "value1"; - - // The character encoding the you want to use for the subject line and - // message body of the email. - static final String charset = "UTF-8"; - - public static void main(String[] args) throws IOException { - - // Convert comma-separated lists of To, CC, and BCC Addresses into collections. - // This works even if the string only contains a single email address. - Collection toAddresses = - new ArrayList(Arrays.asList(toAddress.split("\\s*,\\s*"))); - Collection ccAddresses = - new ArrayList(Arrays.asList(ccAddress.split("\\s*,\\s*"))); - Collection bccAddresses = - new ArrayList(Arrays.asList(bccAddress.split("\\s*,\\s*"))); - - try { - // Create a new email client - AmazonPinpointEmail client = AmazonPinpointEmailClientBuilder.standard() - .withRegion(region).build(); - - // Combine all of the components of the email to create a request. - SendEmailRequest request = new SendEmailRequest() - .withFromEmailAddress(senderAddress) - .withConfigurationSetName(configurationSet) - .withDestination(new Destination() - .withToAddresses(toAddresses) - .withCcAddresses(ccAddresses) - .withBccAddresses(bccAddresses) - ) - .withContent(new EmailContent() - .withSimple(new Message() - .withSubject(new Content() - .withCharset(charset) - .withData(subject) - ) - .withBody(new Body() - .withHtml(new Content() - .withCharset(charset) - .withData(htmlBody) - ) - .withText(new Content() - .withCharset(charset) - .withData(textBody) - ) - ) - ) - ) - .withEmailTags(new MessageTag() - .withName(tagKey0) - .withValue(tagValue0) - ) - .withEmailTags(new MessageTag() - .withName(tagKey1) - .withValue(tagValue1) - ); - client.sendEmail(request); - System.out.println("Email sent!"); - System.out.println(request); - } catch (Exception ex) { - System.out.println("The email wasn't sent. Error message: " - + ex.getMessage()); + // The AWS Region that you want to use to send the email. For a list of + // AWS Regions where the Amazon Pinpoint Email API is available, see + // https://docs.aws.amazon.com/pinpoint-email/latest/APIReference + static final String region = "us-west-2"; + + // The "From" address. This address has to be verified in Amazon + // Pinpoint in the region you're using to send email. + static final String senderAddress = "sender@example.com"; + + // The address on the "To" line. If your Amazon Pinpoint account is in + // the sandbox, this address also has to be verified. + static final String toAddress = "recipient@example.com"; + + // CC and BCC addresses. If your account is in the sandbox, these + // addresses have to be verified. + // In this example, there are several CC recipients. Each address is separated + // with a comma. We convert this string to an ArrayList later in the example. + static final String ccAddress = "cc_recipient0@example.com, cc_recipient1@example.com"; + static final String bccAddress = "bcc_recipient@example.com"; + + // The configuration set that you want to use to send the email. + static final String configurationSet = "ConfigSet"; + + // The subject line of the email. + static final String subject = "Amazon Pinpoint Email API test"; + + // The email body for recipients with non-HTML email clients. + static final String textBody = "Amazon Pinpoint Email Test (Java)\r\n" + + "This email was sent using the Amazon Pinpoint " + + "Email API using the AWS SDK for Java."; + + // The body of the email for recipients whose email clients support + // HTML content. + static final String htmlBody = "

Amazon Pinpoint test (AWS SDK for Java)

" + + "

This email was sent through the " + + "Amazon Pinpoint Email API using the " + + "AWS SDK for Java"; + + // The message tags that you want to apply to the email. + static final String tagKey0 = "key0"; + static final String tagValue0 = "value0"; + static final String tagKey1 = "key1"; + static final String tagValue1 = "value1"; + + // The character encoding the you want to use for the subject line and + // message body of the email. + static final String charset = "UTF-8"; + + public static void main(String[] args) throws IOException { + + // Convert comma-separated lists of To, CC, and BCC Addresses into collections. + // This works even if the string only contains a single email address. + Collection toAddresses = new ArrayList(Arrays.asList(toAddress.split("\\s*,\\s*"))); + Collection ccAddresses = new ArrayList(Arrays.asList(ccAddress.split("\\s*,\\s*"))); + Collection bccAddresses = new ArrayList(Arrays.asList(bccAddress.split("\\s*,\\s*"))); + + try { + // Create a new email client + AmazonPinpointEmail client = AmazonPinpointEmailClientBuilder.standard() + .withRegion(region).build(); + + // Combine all of the components of the email to create a request. + SendEmailRequest request = new SendEmailRequest() + .withFromEmailAddress(senderAddress) + .withConfigurationSetName(configurationSet) + .withDestination(new Destination() + .withToAddresses(toAddresses) + .withCcAddresses(ccAddresses) + .withBccAddresses(bccAddresses)) + .withContent(new EmailContent() + .withSimple(new Message() + .withSubject(new Content() + .withCharset(charset) + .withData(subject)) + .withBody(new Body() + .withHtml(new Content() + .withCharset(charset) + .withData(htmlBody)) + .withText(new Content() + .withCharset(charset) + .withData(textBody))))) + .withEmailTags(new MessageTag() + .withName(tagKey0) + .withValue(tagValue0)) + .withEmailTags(new MessageTag() + .withName(tagKey1) + .withValue(tagValue1)); + client.sendEmail(request); + System.out.println("Email sent!"); + System.out.println(request); + } catch (Exception ex) { + System.out.println("The email wasn't sent. Error message: " + + ex.getMessage()); + } } - } } // snippet-end:[pinpoint.java.pinpoint_send_email_message_email_api.complete] diff --git a/java/example_code/pinpoint-sms-voice/pinpoint_send_voice_message_sms_voice_api.java b/java/example_code/pinpoint-sms-voice/pinpoint_send_voice_message_sms_voice_api.java index 88b5e0b6f99..601bb2f48b4 100644 --- a/java/example_code/pinpoint-sms-voice/pinpoint_send_voice_message_sms_voice_api.java +++ b/java/example_code/pinpoint-sms-voice/pinpoint_send_voice_message_sms_voice_api.java @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[pinpoint_send_voice_message_sms_voice_api demonstrates how to send a transactional voice message by using the SendVoiceMessage operation in the Amazon Pinpoint SMS and Voice API.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Pinpoint SMS and Voice API] -// snippet-keyword:[Code Sample] -// snippet-keyword:[SendVoiceMessage] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2019-01-20] -// snippet-sourceauthor:[AWS] // snippet-start:[pinpoint.java.pinpoint_send_voice_message_sms_voice_api.complete] package com.amazonaws.samples; @@ -35,63 +14,62 @@ import com.amazonaws.services.pinpointsmsvoice.model.VoiceMessageContent; public class SendMessage { - + // The AWS Region that you want to use to send the voice message. For a list of // AWS Regions where the Amazon Pinpoint SMS and Voice API is available, see // https://docs.aws.amazon.com/pinpoint-sms-voice/latest/APIReference/ static final String region = "us-east-1"; - + // The phone number that the message is sent from. The phone number that you - // specify has to be associated with your Amazon Pinpoint account. For best + // specify has to be associated with your Amazon Pinpoint account. For best // results, you should specify the phone number in E.164 format. static final String originationNumber = "+12065550110"; - - // The recipient's phone number. For best results, you should specify the + + // The recipient's phone number. For best results, you should specify the // phone number in E.164 format. static final String destinationNumber = "+12065550142"; - + // The Amazon Polly voice that you want to use to send the message. For a list // of voices, see https://docs.aws.amazon.com/polly/latest/dg/voicelist.html static final String voiceName = "Matthew"; - + // The language to use when sending the message. For a list of supported - // languages, see https://docs.aws.amazon.com/polly/latest/dg/SupportedLanguage.html + // languages, see + // https://docs.aws.amazon.com/polly/latest/dg/SupportedLanguage.html static final String languageCode = "en-US"; - + // The content of the message. This example uses SSML to customize and control - // certain aspects of the message, such as by adding pauses and changing + // certain aspects of the message, such as by adding pauses and changing // phonation. The message can't contain any line breaks. static final String ssmlMessage = "This is a test message sent from " - + "Amazon Pinpoint " - + "using the AWS " - + "SDK for Java. " - + "Thank " - + "you for listening."; - - // The phone number that you want to appear on the recipient's device. The + + "Amazon Pinpoint " + + "using the AWS " + + "SDK for Java. " + + "Thank " + + "you for listening."; + + // The phone number that you want to appear on the recipient's device. The // phone number that you specify has to be associated with your Amazon Pinpoint // account. static final String callerId = "+12065550199"; - + // The configuration set that you want to use to send the message. static final String configurationSet = "ConfigSet"; - + public static void main(String[] args) throws IOException { try { AmazonPinpointSMSVoice client = AmazonPinpointSMSVoiceClientBuilder.standard() - .withRegion(region).build(); + .withRegion(region).build(); SendVoiceMessageRequest request = new SendVoiceMessageRequest() - .withCallerId(callerId) - .withDestinationPhoneNumber(destinationNumber) - .withOriginationPhoneNumber(originationNumber) - .withConfigurationSetName(configurationSet) - .withContent(new VoiceMessageContent() - .withSSMLMessage(new SSMLMessageType() - .withLanguageCode(languageCode) - .withVoiceId(voiceName) - .withText(ssmlMessage) - ) - ); + .withCallerId(callerId) + .withDestinationPhoneNumber(destinationNumber) + .withOriginationPhoneNumber(originationNumber) + .withConfigurationSetName(configurationSet) + .withContent(new VoiceMessageContent() + .withSSMLMessage(new SSMLMessageType() + .withLanguageCode(languageCode) + .withVoiceId(voiceName) + .withText(ssmlMessage))); client.sendVoiceMessage(request); System.out.println("The message was sent successfully."); } catch (Exception ex) { diff --git a/java/example_code/pinpoint/pinpoint_associate_endpoints_users.java b/java/example_code/pinpoint/pinpoint_associate_endpoints_users.java index 628f4fbd4e7..8b13d3009f4 100644 --- a/java/example_code/pinpoint/pinpoint_associate_endpoints_users.java +++ b/java/example_code/pinpoint/pinpoint_associate_endpoints_users.java @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[pinpoint_associate_endpoints_users demonstrates how to associate users with endpoints in Amazon Pinpoint.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Pinpoint] -// snippet-keyword:[Code Sample] -// snippet-keyword:[UpdateEndpoint] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2018-08-07] -// snippet-sourceauthor:[AWS] // snippet-start:[pinpoint.java.pinpoint_associate_endpoints_users.complete] import com.amazonaws.regions.Regions; @@ -37,47 +16,48 @@ public class AddExampleUser { - public static void main(String[] args) { + public static void main(String[] args) { - final String USAGE = "\n" + - "AddExampleUser - Adds a user definition to the specified Amazon Pinpoint endpoint." + - "Usage: AddExampleUser " + - "Where:\n" + - " endpointId - The ID of the endpoint to add the user to." + - " applicationId - The ID of the Amazon Pinpoint application that contains the endpoint."; + final String USAGE = "\n" + + "AddExampleUser - Adds a user definition to the specified Amazon Pinpoint endpoint." + + "Usage: AddExampleUser " + + "Where:\n" + + " endpointId - The ID of the endpoint to add the user to." + + " applicationId - The ID of the Amazon Pinpoint application that contains the endpoint."; - if (args.length < 1) { - System.out.println(USAGE); - System.exit(1); - } + if (args.length < 1) { + System.out.println(USAGE); + System.exit(1); + } - String endpointId = args[0]; - String applicationId = args[1]; + String endpointId = args[0]; + String applicationId = args[1]; - // Creates a new user definition. - EndpointUser wangXiulan = new EndpointUser().withUserId("example_user"); + // Creates a new user definition. + EndpointUser wangXiulan = new EndpointUser().withUserId("example_user"); - // Assigns custom user attributes. - wangXiulan.addUserAttributesEntry("name", Arrays.asList("Wang", "Xiulan")); - wangXiulan.addUserAttributesEntry("gender", Collections.singletonList("female")); - wangXiulan.addUserAttributesEntry("age", Collections.singletonList("39")); + // Assigns custom user attributes. + wangXiulan.addUserAttributesEntry("name", Arrays.asList("Wang", "Xiulan")); + wangXiulan.addUserAttributesEntry("gender", Collections.singletonList("female")); + wangXiulan.addUserAttributesEntry("age", Collections.singletonList("39")); - // Adds the user definition to the EndpointRequest that is passed to the Amazon Pinpoint client. - EndpointRequest wangXiulansIphone = new EndpointRequest() - .withUser(wangXiulan); + // Adds the user definition to the EndpointRequest that is passed to the Amazon + // Pinpoint client. + EndpointRequest wangXiulansIphone = new EndpointRequest() + .withUser(wangXiulan); - // Initializes the Amazon Pinpoint client. - AmazonPinpoint pinpointClient = AmazonPinpointClientBuilder.standard() - .withRegion(Regions.US_EAST_1).build(); + // Initializes the Amazon Pinpoint client. + AmazonPinpoint pinpointClient = AmazonPinpointClientBuilder.standard() + .withRegion(Regions.US_EAST_1).build(); - // Updates the specified endpoint with Amazon Pinpoint. - UpdateEndpointResult result = pinpointClient.updateEndpoint(new UpdateEndpointRequest() - .withEndpointRequest(wangXiulansIphone) - .withApplicationId(applicationId) - .withEndpointId(endpointId)); + // Updates the specified endpoint with Amazon Pinpoint. + UpdateEndpointResult result = pinpointClient.updateEndpoint(new UpdateEndpointRequest() + .withEndpointRequest(wangXiulansIphone) + .withApplicationId(applicationId) + .withEndpointId(endpointId)); - System.out.format("Update endpoint result: %s\n", result.getMessageBody().getMessage()); + System.out.format("Update endpoint result: %s\n", result.getMessageBody().getMessage()); - } + } } // snippet-end:[pinpoint.java.pinpoint_associate_endpoints_users.complete] diff --git a/java/example_code/pinpoint/pinpoint_create_campaign.java b/java/example_code/pinpoint/pinpoint_create_campaign.java index f7dc20a896a..83d4dee5107 100644 --- a/java/example_code/pinpoint/pinpoint_create_campaign.java +++ b/java/example_code/pinpoint/pinpoint_create_campaign.java @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[pinpoint_create_campaign demonstrates how to create and configure an Amazon Pinpoint campaign.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Pinpoint] -// snippet-keyword:[Code Sample] -// snippet-keyword:[CreateCampaign] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2018-08-07] -// snippet-sourceauthor:[AWS] // snippet-start:[pinpoint.java.pinpoint_create_campaign.complete] import com.amazonaws.services.pinpoint.AmazonPinpointClient; @@ -39,34 +18,34 @@ public class PinpointCampaignSample { - public CampaignResponse createCampaign(AmazonPinpointClient client, String appId, String segmentId) { - Schedule schedule = new Schedule() - .withStartTime("IMMEDIATE"); + public CampaignResponse createCampaign(AmazonPinpointClient client, String appId, String segmentId) { + Schedule schedule = new Schedule() + .withStartTime("IMMEDIATE"); - Message defaultMessage = new Message() - .withAction(Action.OPEN_APP) - .withBody("My message body.") - .withTitle("My message title."); + Message defaultMessage = new Message() + .withAction(Action.OPEN_APP) + .withBody("My message body.") + .withTitle("My message title."); - MessageConfiguration messageConfiguration = new MessageConfiguration() - .withDefaultMessage(defaultMessage); + MessageConfiguration messageConfiguration = new MessageConfiguration() + .withDefaultMessage(defaultMessage); - WriteCampaignRequest request = new WriteCampaignRequest() - .withDescription("My description.") - .withSchedule(schedule) - .withSegmentId(segmentId) - .withName("MyCampaign") - .withMessageConfiguration(messageConfiguration); + WriteCampaignRequest request = new WriteCampaignRequest() + .withDescription("My description.") + .withSchedule(schedule) + .withSegmentId(segmentId) + .withName("MyCampaign") + .withMessageConfiguration(messageConfiguration); - CreateCampaignRequest createCampaignRequest = new CreateCampaignRequest() - .withApplicationId(appId).withWriteCampaignRequest(request); + CreateCampaignRequest createCampaignRequest = new CreateCampaignRequest() + .withApplicationId(appId).withWriteCampaignRequest(request); - CreateCampaignResult result = client.createCampaign(createCampaignRequest); + CreateCampaignResult result = client.createCampaign(createCampaignRequest); - System.out.println("Campaign ID: " + result.getCampaignResponse().getId()); + System.out.println("Campaign ID: " + result.getCampaignResponse().getId()); - return result.getCampaignResponse(); - } + return result.getCampaignResponse(); + } } diff --git a/java/example_code/pinpoint/pinpoint_create_endpoint.java b/java/example_code/pinpoint/pinpoint_create_endpoint.java index b71b35a01f5..1877a7fa48a 100644 --- a/java/example_code/pinpoint/pinpoint_create_endpoint.java +++ b/java/example_code/pinpoint/pinpoint_create_endpoint.java @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[pinpoint_create_endpoint demonstrates how to create a new endpoint that includes standard and custom attributes and metrics.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Pinpoint] -// snippet-keyword:[Code Sample] -// snippet-keyword:[CreateEndpoint] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2018-08-07] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[pinpoint.java.pinpoint_create_endpoint.complete] import com.amazonaws.regions.Regions; @@ -33,70 +12,71 @@ public class AddExampleEndpoint { public static void main(String[] args) { - + final String USAGE = "\n" + - "AddExampleEndpoint - Adds an example endpoint to an Amazon Pinpoint application." + - "Usage: AddExampleEndpoint " + - "Where:\n" + - " applicationId - The ID of the Amazon Pinpoint application to add the example " + - "endpoint to."; - + "AddExampleEndpoint - Adds an example endpoint to an Amazon Pinpoint application." + + "Usage: AddExampleEndpoint " + + "Where:\n" + + " applicationId - The ID of the Amazon Pinpoint application to add the example " + + "endpoint to."; + if (args.length < 1) { - System.out.println(USAGE); - System.exit(1); + System.out.println(USAGE); + System.exit(1); } - + String applicationId = args[0]; - - // The device token assigned to the user's device by Apple Push Notification service (APNs). + + // The device token assigned to the user's device by Apple Push Notification + // service (APNs). String deviceToken = "1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p7q8r9s0t1u2v3w4x5y6z7a8b9c0d1e2f"; - + // Initializes an endpoint definition with channel type and address. EndpointRequest wangXiulansIphoneEndpoint = new EndpointRequest() - .withChannelType(ChannelType.APNS) - .withAddress(deviceToken); - + .withChannelType(ChannelType.APNS) + .withAddress(deviceToken); + // Adds custom attributes to the endpoint. wangXiulansIphoneEndpoint.addAttributesEntry("interests", Arrays.asList( - "technology", - "music", - "travel")); - + "technology", + "music", + "travel")); + // Adds custom metrics to the endpoint. wangXiulansIphoneEndpoint.addMetricsEntry("technology_interest_level", 9.0); wangXiulansIphoneEndpoint.addMetricsEntry("music_interest_level", 6.0); wangXiulansIphoneEndpoint.addMetricsEntry("travel_interest_level", 4.0); - + // Adds standard demographic attributes. wangXiulansIphoneEndpoint.setDemographic(new EndpointDemographic() - .withAppVersion("1.0") - .withMake("apple") - .withModel("iPhone") - .withModelVersion("8") - .withPlatform("ios") - .withPlatformVersion("11.3.1") - .withTimezone("America/Los_Angeles")); - + .withAppVersion("1.0") + .withMake("apple") + .withModel("iPhone") + .withModelVersion("8") + .withPlatform("ios") + .withPlatformVersion("11.3.1") + .withTimezone("America/Los_Angeles")); + // Adds standard location attributes. wangXiulansIphoneEndpoint.setLocation(new EndpointLocation() - .withCountry("US") - .withCity("Seattle") - .withPostalCode("98121") - .withLatitude(47.61) - .withLongitude(-122.33)); - + .withCountry("US") + .withCity("Seattle") + .withPostalCode("98121") + .withLatitude(47.61) + .withLongitude(-122.33)); + // Initializes the Amazon Pinpoint client. AmazonPinpoint pinpointClient = AmazonPinpointClientBuilder.standard() - .withRegion(Regions.US_EAST_1).build(); - + .withRegion(Regions.US_EAST_1).build(); + // Updates or creates the endpoint with Amazon Pinpoint. UpdateEndpointResult result = pinpointClient.updateEndpoint(new UpdateEndpointRequest() - .withApplicationId(applicationId) - .withEndpointId("example_endpoint") - .withEndpointRequest(wangXiulansIphoneEndpoint)); - + .withApplicationId(applicationId) + .withEndpointId("example_endpoint") + .withEndpointRequest(wangXiulansIphoneEndpoint)); + System.out.format("Update endpoint result: %s\n", result.getMessageBody().getMessage()); - + } } // snippet-end:[pinpoint.java.pinpoint_create_endpoint.complete] diff --git a/java/example_code/pinpoint/pinpoint_create_import_job.java b/java/example_code/pinpoint/pinpoint_create_import_job.java index 796ed56a5c6..dad6100a82c 100644 --- a/java/example_code/pinpoint/pinpoint_create_import_job.java +++ b/java/example_code/pinpoint/pinpoint_create_import_job.java @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[pinpoint_create_import_job demonstrates how to import a segment of customers using a source file stored in an Amazon S3 bucket.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Pinpoint] -// snippet-keyword:[Code Sample] -// snippet-keyword:[CreateImportJob] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2018-08-07] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[pinpoint.java.pinpoint_create_import_job.complete] package com.amazonaws.examples.pinpoint; @@ -50,20 +29,20 @@ public class ImportEndpoints { public static void main(String[] args) { final String USAGE = "\n" + - "ImportEndpoints - Adds endpoints to an Amazon Pinpoint application by: \n" + - "1.) Uploading the endpoint definitions to an Amazon S3 bucket. \n" + - "2.) Importing the endpoint definitions from the bucket to an Amazon Pinpoint " + + "ImportEndpoints - Adds endpoints to an Amazon Pinpoint application by: \n" + + "1.) Uploading the endpoint definitions to an Amazon S3 bucket. \n" + + "2.) Importing the endpoint definitions from the bucket to an Amazon Pinpoint " + "application.\n\n" + - "Usage: ImportEndpoints " + + "Usage: ImportEndpoints " + "\n\n" + - "Where:\n" + - " endpointsFileLocation - The relative location of the JSON file that contains the " + + "Where:\n" + + " endpointsFileLocation - The relative location of the JSON file that contains the " + "endpoint definitions.\n" + - " s3BucketName - The name of the Amazon S3 bucket to upload the JSON file to. If the " + + " s3BucketName - The name of the Amazon S3 bucket to upload the JSON file to. If the " + "bucket doesn't exist, a new bucket is created.\n" + - " iamImportRoleArn - The ARN of an IAM role that grants Amazon Pinpoint read " + + " iamImportRoleArn - The ARN of an IAM role that grants Amazon Pinpoint read " + "permissions to the S3 bucket.\n" + - " applicationId - The ID of the Amazon Pinpoint application to add the endpoints to."; + " applicationId - The ID of the Amazon Pinpoint application to add the endpoints to."; if (args.length < 1) { System.out.println(USAGE); @@ -112,7 +91,7 @@ private static void uploadToS3(File endpointsFile, String s3BucketName) { } private static void importToPinpoint(String endpointsFileName, String s3BucketName, - String iamImportRoleArn, String applicationId) { + String iamImportRoleArn, String applicationId) { // The S3 URL that Amazon Pinpoint requires to find the endpoints file. String s3Url = "s3://" + s3BucketName + "/imports/" + endpointsFileName; @@ -137,8 +116,7 @@ private static void importToPinpoint(String endpointsFileName, String s3BucketNa try { // Runs the import job with Amazon Pinpoint. - CreateImportJobResult importResult = - pinpointClient.createImportJob(createImportJobRequest); + CreateImportJobResult importResult = pinpointClient.createImportJob(createImportJobRequest); String jobId = importResult.getImportJobResponse().getId(); GetImportJobResult getImportJobResult = null; @@ -162,7 +140,8 @@ private static void importToPinpoint(String endpointsFileName, String s3BucketNa } // Checks for entries that failed to import. - // getFailures provides up to 100 of the first failed entries for the job, if any exist. + // getFailures provides up to 100 of the first failed entries for the job, if + // any exist. List failedEndpoints = getImportJobResult.getImportJobResponse().getFailures(); if (failedEndpoints != null) { System.out.println("Failed to import the following entries:"); diff --git a/java/example_code/pinpoint/pinpoint_create_segment.java b/java/example_code/pinpoint/pinpoint_create_segment.java index 16332f63360..26039b44dd6 100644 --- a/java/example_code/pinpoint/pinpoint_create_segment.java +++ b/java/example_code/pinpoint/pinpoint_create_segment.java @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[pinpoint_export_endpoints demonstrates how to create a segment that is based on data reported by an app.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Pinpoint] -// snippet-keyword:[Code Sample] -// snippet-keyword:[CreateSegment] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2018-08-07] -// snippet-sourceauthor:[AWS] // snippet-start:[pinpoint.java.pinpoint_create_segment.complete] import com.amazonaws.services.pinpoint.AmazonPinpointClient; @@ -42,37 +21,37 @@ public class PinpointSegmentSample { - public SegmentResponse createSegment(AmazonPinpointClient client, String appId) { - Map segmentAttributes = new HashMap<>(); - segmentAttributes.put("Team", new AttributeDimension().withAttributeType(AttributeType.INCLUSIVE).withValues("Lakers")); + public SegmentResponse createSegment(AmazonPinpointClient client, String appId) { + Map segmentAttributes = new HashMap<>(); + segmentAttributes.put("Team", new AttributeDimension().withAttributeType(AttributeType.INCLUSIVE) + .withValues("Lakers")); - SegmentBehaviors segmentBehaviors = new SegmentBehaviors(); - SegmentDemographics segmentDemographics = new SegmentDemographics(); - SegmentLocation segmentLocation = new SegmentLocation(); + SegmentBehaviors segmentBehaviors = new SegmentBehaviors(); + SegmentDemographics segmentDemographics = new SegmentDemographics(); + SegmentLocation segmentLocation = new SegmentLocation(); - RecencyDimension recencyDimension = new RecencyDimension(); - recencyDimension.withDuration("DAY_30").withRecencyType("ACTIVE"); - segmentBehaviors.setRecency(recencyDimension); + RecencyDimension recencyDimension = new RecencyDimension(); + recencyDimension.withDuration("DAY_30").withRecencyType("ACTIVE"); + segmentBehaviors.setRecency(recencyDimension); - SegmentDimensions dimensions = new SegmentDimensions() - .withAttributes(segmentAttributes) - .withBehavior(segmentBehaviors) - .withDemographic(segmentDemographics) - .withLocation(segmentLocation); + SegmentDimensions dimensions = new SegmentDimensions() + .withAttributes(segmentAttributes) + .withBehavior(segmentBehaviors) + .withDemographic(segmentDemographics) + .withLocation(segmentLocation); + WriteSegmentRequest writeSegmentRequest = new WriteSegmentRequest() + .withName("MySegment").withDimensions(dimensions); - WriteSegmentRequest writeSegmentRequest = new WriteSegmentRequest() - .withName("MySegment").withDimensions(dimensions); + CreateSegmentRequest createSegmentRequest = new CreateSegmentRequest() + .withApplicationId(appId).withWriteSegmentRequest(writeSegmentRequest); - CreateSegmentRequest createSegmentRequest = new CreateSegmentRequest() - .withApplicationId(appId).withWriteSegmentRequest(writeSegmentRequest); + CreateSegmentResult createSegmentResult = client.createSegment(createSegmentRequest); - CreateSegmentResult createSegmentResult = client.createSegment(createSegmentRequest); + System.out.println("Segment ID: " + createSegmentResult.getSegmentResponse().getId()); - System.out.println("Segment ID: " + createSegmentResult.getSegmentResponse().getId()); - - return createSegmentResult.getSegmentResponse(); - } + return createSegmentResult.getSegmentResponse(); + } } diff --git a/java/example_code/pinpoint/pinpoint_delete_endpoint.java b/java/example_code/pinpoint/pinpoint_delete_endpoint.java index d5f44849751..efaf5f69f31 100644 --- a/java/example_code/pinpoint/pinpoint_delete_endpoint.java +++ b/java/example_code/pinpoint/pinpoint_delete_endpoint.java @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[pinpoint_delete_endpoint demonstrates how to delete an existing endpoint in Amazon Pinpoint.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Pinpoint] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DeleteEndpoint] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2018-08-07] -// snippet-sourceauthor:[AWS] // snippet-start:[pinpoint.java.pinpoint_delete_endpoint.complete] import com.amazonaws.AmazonServiceException; @@ -57,9 +36,8 @@ public static void main(String[] args) { try { // Deletes each of the specified endpoints with the Amazon Pinpoint client. - for (String endpointId: endpointIds) { - DeleteEndpointResult result = - pinpointClient.deleteEndpoint(new DeleteEndpointRequest() + for (String endpointId : endpointIds) { + DeleteEndpointResult result = pinpointClient.deleteEndpoint(new DeleteEndpointRequest() .withEndpointId(endpointId) .withApplicationId(applicationId)); System.out.format("Deleted endpoint %s.\n", result.getEndpointResponse().getId()); diff --git a/java/example_code/pinpoint/pinpoint_export_endpoints.java b/java/example_code/pinpoint/pinpoint_export_endpoints.java index 71338262b4a..3fd0ba74cd1 100644 --- a/java/example_code/pinpoint/pinpoint_export_endpoints.java +++ b/java/example_code/pinpoint/pinpoint_export_endpoints.java @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[pinpoint_export_endpoints demonstrates how to export information about several existing endpoints to an Amazon S3 bucket that you specify.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Pinpoint] -// snippet-keyword:[Code Sample] -// snippet-keyword:[CreateExportJob] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2019-01-20] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[pinpoint.java.pinpoint_export_endpoints.complete] import com.amazonaws.AmazonServiceException; @@ -77,8 +56,7 @@ public static void main(String[] args) { String applicationId = args[3]; // Exports the endpoints to Amazon S3 and stores the keys of the new objects. - List objectKeys = - exportEndpointsToS3(s3BucketName, iamExportRoleArn, applicationId); + List objectKeys = exportEndpointsToS3(s3BucketName, iamExportRoleArn, applicationId); // Filters the keys to only those objects that have the endpoint definitions. // These objects have the .gz extension. @@ -92,12 +70,11 @@ public static void main(String[] args) { } public static List exportEndpointsToS3(String s3BucketName, String iamExportRoleArn, - String applicationId) { + String applicationId) { // The S3 path that Amazon Pinpoint exports the endpoints to. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH_mm:ss.SSS_z"); - String endpointsKeyPrefix = "exports/" + applicationId + "_" + dateFormat.format(new Date - ()); + String endpointsKeyPrefix = "exports/" + applicationId + "_" + dateFormat.format(new Date()); String s3UrlPrefix = "s3://" + s3BucketName + "/" + endpointsKeyPrefix + "/"; // Defines the export job that Amazon Pinpoint runs. @@ -119,8 +96,7 @@ public static List exportEndpointsToS3(String s3BucketName, String iamEx try { // Runs the export job with Amazon Pinpoint. - CreateExportJobResult exportResult = - pinpointClient.createExportJob(createExportJobRequest); + CreateExportJobResult exportResult = pinpointClient.createExportJob(createExportJobRequest); // Prints the export job status to the console while the job runs. String jobId = exportResult.getExportJobResponse().getId(); @@ -146,7 +122,7 @@ public static List exportEndpointsToS3(String s3BucketName, String iamEx } private static void printExportJobStatus(AmazonPinpoint pinpointClient, - String applicationId, String jobId) { + String applicationId, String jobId) { GetExportJobResult getExportJobResult; String jobStatus; @@ -170,7 +146,8 @@ private static void printExportJobStatus(AmazonPinpoint pinpointClient, } // Checks for entries that failed to import. - // getFailures provides up to 100 of the first failed entries for the job, if any exist. + // getFailures provides up to 100 of the first failed entries for the job, if + // any exist. List failedEndpoints = getExportJobResult.getExportJobResponse().getFailures(); if (failedEndpoints != null) { System.out.println("Failed to import the following entries:"); @@ -185,7 +162,7 @@ private static void printExportJobStatus(AmazonPinpoint pinpointClient, } public static void downloadFromS3(String s3BucketName, List objectKeys, - String downloadDirectory) { + String downloadDirectory) { // Initializes the Amazon S3 client. AmazonS3 s3Client = AmazonS3ClientBuilder.defaultClient(); @@ -215,7 +192,7 @@ private static void writeObjectToFile(Path filePath, S3Object object) { // Writes the contents of the S3 object to a file. File endpointsFile = new File(filePath.toAbsolutePath().toString()); try (FileOutputStream fos = new FileOutputStream(endpointsFile); - S3ObjectInputStream s3is = object.getObjectContent()) { + S3ObjectInputStream s3is = object.getObjectContent()) { byte[] read_buf = new byte[1024]; int read_len = 0; while ((read_len = s3is.read(read_buf)) > 0) { @@ -229,4 +206,3 @@ private static void writeObjectToFile(Path filePath, S3Object object) { } // snippet-end:[pinpoint.java.pinpoint_export_endpoints.complete] - diff --git a/java/example_code/pinpoint/pinpoint_import_segment.java b/java/example_code/pinpoint/pinpoint_import_segment.java index 93a16fb02c8..03a4b3ffba8 100644 --- a/java/example_code/pinpoint/pinpoint_import_segment.java +++ b/java/example_code/pinpoint/pinpoint_import_segment.java @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[pinpoint_import_segment demonstrates how to create a segment by importing information about the endpoints that belong to the segment.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Pinpoint] -// snippet-keyword:[Code Sample] -// snippet-keyword:[CreateImportJob] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2018-08-07] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[pinpoint.java.pinpoint_import_segment.complete] import com.amazonaws.AmazonServiceException; @@ -43,18 +22,21 @@ public class ImportSegment { public static void main(String[] args) { final String USAGE = "\n" + - "ImportSegment - Creates a segment by: \n" + - "1.) Uploading the endpoint definitions that belong to the segment to an Amazon S3 bucket. \n" + - "2.) Importing the endpoint definitions from the bucket to an Amazon Pinpoint application." + - " Amazon Pinpoint creates a segment that has the specified name.\n\n" + - "Usage: ImportSegment \n\n" + - "Where:\n" + - " endpointsFileLocation - The relative location of the JSON file that contains the endpoint definitions.\n" + - " s3BucketName - The name of the Amazon S3 bucket to upload the JSON file to. If the bucket doesn't " + - "exist, a new bucket is created.\n" + - " iamImportRoleArn - The ARN of an IAM role that grants Amazon Pinpoint read permissions so the S3 bucket.\n" + - " segmentName - The name for the segment that you are creating or updating." + - " applicationId - The ID of the Amazon Pinpoint application to add the endpoints to."; + "ImportSegment - Creates a segment by: \n" + + "1.) Uploading the endpoint definitions that belong to the segment to an Amazon S3 bucket. \n" + + "2.) Importing the endpoint definitions from the bucket to an Amazon Pinpoint application." + + " Amazon Pinpoint creates a segment that has the specified name.\n\n" + + "Usage: ImportSegment \n\n" + + + "Where:\n" + + " endpointsFileLocation - The relative location of the JSON file that contains the endpoint definitions.\n" + + + " s3BucketName - The name of the Amazon S3 bucket to upload the JSON file to. If the bucket doesn't " + + "exist, a new bucket is created.\n" + + " iamImportRoleArn - The ARN of an IAM role that grants Amazon Pinpoint read permissions so the S3 bucket.\n" + + + " segmentName - The name for the segment that you are creating or updating." + + " applicationId - The ID of the Amazon Pinpoint application to add the endpoints to."; if (args.length < 1) { System.out.println(USAGE); @@ -104,7 +86,7 @@ private static void uploadToS3(File endpointsFile, String s3BucketName) { } private static void importSegment(String endpointsFileName, String s3BucketName, String iamImportRoleArn, - String segmentName, String applicationId) { + String segmentName, String applicationId) { // The S3 URL that Amazon Pinpoint requires to find the endpoints file. String s3Url = "s3://" + s3BucketName + "/imports/" + endpointsFileName; diff --git a/java/example_code/pinpoint/pinpoint_list_endpoint_ids.java b/java/example_code/pinpoint/pinpoint_list_endpoint_ids.java index 58d033d855c..244e3f2c568 100644 --- a/java/example_code/pinpoint/pinpoint_list_endpoint_ids.java +++ b/java/example_code/pinpoint/pinpoint_list_endpoint_ids.java @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[pinpoint_list_endpoint_ids demonstrates how to produce a list of endpoint IDs that are associated with an Amazon Pinpoint project/application. This code example only works if you've already exported a list of endpoints by using the pinpoint_export_endpoints example.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Pinpoint] -// snippet-keyword:[Code Sample] -// snippet-keyword:[CreateExportJob] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2018-08-07] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[pinpoint.java.pinpoint_list_endpoint_ids.complete] import com.amazonaws.AmazonServiceException; @@ -76,8 +55,7 @@ public static void main(String[] args) { String iamExportRoleArn = args[2]; // Exports the endpoints to Amazon S3 and stores the keys of the new objects. - List objectKeys = - ExportEndpoints.exportEndpointsToS3(s3BucketName, iamExportRoleArn, applicationId); + List objectKeys = ExportEndpoints.exportEndpointsToS3(s3BucketName, iamExportRoleArn, applicationId); // Filters the keys to only those objects that have the endpoint definitions. // These objects have the .gz extension. @@ -130,11 +108,9 @@ private static List getEndpointIdsFromFile(S3Object endpointsFile) { .create(); // Reads each endpoint entry in the file and adds the ID to the list. - try (GZIPInputStream gzipInputStream = - new GZIPInputStream(endpointsFile.getObjectContent()); - BufferedReader reader = - new BufferedReader(new InputStreamReader( - gzipInputStream, "UTF-8"))) { + try (GZIPInputStream gzipInputStream = new GZIPInputStream(endpointsFile.getObjectContent()); + BufferedReader reader = new BufferedReader(new InputStreamReader( + gzipInputStream, "UTF-8"))) { String endpointString; while ((endpointString = reader.readLine()) != null) { JsonObject endpointJson = gson.fromJson(endpointString, JsonObject.class); diff --git a/java/example_code/pinpoint/pinpoint_lookup_endpoint.java b/java/example_code/pinpoint/pinpoint_lookup_endpoint.java index 8177999fb18..4f771a132b8 100644 --- a/java/example_code/pinpoint/pinpoint_lookup_endpoint.java +++ b/java/example_code/pinpoint/pinpoint_lookup_endpoint.java @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[pinpoint_lookup_endpoint demonstrates how to display information about an existing endpoint in Amazon Pinpoint.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Pinpoint] -// snippet-keyword:[Code Sample] -// snippet-keyword:[GetEndpoint] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2018-08-07] -// snippet-sourceauthor:[AWS] // snippet-start:[pinpoint.java.pinpoint_lookup_endpoint.complete] import com.amazonaws.regions.Regions; @@ -36,47 +15,47 @@ public class LookUpEndpoint { - public static void main(String[] args) { + public static void main(String[] args) { - final String USAGE = "\n" + - "LookUpEndpoint - Prints the definition of the endpoint that has the specified ID." + - "Usage: LookUpEndpoint \n\n" + + final String USAGE = "\n" + + "LookUpEndpoint - Prints the definition of the endpoint that has the specified ID." + + "Usage: LookUpEndpoint \n\n" + - "Where:\n" + - " applicationId - The ID of the Amazon Pinpoint application that has the " + - "endpoint." + - " endpointId - The ID of the endpoint "; + "Where:\n" + + " applicationId - The ID of the Amazon Pinpoint application that has the " + + "endpoint." + + " endpointId - The ID of the endpoint "; - if (args.length < 1) { - System.out.println(USAGE); - System.exit(1); - } + if (args.length < 1) { + System.out.println(USAGE); + System.exit(1); + } - String applicationId = args[0]; - String endpointId = args[1]; + String applicationId = args[0]; + String endpointId = args[1]; - // Specifies the endpoint that the Amazon Pinpoint client looks up. - GetEndpointRequest request = new GetEndpointRequest() - .withEndpointId(endpointId) - .withApplicationId(applicationId); + // Specifies the endpoint that the Amazon Pinpoint client looks up. + GetEndpointRequest request = new GetEndpointRequest() + .withEndpointId(endpointId) + .withApplicationId(applicationId); - // Initializes the Amazon Pinpoint client. - AmazonPinpoint pinpointClient = AmazonPinpointClientBuilder.standard() - .withRegion(Regions.US_EAST_1).build(); + // Initializes the Amazon Pinpoint client. + AmazonPinpoint pinpointClient = AmazonPinpointClientBuilder.standard() + .withRegion(Regions.US_EAST_1).build(); - // Uses the Amazon Pinpoint client to get the endpoint definition. - GetEndpointResult result = pinpointClient.getEndpoint(request); - EndpointResponse endpoint = result.getEndpointResponse(); + // Uses the Amazon Pinpoint client to get the endpoint definition. + GetEndpointResult result = pinpointClient.getEndpoint(request); + EndpointResponse endpoint = result.getEndpointResponse(); - // Uses the Google Gson library to pretty print the endpoint JSON. - Gson gson = new GsonBuilder() - .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE) - .setPrettyPrinting() - .create(); - String endpointJson = gson.toJson(endpoint); + // Uses the Google Gson library to pretty print the endpoint JSON. + Gson gson = new GsonBuilder() + .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE) + .setPrettyPrinting() + .create(); + String endpointJson = gson.toJson(endpoint); - System.out.println(endpointJson); - } + System.out.println(endpointJson); + } } // snippet-end:[pinpoint.java.pinpoint_lookup_endpoint.complete] diff --git a/java/example_code/pinpoint/pinpoint_send_email_message_api.java b/java/example_code/pinpoint/pinpoint_send_email_message_api.java index 8686e44065d..ae54893ba76 100644 --- a/java/example_code/pinpoint/pinpoint_send_email_message_api.java +++ b/java/example_code/pinpoint/pinpoint_send_email_message_api.java @@ -1,30 +1,10 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[pinpoint_send_email_message_api demonstrates how to send a transactional email by using the SendMessages operation in the Amazon Pinpoint API.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Pinpoint] -// snippet-keyword:[Code Sample] -// snippet-keyword:[SendMessages] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2019-01-20] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[pinpoint.java.pinpoint_send_email_message_api.complete] package com.amazonaws.samples; + import java.io.IOException; import java.util.HashMap; import java.util.Map; @@ -42,88 +22,80 @@ public class SendMessages { - // The AWS Region that you want to use to send the message. For a list of - // AWS Regions where the Amazon Pinpoint API is available, see - // https://docs.aws.amazon.com/pinpoint/latest/apireference/ - public static String region = "us-west-2"; - - // The "From" address. This address has to be verified in Amazon - // Pinpoint in the region you're using to send email. - public static String senderAddress = "sender@example.com"; - - // The address on the "To" line. If your Amazon Pinpoint account is in - // the sandbox, this address also has to be verified. - public static String toAddress = "recipient@example.com"; - - // The Amazon Pinpoint project/application ID to use when you send this message. - // Make sure that the SMS channel is enabled for the project or application - // that you choose. - public static String appId = "ce796be37f32f178af652b26eexample"; - - // The subject line of the email. - public static String subject = "Amazon Pinpoint test"; - - // The email body for recipients with non-HTML email clients. - static final String textBody = "Amazon Pinpoint Test (SDK for Java 2.x)\r\n" - + "---------------------------------\r\n" - + "This email was sent using the Amazon Pinpoint " - + "API using the AWS SDK for Java 2.x."; - - // The body of the email for recipients whose email clients support - // HTML content. - static final String htmlBody = "

Amazon Pinpoint test (AWS SDK for Java 2.x)

" - + "

This email was sent through the " - + "Amazon Pinpoint Email API using the " - + "AWS SDK for Java 2.x"; - - // The character encoding the you want to use for the subject line and - // message body of the email. - public static String charset = "UTF-8"; - - public static void main(String[] args) throws IOException { - - try { - Map addressMap = - new HashMap(); - - addressMap.put(toAddress, new AddressConfiguration() - .withChannelType(ChannelType.EMAIL)); - - AmazonPinpoint client = AmazonPinpointClientBuilder.standard() - .withRegion(region).build(); - - SendMessagesRequest request = (new SendMessagesRequest() - .withApplicationId(appId) - .withMessageRequest(new MessageRequest() - .withAddresses(addressMap) - .withMessageConfiguration(new DirectMessageConfiguration() - .withEmailMessage(new EmailMessage() - .withSimpleEmail(new SimpleEmail() - .withHtmlPart(new SimpleEmailPart() - .withCharset(charset) - .withData(htmlBody) - ) - .withTextPart(new SimpleEmailPart() - .withCharset(charset) - .withData(textBody) - ) - .withSubject(new SimpleEmailPart() - .withCharset(charset) - .withData(subject) - ) - ) - ) - ) - ) - ); - System.out.println("Sending message..."); - client.sendMessages(request); - System.out.println("Message sent!"); - } catch (Exception ex) { - System.out.println("The message wasn't sent. Error message: " - + ex.getMessage()); + // The AWS Region that you want to use to send the message. For a list of + // AWS Regions where the Amazon Pinpoint API is available, see + // https://docs.aws.amazon.com/pinpoint/latest/apireference/ + public static String region = "us-west-2"; + + // The "From" address. This address has to be verified in Amazon + // Pinpoint in the region you're using to send email. + public static String senderAddress = "sender@example.com"; + + // The address on the "To" line. If your Amazon Pinpoint account is in + // the sandbox, this address also has to be verified. + public static String toAddress = "recipient@example.com"; + + // The Amazon Pinpoint project/application ID to use when you send this message. + // Make sure that the SMS channel is enabled for the project or application + // that you choose. + public static String appId = "ce796be37f32f178af652b26eexample"; + + // The subject line of the email. + public static String subject = "Amazon Pinpoint test"; + + // The email body for recipients with non-HTML email clients. + static final String textBody = "Amazon Pinpoint Test (SDK for Java 2.x)\r\n" + + "---------------------------------\r\n" + + "This email was sent using the Amazon Pinpoint " + + "API using the AWS SDK for Java 2.x."; + + // The body of the email for recipients whose email clients support + // HTML content. + static final String htmlBody = "

Amazon Pinpoint test (AWS SDK for Java 2.x)

" + + "

This email was sent through the " + + "Amazon Pinpoint Email API using the " + + "AWS SDK for Java 2.x"; + + // The character encoding the you want to use for the subject line and + // message body of the email. + public static String charset = "UTF-8"; + + public static void main(String[] args) throws IOException { + + try { + Map addressMap = new HashMap(); + + addressMap.put(toAddress, new AddressConfiguration() + .withChannelType(ChannelType.EMAIL)); + + AmazonPinpoint client = AmazonPinpointClientBuilder.standard() + .withRegion(region).build(); + + SendMessagesRequest request = (new SendMessagesRequest() + .withApplicationId(appId) + .withMessageRequest(new MessageRequest() + .withAddresses(addressMap) + .withMessageConfiguration(new DirectMessageConfiguration() + .withEmailMessage(new EmailMessage() + .withSimpleEmail( + new SimpleEmail() + .withHtmlPart(new SimpleEmailPart() + .withCharset(charset) + .withData(htmlBody)) + .withTextPart(new SimpleEmailPart() + .withCharset(charset) + .withData(textBody)) + .withSubject(new SimpleEmailPart() + .withCharset(charset) + .withData(subject))))))); + System.out.println("Sending message..."); + client.sendMessages(request); + System.out.println("Message sent!"); + } catch (Exception ex) { + System.out.println("The message wasn't sent. Error message: " + + ex.getMessage()); + } } - } } // snippet-end:[pinpoint.java.pinpoint_send_email_message_api.complete] diff --git a/java/example_code/pinpoint/pinpoint_send_email_smtp.java b/java/example_code/pinpoint/pinpoint_send_email_smtp.java index b482c282b85..f8e3c191fcb 100644 --- a/java/example_code/pinpoint/pinpoint_send_email_smtp.java +++ b/java/example_code/pinpoint/pinpoint_send_email_smtp.java @@ -1,26 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[pinpoint_send_email_smtp demonstrates how to send a transactional email by using the Amazon Pinpoint SMTP interface.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Pinpoint] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2019-01-20] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[pinpoint.java.pinpoint_send_email_smtp.complete] import java.util.Properties; @@ -43,7 +23,7 @@ public class SendEmail { // Replace sender@example.com with your "From" address. // This address must be verified with Amazon Pinpoint. - static final String senderName= "Mary Major"; + static final String senderName = "Mary Major"; static final String senderAddress = "sender@example.com"; // Replace recipient@example.com with a "To" address. If your account @@ -72,12 +52,11 @@ public class SendEmail { // The body of the email for recipients whose email clients don't // support HTML content. static final String htmlBody = String.join( - System.getProperty("line.separator"), - "

Amazon Pinpoint SMTP Email Test

", - "

This email was sent with Amazon Pinpoint using the ", - "Javamail Package", - " for Java." - ); + System.getProperty("line.separator"), + "

Amazon Pinpoint SMTP Email Test

", + "

This email was sent with Amazon Pinpoint using the ", + "Javamail Package", + " for Java."); // The message tags that you want to apply to the email. static final String tag0 = "key0=value0"; @@ -86,24 +65,25 @@ public class SendEmail { public static void main(String[] args) throws Exception { // Create a Properties object to contain connection configuration information. - Properties props = System.getProperties(); - props.put("mail.transport.protocol", "smtp"); - props.put("mail.smtp.port", port); - props.put("mail.smtp.starttls.enable", "true"); - props.put("mail.smtp.auth", "true"); + Properties props = System.getProperties(); + props.put("mail.transport.protocol", "smtp"); + props.put("mail.smtp.port", port); + props.put("mail.smtp.starttls.enable", "true"); + props.put("mail.smtp.auth", "true"); - // Create a Session object to represent a mail session with the specified properties. - Session session = Session.getDefaultInstance(props); + // Create a Session object to represent a mail session with the specified + // properties. + Session session = Session.getDefaultInstance(props); // Create a message with the specified information. MimeMessage msg = new MimeMessage(session); - msg.setFrom(new InternetAddress(senderAddress,senderName)); + msg.setFrom(new InternetAddress(senderAddress, senderName)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddresses)); msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccAddresses)); msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bccAddresses)); msg.setSubject(subject); - msg.setContent(htmlBody,"text/html"); + msg.setContent(htmlBody, "text/html"); // Add headers for configuration set and message tags to the message. msg.setHeader("X-SES-CONFIGURATION-SET", configurationSet); @@ -117,18 +97,17 @@ public static void main(String[] args) throws Exception { try { System.out.println("Sending..."); - // Connect to Amazon Pinpoint using the SMTP username and password you specified above. + // Connect to Amazon Pinpoint using the SMTP username and password you specified + // above. transport.connect(smtpEndpoint, smtpUsername, smtpPassword); // Send the email. transport.sendMessage(msg, msg.getAllRecipients()); System.out.println("Email sent!"); - } - catch (Exception ex) { + } catch (Exception ex) { System.out.println("The email wasn't sent. Error message: " - + ex.getMessage()); - } - finally { + + ex.getMessage()); + } finally { // Close the connection to the SMTP server. transport.close(); } diff --git a/java/example_code/pinpoint/pinpoint_send_sms_message_api.java b/java/example_code/pinpoint/pinpoint_send_sms_message_api.java index adbcaa3f295..ae07ae0c5a7 100644 --- a/java/example_code/pinpoint/pinpoint_send_sms_message_api.java +++ b/java/example_code/pinpoint/pinpoint_send_sms_message_api.java @@ -1,30 +1,10 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[pinpoint_send_sms_message_api demonstrates how send a transactional SMS message by using the SendMessages operation in the Amazon Pinpoint API.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Pinpoint] -// snippet-keyword:[Code Sample] -// snippet-keyword:[SendMessages] -// snippet-sourcetype:[snippet] -// snippet-sourcedate:[2019-01-20] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[pinpoint.java.pinpoint_send_sms_message_api.complete] package com.amazonaws.samples; + import java.io.IOException; import java.util.HashMap; import java.util.Map; @@ -40,77 +20,74 @@ public class SendMessage { - // The AWS Region that you want to use to send the message. For a list of - // AWS Regions where the Amazon Pinpoint API is available, see - // https://docs.aws.amazon.com/pinpoint/latest/apireference/ - public static String region = "us-east-1"; - - // The phone number or short code to send the message from. The phone number - // or short code that you specify has to be associated with your Amazon Pinpoint - // account. For best results, specify long codes in E.164 format. - public static String originationNumber = "+12065550199"; - - // The recipient's phone number. For best results, you should specify the - // phone number in E.164 format. - public static String destinationNumber = "+14255550142"; - - // The content of the SMS message. - public static String message = "This message was sent through Amazon Pinpoint " - + "using the AWS SDK for Java. Reply STOP to " - + "opt out."; - - // The Pinpoint project/application ID to use when you send this message. - // Make sure that the SMS channel is enabled for the project or application - // that you choose. - public static String appId = "ce796be37f32f178af652b26eexample"; - - // The type of SMS message that you want to send. If you plan to send - // time-sensitive content, specify TRANSACTIONAL. If you plan to send - // marketing-related content, specify PROMOTIONAL. - public static String messageType = "TRANSACTIONAL"; - - // The registered keyword associated with the originating short code. - public static String registeredKeyword = "myKeyword"; - - // The sender ID to use when sending the message. Support for sender ID - // varies by country or region. For more information, see - // https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-countries.html - public static String senderId = "MySenderID"; - - public static void main(String[] args) throws IOException { - - try { - Map addressMap = - new HashMap(); - - addressMap.put(destinationNumber, new AddressConfiguration() - .withChannelType(ChannelType.SMS)); - - AmazonPinpoint client = AmazonPinpointClientBuilder.standard() - .withRegion(region).build(); - - SendMessagesRequest request = new SendMessagesRequest() - .withApplicationId(appId) - .withMessageRequest(new MessageRequest() - .withAddresses(addressMap) - .withMessageConfiguration(new DirectMessageConfiguration() - .withSMSMessage(new SMSMessage() - .withBody(message) - .withMessageType(messageType) - .withOriginationNumber(originationNumber) - .withSenderId(senderId) - .withKeyword(registeredKeyword) - ) - ) - ); - System.out.println("Sending message..."); - client.sendMessages(request); - System.out.println("Message sent!"); - } catch (Exception ex) { - System.out.println("The message wasn't sent. Error message: " - + ex.getMessage()); + // The AWS Region that you want to use to send the message. For a list of + // AWS Regions where the Amazon Pinpoint API is available, see + // https://docs.aws.amazon.com/pinpoint/latest/apireference/ + public static String region = "us-east-1"; + + // The phone number or short code to send the message from. The phone number + // or short code that you specify has to be associated with your Amazon Pinpoint + // account. For best results, specify long codes in E.164 format. + public static String originationNumber = "+12065550199"; + + // The recipient's phone number. For best results, you should specify the + // phone number in E.164 format. + public static String destinationNumber = "+14255550142"; + + // The content of the SMS message. + public static String message = "This message was sent through Amazon Pinpoint " + + "using the AWS SDK for Java. Reply STOP to " + + "opt out."; + + // The Pinpoint project/application ID to use when you send this message. + // Make sure that the SMS channel is enabled for the project or application + // that you choose. + public static String appId = "ce796be37f32f178af652b26eexample"; + + // The type of SMS message that you want to send. If you plan to send + // time-sensitive content, specify TRANSACTIONAL. If you plan to send + // marketing-related content, specify PROMOTIONAL. + public static String messageType = "TRANSACTIONAL"; + + // The registered keyword associated with the originating short code. + public static String registeredKeyword = "myKeyword"; + + // The sender ID to use when sending the message. Support for sender ID + // varies by country or region. For more information, see + // https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-countries.html + public static String senderId = "MySenderID"; + + public static void main(String[] args) throws IOException { + + try { + Map addressMap = new HashMap(); + + addressMap.put(destinationNumber, new AddressConfiguration() + .withChannelType(ChannelType.SMS)); + + AmazonPinpoint client = AmazonPinpointClientBuilder.standard() + .withRegion(region).build(); + + SendMessagesRequest request = new SendMessagesRequest() + .withApplicationId(appId) + .withMessageRequest(new MessageRequest() + .withAddresses(addressMap) + .withMessageConfiguration(new DirectMessageConfiguration() + .withSMSMessage(new SMSMessage() + .withBody(message) + .withMessageType(messageType) + .withOriginationNumber( + originationNumber) + .withSenderId(senderId) + .withKeyword(registeredKeyword)))); + System.out.println("Sending message..."); + client.sendMessages(request); + System.out.println("Message sent!"); + } catch (Exception ex) { + System.out.println("The message wasn't sent. Error message: " + + ex.getMessage()); + } } - } } // snippet-end:[pinpoint.java.pinpoint_send_sms_message_api.complete] diff --git a/java/example_code/pinpoint/pinpoint_update_endpoints_batch.java b/java/example_code/pinpoint/pinpoint_update_endpoints_batch.java index ee4e3fa6e8c..863960ca627 100644 --- a/java/example_code/pinpoint/pinpoint_update_endpoints_batch.java +++ b/java/example_code/pinpoint/pinpoint_update_endpoints_batch.java @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[pinpoint_update_endpoints_batch demonstrates how to update several existing endpoints in a single call to the API.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Pinpoint] -// snippet-keyword:[Code Sample] -// snippet-keyword:[UpdateEndpointsBatch] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-08-07] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[pinpoint.java.pinpoint_update_endpoints_batch.complete] import com.amazonaws.regions.Regions; @@ -38,94 +17,91 @@ public class AddExampleEndpoints { - public static void main(String[] args) { - - final String USAGE = "\n" + - "AddExampleEndpoints - Adds example endpoints to an Amazon Pinpoint application." + - "Usage: AddExampleEndpoints " + - "Where:\n" + - " applicationId - The ID of the Amazon Pinpoint application to add the example endpoints to."; + public static void main(String[] args) { - if (args.length < 1) { - System.out.println(USAGE); - System.exit(1); - } + final String USAGE = "\n" + + "AddExampleEndpoints - Adds example endpoints to an Amazon Pinpoint application." + + "Usage: AddExampleEndpoints " + + "Where:\n" + + " applicationId - The ID of the Amazon Pinpoint application to add the example endpoints to."; + if (args.length < 1) { + System.out.println(USAGE); + System.exit(1); + } - String applicationId = args[0]; + String applicationId = args[0]; - // Initializes an endpoint definition with channel type, address, and ID. - EndpointBatchItem richardRoesEmailEndpoint = new EndpointBatchItem() - .withChannelType(ChannelType.EMAIL) - .withAddress("richard_roe@example.com") - .withId("example_endpoint_1"); + // Initializes an endpoint definition with channel type, address, and ID. + EndpointBatchItem richardRoesEmailEndpoint = new EndpointBatchItem() + .withChannelType(ChannelType.EMAIL) + .withAddress("richard_roe@example.com") + .withId("example_endpoint_1"); - // Adds custom attributes to the endpoint. - richardRoesEmailEndpoint.addAttributesEntry("interests", Arrays.asList( - "music", - "books")); + // Adds custom attributes to the endpoint. + richardRoesEmailEndpoint.addAttributesEntry("interests", Arrays.asList( + "music", + "books")); - // Adds custom metrics to the endpoint. - richardRoesEmailEndpoint.addMetricsEntry("music_interest_level", 3.0); - richardRoesEmailEndpoint.addMetricsEntry("books_interest_level", 7.0); + // Adds custom metrics to the endpoint. + richardRoesEmailEndpoint.addMetricsEntry("music_interest_level", 3.0); + richardRoesEmailEndpoint.addMetricsEntry("books_interest_level", 7.0); - // Initializes a user definition with a user ID. - EndpointUser richardRoe = new EndpointUser().withUserId("example_user_1"); + // Initializes a user definition with a user ID. + EndpointUser richardRoe = new EndpointUser().withUserId("example_user_1"); - // Adds custom user attributes. - richardRoe.addUserAttributesEntry("name", Arrays.asList("Richard", "Roe")); + // Adds custom user attributes. + richardRoe.addUserAttributesEntry("name", Arrays.asList("Richard", "Roe")); - // Adds the user definition to the endpoint. - richardRoesEmailEndpoint.setUser(richardRoe); + // Adds the user definition to the endpoint. + richardRoesEmailEndpoint.setUser(richardRoe); - // Initializes an endpoint definition with channel type, address, and ID. - EndpointBatchItem maryMajorsSmsEndpoint = new EndpointBatchItem() - .withChannelType(ChannelType.SMS) - .withAddress("+16145550100") - .withId("example_endpoint_2"); + // Initializes an endpoint definition with channel type, address, and ID. + EndpointBatchItem maryMajorsSmsEndpoint = new EndpointBatchItem() + .withChannelType(ChannelType.SMS) + .withAddress("+16145550100") + .withId("example_endpoint_2"); - // Adds custom attributes to the endpoint. - maryMajorsSmsEndpoint.addAttributesEntry("interests", Arrays.asList( - "cooking", - "politics", - "finance")); + // Adds custom attributes to the endpoint. + maryMajorsSmsEndpoint.addAttributesEntry("interests", Arrays.asList( + "cooking", + "politics", + "finance")); - // Adds custom metrics to the endpoint. - maryMajorsSmsEndpoint.addMetricsEntry("cooking_interest_level", 5.0); - maryMajorsSmsEndpoint.addMetricsEntry("politics_interest_level", 8.0); - maryMajorsSmsEndpoint.addMetricsEntry("finance_interest_level", 4.0); + // Adds custom metrics to the endpoint. + maryMajorsSmsEndpoint.addMetricsEntry("cooking_interest_level", 5.0); + maryMajorsSmsEndpoint.addMetricsEntry("politics_interest_level", 8.0); + maryMajorsSmsEndpoint.addMetricsEntry("finance_interest_level", 4.0); - // Initializes a user definition with a user ID. - EndpointUser maryMajor = new EndpointUser().withUserId("example_user_2"); + // Initializes a user definition with a user ID. + EndpointUser maryMajor = new EndpointUser().withUserId("example_user_2"); - // Adds custom user attributes. - maryMajor.addUserAttributesEntry("name", Arrays.asList("Mary", "Major")); + // Adds custom user attributes. + maryMajor.addUserAttributesEntry("name", Arrays.asList("Mary", "Major")); - // Adds the user definition to the endpoint. - maryMajorsSmsEndpoint.setUser(maryMajor); + // Adds the user definition to the endpoint. + maryMajorsSmsEndpoint.setUser(maryMajor); - // Adds multiple endpoint definitions to a single request object. - EndpointBatchRequest endpointList = new EndpointBatchRequest() - .withItem(richardRoesEmailEndpoint) - .withItem(maryMajorsSmsEndpoint); + // Adds multiple endpoint definitions to a single request object. + EndpointBatchRequest endpointList = new EndpointBatchRequest() + .withItem(richardRoesEmailEndpoint) + .withItem(maryMajorsSmsEndpoint); - // Initializes the Amazon Pinpoint client. - AmazonPinpoint pinpointClient = AmazonPinpointClientBuilder.standard() - .withRegion(Regions.US_EAST_1).build(); + // Initializes the Amazon Pinpoint client. + AmazonPinpoint pinpointClient = AmazonPinpointClientBuilder.standard() + .withRegion(Regions.US_EAST_1).build(); - // Updates or creates the endpoints with Amazon Pinpoint. - UpdateEndpointsBatchResult result = pinpointClient.updateEndpointsBatch( - new UpdateEndpointsBatchRequest() - .withApplicationId(applicationId) - .withEndpointBatchRequest(endpointList)); + // Updates or creates the endpoints with Amazon Pinpoint. + UpdateEndpointsBatchResult result = pinpointClient.updateEndpointsBatch( + new UpdateEndpointsBatchRequest() + .withApplicationId(applicationId) + .withEndpointBatchRequest(endpointList)); - System.out.format("Update endpoints batch result: %s\n", - result.getMessageBody().getMessage()); + System.out.format("Update endpoints batch result: %s\n", + result.getMessageBody().getMessage()); - } + } } // snippet-end:[pinpoint.java.pinpoint_update_endpoints_batch.complete] - - diff --git a/java/example_code/pinpoint/run_example.sh b/java/example_code/pinpoint/run_example.sh index 010f20aecf7..7f103e63d48 100755 --- a/java/example_code/pinpoint/run_example.sh +++ b/java/example_code/pinpoint/run_example.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 if [[ -z $* ]] ; then echo 'Supply the name of one of the example classes as an argument.' echo 'If there are arguments to the class, put them in quotes after the class name.' diff --git a/java/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateApp.java b/java/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateApp.java index 110957f14d4..2a45fa9b1a7 100644 --- a/java/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateApp.java +++ b/java/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateApp.java @@ -1,25 +1,5 @@ -//snippet-sourcedescription:[CreateApp.java demonstrates how to create an application in the Pinpoint dashboard.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[mobiletargeting] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; import com.amazonaws.services.pinpoint.AmazonPinpoint; @@ -31,7 +11,7 @@ public class CreateApp { - public static void main(String[] args) { + public static void main(String[] args) { final String USAGE = "\n" + "CreateApp - create an application in pinpoint dashboard\n\n" + "Usage: CreateApp \n\n" + @@ -47,17 +27,17 @@ public static void main(String[] args) { System.out.println("Creating an application with name: " + appName); - AmazonPinpoint pinpoint = AmazonPinpointClientBuilder.standard().withRegion(Regions.US_EAST_1).build(); + AmazonPinpoint pinpoint = AmazonPinpointClientBuilder.standard().withRegion(Regions.US_EAST_1).build(); - CreateApplicationRequest appRequest = new CreateApplicationRequest() - .withName(appName); + CreateApplicationRequest appRequest = new CreateApplicationRequest() + .withName(appName); - CreateAppRequest request = new CreateAppRequest(); - request.withCreateApplicationRequest(appRequest); - CreateAppResult result = pinpoint.createApp(request); + CreateAppRequest request = new CreateAppRequest(); + request.withCreateApplicationRequest(appRequest); + CreateAppResult result = pinpoint.createApp(request); - String appID = result.getApplicationResponse().getId(); - System.out.println("Application " + appName + " has been created."); - System.out.println("App ID is: " + appID); - } + String appID = result.getApplicationResponse().getId(); + System.out.println("Application " + appName + " has been created."); + System.out.println("App ID is: " + appID); + } } diff --git a/java/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateCampaign.java b/java/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateCampaign.java index 91e2d13533a..fd6328e75be 100644 --- a/java/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateCampaign.java +++ b/java/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateCampaign.java @@ -1,25 +1,5 @@ -//snippet-sourcedescription:[CreateCampaign.java demonstrates how to create a campaign for an application in Pinpoint.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[mobiletargeting] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; import com.amazonaws.regions.Regions; @@ -36,53 +16,53 @@ public class CreateCampaign { - public static void main(String[] args) { - final String USAGE = "\n" + - "CreateCampaign - create a campaign for an application in pinpoint\n\n" + - "Usage: CreateCampaign \n\n" + - "Where:\n" + - " appId - the ID of the application to create the campaign in.\n\n" + - " segmentId - the ID of the segment to create the campaign from.\n\n"; + public static void main(String[] args) { + final String USAGE = "\n" + + "CreateCampaign - create a campaign for an application in pinpoint\n\n" + + "Usage: CreateCampaign \n\n" + + "Where:\n" + + " appId - the ID of the application to create the campaign in.\n\n" + + " segmentId - the ID of the segment to create the campaign from.\n\n"; - if (args.length < 1) { - System.out.println(USAGE); - System.exit(1); - } - String appId = args[0]; - String segmentId = args[1]; + if (args.length < 1) { + System.out.println(USAGE); + System.exit(1); + } + String appId = args[0]; + String segmentId = args[1]; - AmazonPinpoint pinpoint = AmazonPinpointClientBuilder.standard().withRegion(Regions.US_EAST_1).build(); - CampaignResponse result = createCampaign(pinpoint, appId, segmentId); - System.out.println("Campaign " + result.getName() + " created."); - System.out.println(result.getDescription()); - } + AmazonPinpoint pinpoint = AmazonPinpointClientBuilder.standard().withRegion(Regions.US_EAST_1).build(); + CampaignResponse result = createCampaign(pinpoint, appId, segmentId); + System.out.println("Campaign " + result.getName() + " created."); + System.out.println(result.getDescription()); + } - public static CampaignResponse createCampaign(AmazonPinpoint client, String appId, String segmentId) { - Schedule schedule = new Schedule() - .withStartTime("IMMEDIATE"); + public static CampaignResponse createCampaign(AmazonPinpoint client, String appId, String segmentId) { + Schedule schedule = new Schedule() + .withStartTime("IMMEDIATE"); - Message defaultMessage = new Message() - .withAction(Action.OPEN_APP) - .withBody("My message body.") - .withTitle("My message title."); + Message defaultMessage = new Message() + .withAction(Action.OPEN_APP) + .withBody("My message body.") + .withTitle("My message title."); - MessageConfiguration messageConfiguration = new MessageConfiguration() - .withDefaultMessage(defaultMessage); + MessageConfiguration messageConfiguration = new MessageConfiguration() + .withDefaultMessage(defaultMessage); - WriteCampaignRequest request = new WriteCampaignRequest() - .withDescription("My description.") - .withSchedule(schedule) - .withSegmentId(segmentId) - .withName("MyCampaign") - .withMessageConfiguration(messageConfiguration); + WriteCampaignRequest request = new WriteCampaignRequest() + .withDescription("My description.") + .withSchedule(schedule) + .withSegmentId(segmentId) + .withName("MyCampaign") + .withMessageConfiguration(messageConfiguration); - CreateCampaignRequest createCampaignRequest = new CreateCampaignRequest() - .withApplicationId(appId).withWriteCampaignRequest(request); + CreateCampaignRequest createCampaignRequest = new CreateCampaignRequest() + .withApplicationId(appId).withWriteCampaignRequest(request); - CreateCampaignResult result = client.createCampaign(createCampaignRequest); + CreateCampaignResult result = client.createCampaign(createCampaignRequest); - System.out.println("Campaign ID: " + result.getCampaignResponse().getId()); + System.out.println("Campaign ID: " + result.getCampaignResponse().getId()); - return result.getCampaignResponse(); - } + return result.getCampaignResponse(); + } } diff --git a/java/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateEndpoint.java b/java/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateEndpoint.java index 582038f0e20..7b3d4029b76 100644 --- a/java/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateEndpoint.java +++ b/java/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateEndpoint.java @@ -1,25 +1,5 @@ -//snippet-sourcedescription:[CreateEndpoint.java demonstrates how to create an endpoint for an application in Pinpoint.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[mobiletargeting] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; import com.amazonaws.regions.Regions; @@ -46,104 +26,104 @@ public class CreateEndpoint { - public static void main(String[] args) { + public static void main(String[] args) { - final String USAGE = "\n" + - "CreateEndpoint - create an endpoint for an application in pinpoint\n\n" + - "Usage: CreateEndpoint \n\n" + - "Where:\n" + - " appId - the ID of the application to create an endpoint for.\n\n"; + final String USAGE = "\n" + + "CreateEndpoint - create an endpoint for an application in pinpoint\n\n" + + "Usage: CreateEndpoint \n\n" + + "Where:\n" + + " appId - the ID of the application to create an endpoint for.\n\n"; - if (args.length < 1) { - System.out.println(USAGE); - System.exit(1); + if (args.length < 1) { + System.out.println(USAGE); + System.exit(1); + } + String appId = args[0]; + + AmazonPinpoint pinpoint = AmazonPinpointClientBuilder.standard().withRegion(Regions.US_EAST_1).build(); + + EndpointResponse response = createEndpoint(pinpoint, appId); + + System.out.println(response.getAddress()); + System.out.println(response.getChannelType()); + System.out.println(response.getApplicationId()); + System.out.println(response.getEndpointStatus()); + System.out.println(response.getRequestId()); + System.out.println(response.getUser()); + } + + public static EndpointResponse createEndpoint(AmazonPinpoint client, String appId) { + String endpointId = UUID.randomUUID().toString(); + System.out.println("Endpoint ID: " + endpointId); + + EndpointRequest endpointRequest = createEndpointRequestData(); + + UpdateEndpointRequest updateEndpointRequest = new UpdateEndpointRequest() + .withApplicationId(appId) + .withEndpointId(endpointId) + .withEndpointRequest(endpointRequest); + + UpdateEndpointResult updateEndpointResponse = client.updateEndpoint(updateEndpointRequest); + System.out.println("Update Endpoint Response: " + updateEndpointResponse.getMessageBody()); + + GetEndpointRequest getEndpointRequest = new GetEndpointRequest() + .withApplicationId(appId) + .withEndpointId(endpointId); + GetEndpointResult getEndpointResult = client.getEndpoint(getEndpointRequest); + + System.out.println("Got Endpoint: " + getEndpointResult.getEndpointResponse().getId()); + return getEndpointResult.getEndpointResponse(); + } + + private static EndpointRequest createEndpointRequestData() { + + HashMap> customAttributes = new HashMap<>(); + List favoriteTeams = new ArrayList<>(); + favoriteTeams.add("Lakers"); + favoriteTeams.add("Warriors"); + customAttributes.put("team", favoriteTeams); + + EndpointDemographic demographic = new EndpointDemographic() + .withAppVersion("1.0") + .withMake("apple") + .withModel("iPhone") + .withModelVersion("7") + .withPlatform("ios") + .withPlatformVersion("10.1.1") + .withTimezone("America/Los_Angeles"); + + EndpointLocation location = new EndpointLocation() + .withCity("Los Angeles") + .withCountry("US") + .withLatitude(34.0) + .withLongitude(-118.2) + .withPostalCode("90068") + .withRegion("CA"); + + Map metrics = new HashMap<>(); + metrics.put("health", 100.00); + metrics.put("luck", 75.00); + + EndpointUser user = new EndpointUser() + .withUserId(UUID.randomUUID().toString()); + + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); // Quoted "Z" to indicate UTC, no + // timezone offset + String nowAsISO = df.format(new Date()); + + EndpointRequest endpointRequest = new EndpointRequest() + .withAddress(UUID.randomUUID().toString()) + .withAttributes(customAttributes) + .withChannelType("APNS") + .withDemographic(demographic) + .withEffectiveDate(nowAsISO) + .withLocation(location) + .withMetrics(metrics) + .withOptOut("NONE") + .withRequestId(UUID.randomUUID().toString()) + .withUser(user); + + return endpointRequest; } - String appId = args[0]; - - AmazonPinpoint pinpoint = AmazonPinpointClientBuilder.standard().withRegion(Regions.US_EAST_1).build(); - - EndpointResponse response = createEndpoint(pinpoint, appId); - - System.out.println(response.getAddress()); - System.out.println(response.getChannelType()); - System.out.println(response.getApplicationId()); - System.out.println(response.getEndpointStatus()); - System.out.println(response.getRequestId()); - System.out.println(response.getUser()); - } - - public static EndpointResponse createEndpoint(AmazonPinpoint client, String appId) { - String endpointId = UUID.randomUUID().toString(); - System.out.println("Endpoint ID: " + endpointId); - - EndpointRequest endpointRequest = createEndpointRequestData(); - - UpdateEndpointRequest updateEndpointRequest = new UpdateEndpointRequest() - .withApplicationId(appId) - .withEndpointId(endpointId) - .withEndpointRequest(endpointRequest); - - UpdateEndpointResult updateEndpointResponse = client.updateEndpoint(updateEndpointRequest); - System.out.println("Update Endpoint Response: " + updateEndpointResponse.getMessageBody()); - - GetEndpointRequest getEndpointRequest = new GetEndpointRequest() - .withApplicationId(appId) - .withEndpointId(endpointId); - GetEndpointResult getEndpointResult = client.getEndpoint(getEndpointRequest); - - System.out.println("Got Endpoint: " + getEndpointResult.getEndpointResponse().getId()); - return getEndpointResult.getEndpointResponse(); - } - - private static EndpointRequest createEndpointRequestData() { - - HashMap> customAttributes = new HashMap<>(); - List favoriteTeams = new ArrayList<>(); - favoriteTeams.add("Lakers"); - favoriteTeams.add("Warriors"); - customAttributes.put("team", favoriteTeams); - - - EndpointDemographic demographic = new EndpointDemographic() - .withAppVersion("1.0") - .withMake("apple") - .withModel("iPhone") - .withModelVersion("7") - .withPlatform("ios") - .withPlatformVersion("10.1.1") - .withTimezone("America/Los_Angeles"); - - EndpointLocation location = new EndpointLocation() - .withCity("Los Angeles") - .withCountry("US") - .withLatitude(34.0) - .withLongitude(-118.2) - .withPostalCode("90068") - .withRegion("CA"); - - Map metrics = new HashMap<>(); - metrics.put("health", 100.00); - metrics.put("luck", 75.00); - - EndpointUser user = new EndpointUser() - .withUserId(UUID.randomUUID().toString()); - - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); // Quoted "Z" to indicate UTC, no timezone offset - String nowAsISO = df.format(new Date()); - - EndpointRequest endpointRequest = new EndpointRequest() - .withAddress(UUID.randomUUID().toString()) - .withAttributes(customAttributes) - .withChannelType("APNS") - .withDemographic(demographic) - .withEffectiveDate(nowAsISO) - .withLocation(location) - .withMetrics(metrics) - .withOptOut("NONE") - .withRequestId(UUID.randomUUID().toString()) - .withUser(user); - - return endpointRequest; - } } diff --git a/java/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateSegment.java b/java/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateSegment.java index db0af54fd74..8b5380184b8 100644 --- a/java/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateSegment.java +++ b/java/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateSegment.java @@ -1,25 +1,5 @@ -//snippet-sourcedescription:[CreateSegment.java demonstrates how to create a segment for a campaign in Pinpoint.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[mobiletargeting] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; import com.amazonaws.regions.Regions; @@ -42,56 +22,56 @@ public class CreateSegment { - public static void main(String[] args) { - final String USAGE = "\n" + - "CreateSegment - create a segment \n\n" + - "Usage: CreateSegment \n\n" + - "Where:\n" + - " appId - the ID the application to create a segment for.\n\n"; + public static void main(String[] args) { + final String USAGE = "\n" + + "CreateSegment - create a segment \n\n" + + "Usage: CreateSegment \n\n" + + "Where:\n" + + " appId - the ID the application to create a segment for.\n\n"; - if (args.length < 1) { - System.out.println(USAGE); - System.exit(1); - } - String appId = args[0]; - - AmazonPinpoint pinpoint = AmazonPinpointClientBuilder.standard().withRegion(Regions.US_EAST_1).build(); + if (args.length < 1) { + System.out.println(USAGE); + System.exit(1); + } + String appId = args[0]; - SegmentResponse result = createSegment(pinpoint, appId); - System.out.println("Segment " + result.getName() + " created."); - System.out.println(result.getSegmentType()); - } + AmazonPinpoint pinpoint = AmazonPinpointClientBuilder.standard().withRegion(Regions.US_EAST_1).build(); - public static SegmentResponse createSegment(AmazonPinpoint client, String appId) { - Map segmentAttributes = new HashMap<>(); - segmentAttributes.put("Team", new AttributeDimension().withAttributeType(AttributeType.INCLUSIVE).withValues("Lakers")); + SegmentResponse result = createSegment(pinpoint, appId); + System.out.println("Segment " + result.getName() + " created."); + System.out.println(result.getSegmentType()); + } - SegmentBehaviors segmentBehaviors = new SegmentBehaviors(); - SegmentDemographics segmentDemographics = new SegmentDemographics(); - SegmentLocation segmentLocation = new SegmentLocation(); + public static SegmentResponse createSegment(AmazonPinpoint client, String appId) { + Map segmentAttributes = new HashMap<>(); + segmentAttributes.put("Team", new AttributeDimension().withAttributeType(AttributeType.INCLUSIVE) + .withValues("Lakers")); - RecencyDimension recencyDimension = new RecencyDimension(); - recencyDimension.withDuration("DAY_30").withRecencyType("ACTIVE"); - segmentBehaviors.setRecency(recencyDimension); + SegmentBehaviors segmentBehaviors = new SegmentBehaviors(); + SegmentDemographics segmentDemographics = new SegmentDemographics(); + SegmentLocation segmentLocation = new SegmentLocation(); - SegmentDimensions dimensions = new SegmentDimensions() - .withAttributes(segmentAttributes) - .withBehavior(segmentBehaviors) - .withDemographic(segmentDemographics) - .withLocation(segmentLocation); + RecencyDimension recencyDimension = new RecencyDimension(); + recencyDimension.withDuration("DAY_30").withRecencyType("ACTIVE"); + segmentBehaviors.setRecency(recencyDimension); + SegmentDimensions dimensions = new SegmentDimensions() + .withAttributes(segmentAttributes) + .withBehavior(segmentBehaviors) + .withDemographic(segmentDemographics) + .withLocation(segmentLocation); - WriteSegmentRequest writeSegmentRequest = new WriteSegmentRequest() - .withName("MySegment").withDimensions(dimensions); + WriteSegmentRequest writeSegmentRequest = new WriteSegmentRequest() + .withName("MySegment").withDimensions(dimensions); - CreateSegmentRequest createSegmentRequest = new CreateSegmentRequest() - .withApplicationId(appId).withWriteSegmentRequest(writeSegmentRequest); + CreateSegmentRequest createSegmentRequest = new CreateSegmentRequest() + .withApplicationId(appId).withWriteSegmentRequest(writeSegmentRequest); - CreateSegmentResult createSegmentResult = client.createSegment(createSegmentRequest); + CreateSegmentResult createSegmentResult = client.createSegment(createSegmentRequest); - System.out.println("Segment ID: " + createSegmentResult.getSegmentResponse().getId()); + System.out.println("Segment ID: " + createSegmentResult.getSegmentResponse().getId()); - return createSegmentResult.getSegmentResponse(); - } + return createSegmentResult.getSegmentResponse(); + } } diff --git a/java/example_code/pinpoint/src/main/java/com/example/pinpoint/DeleteApp.java b/java/example_code/pinpoint/src/main/java/com/example/pinpoint/DeleteApp.java index b1b0f75d6cf..e00d88e8891 100644 --- a/java/example_code/pinpoint/src/main/java/com/example/pinpoint/DeleteApp.java +++ b/java/example_code/pinpoint/src/main/java/com/example/pinpoint/DeleteApp.java @@ -1,25 +1,5 @@ -//snippet-sourcedescription:[DeleteApp.java demonstrates how to delete an application in the Pinpoint dashboard.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[mobiletargeting] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; import com.amazonaws.regions.Regions; @@ -31,19 +11,19 @@ public class DeleteApp { public static void main(String args[]) { final String USAGE = "\n" + - "DeleteApp - delete an application in the pinpoint dashboard\n\n" + - "Usage: DeleteApp \n\n" + - "Where:\n" + - " appID - the application ID of the application to delete.\n\n"; + "DeleteApp - delete an application in the pinpoint dashboard\n\n" + + "Usage: DeleteApp \n\n" + + "Where:\n" + + " appID - the application ID of the application to delete.\n\n"; - if (args.length < 1) { - System.out.println(USAGE); - System.exit(1); - } + if (args.length < 1) { + System.out.println(USAGE); + System.exit(1); + } - String appID = args[0]; + String appID = args[0]; - System.out.println("Deleting application: " + appID); + System.out.println("Deleting application: " + appID); AmazonPinpoint pinpoint = AmazonPinpointClientBuilder.standard().withRegion(Regions.US_EAST_1).build(); diff --git a/java/example_code/pinpoint/src/main/java/com/example/pinpoint/ImportSegment.java b/java/example_code/pinpoint/src/main/java/com/example/pinpoint/ImportSegment.java index 0df123437f9..2ba7d3c8681 100644 --- a/java/example_code/pinpoint/src/main/java/com/example/pinpoint/ImportSegment.java +++ b/java/example_code/pinpoint/src/main/java/com/example/pinpoint/ImportSegment.java @@ -1,25 +1,5 @@ -//snippet-sourcedescription:[ImportSegment.java demonstrates how to import a segment into Pinpoint.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[mobiletargeting] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; import com.amazonaws.regions.Regions; @@ -31,39 +11,38 @@ import com.amazonaws.services.pinpoint.model.ImportJobRequest; import com.amazonaws.services.pinpoint.model.ImportJobResponse; - public class ImportSegment { public static void main(String[] args) { final String USAGE = "\n" + - "ImportSegment - import a segment \n\n" + - "Usage: ImportSegment \n\n" + - "Where:\n" + - " appId - the ID the application to create a segment for.\n\n" + - " bucket - name of the s3 bucket that contains the segment definitions.\n\n" + - " key - key of the s3 object " + - " roleArn - ARN of the role that allows pinpoint to access S3"; - - if (args.length < 1) { - System.out.println(USAGE); - System.exit(1); - } - String appId = args[0]; - String bucket = args[1]; - String key = args[2]; - String roleArn = args[3]; + "ImportSegment - import a segment \n\n" + + "Usage: ImportSegment \n\n" + + "Where:\n" + + " appId - the ID the application to create a segment for.\n\n" + + " bucket - name of the s3 bucket that contains the segment definitions.\n\n" + + " key - key of the s3 object " + + " roleArn - ARN of the role that allows pinpoint to access S3"; + + if (args.length < 1) { + System.out.println(USAGE); + System.exit(1); + } + String appId = args[0]; + String bucket = args[1]; + String key = args[2]; + String roleArn = args[3]; AmazonPinpoint pinpoint = AmazonPinpointClientBuilder.standard().withRegion(Regions.US_EAST_1).build(); ImportJobResponse result = createImportSegment(pinpoint, appId, bucket, key, roleArn); - System.out.println("Import job for " + bucket + " submitted."); - System.out.println("See application " + result.getApplicationId() + " for import job status."); + System.out.println("Import job for " + bucket + " submitted."); + System.out.println("See application " + result.getApplicationId() + " for import job status."); } public static ImportJobResponse createImportSegment(AmazonPinpoint client, String appId, - String bucket, - String key, - String roleArn) { + String bucket, + String key, + String roleArn) { // Create the job. ImportJobRequest importRequest = new ImportJobRequest() @@ -80,5 +59,5 @@ public static ImportJobResponse createImportSegment(AmazonPinpoint client, CreateImportJobResult jobResponse = client.createImportJob(jobRequest); return jobResponse.getImportJobResponse(); - } } +} diff --git a/java/example_code/pinpoint/src/main/java/com/example/pinpoint/UpdateChannel.java b/java/example_code/pinpoint/src/main/java/com/example/pinpoint/UpdateChannel.java index ef4c54a574f..84894514969 100644 --- a/java/example_code/pinpoint/src/main/java/com/example/pinpoint/UpdateChannel.java +++ b/java/example_code/pinpoint/src/main/java/com/example/pinpoint/UpdateChannel.java @@ -1,25 +1,5 @@ -//snippet-sourcedescription:[UpdateChannel.java demonstrates how to create a channel for an application in Pinpoint.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[mobiletargeting] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-01-15] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; import com.amazonaws.regions.Regions; @@ -36,16 +16,16 @@ public class UpdateChannel { public static void main(String[] args) { final String USAGE = "\n" + - "CreateChannel - create a channel in pinpoint\n\n" + - "Usage: CreateChannel \n\n" + - "Where:\n" + - " appId - the name of the application to create.\n\n"; - - if (args.length < 1) { - System.out.println(USAGE); - System.exit(1); - } - String appId = args[0]; + "CreateChannel - create a channel in pinpoint\n\n" + + "Usage: CreateChannel \n\n" + + "Where:\n" + + " appId - the name of the application to create.\n\n"; + + if (args.length < 1) { + System.out.println(USAGE); + System.exit(1); + } + String appId = args[0]; AmazonPinpoint pinpoint = AmazonPinpointClientBuilder.standard().withRegion(Regions.US_EAST_1).build(); diff --git a/java/example_code/polly/DescribeVoices.java b/java/example_code/polly/DescribeVoices.java index 12fe3d1256d..db350290ce3 100644 --- a/java/example_code/polly/DescribeVoices.java +++ b/java/example_code/polly/DescribeVoices.java @@ -1,58 +1,37 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[Produces a list of all voices available for use when requesting speech synthesis with Amazon Polly.] -// snippet-service:[polly] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Polly] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DescribeVoices] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] // snippet-start:[polly.java.DescribeVoices.complete] package com.amazonaws.polly.samples; - + import com.amazonaws.services.polly.AmazonPolly; import com.amazonaws.services.polly.AmazonPollyClientBuilder; import com.amazonaws.services.polly.model.DescribeVoicesRequest; import com.amazonaws.services.polly.model.DescribeVoicesResult; - + public class DescribeVoicesSample { AmazonPolly client = AmazonPollyClientBuilder.defaultClient(); - + public void describeVoices() { DescribeVoicesRequest allVoicesRequest = new DescribeVoicesRequest(); DescribeVoicesRequest enUsVoicesRequest = new DescribeVoicesRequest().withLanguageCode("en-US"); - + try { String nextToken; do { DescribeVoicesResult allVoicesResult = client.describeVoices(allVoicesRequest); nextToken = allVoicesResult.getNextToken(); allVoicesRequest.setNextToken(nextToken); - + System.out.println("All voices: " + allVoicesResult.getVoices()); } while (nextToken != null); - + do { DescribeVoicesResult enUsVoicesResult = client.describeVoices(enUsVoicesRequest); nextToken = enUsVoicesResult.getNextToken(); enUsVoicesRequest.setNextToken(nextToken); - + System.out.println("en-US voices: " + enUsVoicesResult.getVoices()); } while (nextToken != null); } catch (Exception e) { @@ -61,8 +40,4 @@ public void describeVoices() { } } - - - - // snippet-end:[polly.java.DescribeVoices.complete] \ No newline at end of file diff --git a/java/example_code/polly/GetLexicon.java b/java/example_code/polly/GetLexicon.java index a596db62205..26a6976ddc9 100644 --- a/java/example_code/polly/GetLexicon.java +++ b/java/example_code/polly/GetLexicon.java @@ -1,45 +1,23 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[GetLexicon demonstrates how to produce the content of a specific pronunciation lexicon stored in an AWS region.] -// snippet-service:[polly] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Polly] -// snippet-keyword:[Code Sample] -// snippet-keyword:[GetLexicon] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] -// snippet-start:[polly.java.GetLexicon.complete] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[polly.java.GetLexicon.complete] package com.amazonaws.polly.samples; - + import com.amazonaws.services.polly.AmazonPolly; import com.amazonaws.services.polly.AmazonPollyClientBuilder; import com.amazonaws.services.polly.model.GetLexiconRequest; import com.amazonaws.services.polly.model.GetLexiconResult; - + public class GetLexiconSample { private String LEXICON_NAME = "SampleLexicon"; - + AmazonPolly client = AmazonPollyClientBuilder.defaultClient(); - + public void getLexicon() { GetLexiconRequest getLexiconRequest = new GetLexiconRequest().withName(LEXICON_NAME); - + try { GetLexiconResult getLexiconResult = client.getLexicon(getLexiconRequest); System.out.println("Lexicon: " + getLexiconResult.getLexicon()); @@ -49,7 +27,4 @@ public void getLexicon() { } } - - - // snippet-end:[polly.java.GetLexicon.complete] \ No newline at end of file diff --git a/java/example_code/polly/ListLexicons.java b/java/example_code/polly/ListLexicons.java index c090c943219..c4f080bce64 100644 --- a/java/example_code/polly/ListLexicons.java +++ b/java/example_code/polly/ListLexicons.java @@ -1,52 +1,30 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[ListLexicons demonstrates how to produce a list of pronunciation lexicons stored in an AWS Region.] -// snippet-service:[polly] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Polly] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ListLexicons] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] // snippet-start:[polly.java.ListLexicons.complete] - package com.amazonaws.polly.samples; - + import com.amazonaws.services.polly.AmazonPolly; import com.amazonaws.services.polly.AmazonPollyClientBuilder; import com.amazonaws.services.polly.model.LexiconAttributes; import com.amazonaws.services.polly.model.LexiconDescription; import com.amazonaws.services.polly.model.ListLexiconsRequest; import com.amazonaws.services.polly.model.ListLexiconsResult; - + public class ListLexiconsSample { AmazonPolly client = AmazonPollyClientBuilder.defaultClient(); - + public void listLexicons() { ListLexiconsRequest listLexiconsRequest = new ListLexiconsRequest(); - + try { String nextToken; do { ListLexiconsResult listLexiconsResult = client.listLexicons(listLexiconsRequest); nextToken = listLexiconsResult.getNextToken(); listLexiconsRequest.setNextToken(nextToken); - + for (LexiconDescription lexiconDescription : listLexiconsResult.getLexicons()) { LexiconAttributes attributes = lexiconDescription.getAttributes(); System.out.println("Name: " + lexiconDescription.getName() @@ -64,7 +42,4 @@ public void listLexicons() { } } - - - // snippet-end:[polly.java.ListLexicons.complete] \ No newline at end of file diff --git a/java/example_code/polly/PutLexicon.java b/java/example_code/polly/PutLexicon.java index 3dd1a3a22f0..e9659bb953e 100644 --- a/java/example_code/polly/PutLexicon.java +++ b/java/example_code/polly/PutLexicon.java @@ -1,52 +1,30 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[PutLexicon demonstrates how to store a pronunciation lexicon in an AWS Region.] -// snippet-service:[polly] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Polly] -// snippet-keyword:[Code Sample] -// snippet-keyword:[PutLexicon] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] // snippet-start:[polly.java.PutLexicon.complete] - package com.amazonaws.polly.samples; - + import com.amazonaws.services.polly.AmazonPolly; import com.amazonaws.services.polly.AmazonPollyClientBuilder; import com.amazonaws.services.polly.model.LexiconAttributes; import com.amazonaws.services.polly.model.LexiconDescription; import com.amazonaws.services.polly.model.ListLexiconsRequest; import com.amazonaws.services.polly.model.ListLexiconsResult; - + public class ListLexiconsSample { AmazonPolly client = AmazonPollyClientBuilder.defaultClient(); - + public void listLexicons() { ListLexiconsRequest listLexiconsRequest = new ListLexiconsRequest(); - + try { String nextToken; do { ListLexiconsResult listLexiconsResult = client.listLexicons(listLexiconsRequest); nextToken = listLexiconsResult.getNextToken(); listLexiconsRequest.setNextToken(nextToken); - + for (LexiconDescription lexiconDescription : listLexiconsResult.getLexicons()) { LexiconAttributes attributes = lexiconDescription.getAttributes(); System.out.println("Name: " + lexiconDescription.getName() @@ -64,7 +42,4 @@ public void listLexicons() { } } - - - // snippet-end:[polly.java.PutLexicon.complete] \ No newline at end of file diff --git a/java/example_code/polly/SpeechMarks.java b/java/example_code/polly/SpeechMarks.java index e3aee23d926..7f6a7d2e081 100644 --- a/java/example_code/polly/SpeechMarks.java +++ b/java/example_code/polly/SpeechMarks.java @@ -1,52 +1,30 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[SpeechMarks demonstrates how to synthesize speech marks for inputed text.] -// snippet-service:[polly] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Polly] -// snippet-keyword:[Code Sample] -// snippet-keyword:[SpeechMarks] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] // snippet-start:[polly.java.SpeechMarks.complete] - package com.amazonaws.polly.samples; - + import com.amazonaws.services.polly.AmazonPolly; import com.amazonaws.services.polly.AmazonPollyClientBuilder; import com.amazonaws.services.polly.model.LexiconAttributes; import com.amazonaws.services.polly.model.LexiconDescription; import com.amazonaws.services.polly.model.ListLexiconsRequest; import com.amazonaws.services.polly.model.ListLexiconsResult; - + public class ListLexiconsSample { AmazonPolly client = AmazonPollyClientBuilder.defaultClient(); - + public void listLexicons() { ListLexiconsRequest listLexiconsRequest = new ListLexiconsRequest(); - + try { String nextToken; do { ListLexiconsResult listLexiconsResult = client.listLexicons(listLexiconsRequest); nextToken = listLexiconsResult.getNextToken(); listLexiconsRequest.setNextToken(nextToken); - + for (LexiconDescription lexiconDescription : listLexiconsResult.getLexicons()) { LexiconAttributes attributes = lexiconDescription.getAttributes(); System.out.println("Name: " + lexiconDescription.getName() @@ -64,7 +42,4 @@ public void listLexicons() { } } - - - // snippet-end:[polly.java.SpeechMarks.complete] \ No newline at end of file diff --git a/java/example_code/polly/StartSpeechSynthesisTask.java b/java/example_code/polly/StartSpeechSynthesisTask.java index ea3b940ebef..cfdf6e33342 100644 --- a/java/example_code/polly/StartSpeechSynthesisTask.java +++ b/java/example_code/polly/StartSpeechSynthesisTask.java @@ -1,30 +1,8 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[StartSpeechSynthesisTask demonstrates how to synthesize a long speech and store it directly in an Amazon S3 bucket..] -// snippet-service:[polly] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Polly] -// snippet-keyword:[Code Sample] -// snippet-keyword:[StartSpeechSynthesisTask] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] // snippet-start:[polly.java.StartSpeechSynthesisTask.complete] - package com.amazonaws.parrot.service.tests.speech.task; import com.amazonaws.parrot.service.tests.AbstractParrotServiceTest; @@ -38,56 +16,52 @@ public class StartSpeechSynthesisTaskSample { - private static final int SYNTHESIS_TASK_TIMEOUT_SECONDS = 300; - private static final AmazonPolly AMAZON_POLLY_CLIENT = AmazonPollyClientBuilder.defaultClient(); - private static final String PLAIN_TEXT = "This is a sample text to be synthesized."; - private static final String OUTPUT_FORMAT_MP3 = OutputFormat.Mp3.toString(); - private static final String OUTPUT_BUCKET = "synth-books-buckets"; - private static final String SNS_TOPIC_ARN = "arn:aws:sns:eu-west-2:561828872312:synthesize-finish-topic"; - private static final Duration SYNTHESIS_TASK_POLL_INTERVAL = Duration.FIVE_SECONDS; - private static final Duration SYNTHESIS_TASK_POLL_DELAY = Duration.TEN_SECONDS; - - public static void main(String... args) { - StartSpeechSynthesisTaskRequest request = new StartSpeechSynthesisTaskRequest() - .withOutputFormat(OUTPUT_FORMAT_MP3) - .withText(PLAIN_TEXT) - .withTextType(TextType.Text) - .withVoiceId(VoiceId.Amy) - .withOutputS3BucketName(OUTPUT_BUCKET) - .withSnsTopicArn(SNS_TOPIC_ARN); - - StartSpeechSynthesisTaskResult result = AMAZON_POLLY_CLIENT.startSpeechSynthesisTask(request); - String taskId = result.getSynthesisTask().getTaskId(); - - await().with() - .pollInterval(SYNTHESIS_TASK_POLL_INTERVAL) - .pollDelay(SYNTHESIS_TASK_POLL_DELAY) - .atMost(SYNTHESIS_TASK_TIMEOUT_SECONDS, TimeUnit.SECONDS) - .until( - () -> getSynthesisTaskStatus(taskId).equals(TaskStatus.Completed.toString()) - ); - } - - private static SynthesisTask getSynthesisTask(String taskId) { - GetSpeechSynthesisTaskRequest getSpeechSynthesisTaskRequest = new GetSpeechSynthesisTaskRequest() - .withTaskId(taskId); - GetSpeechSynthesisTaskResult result =AMAZON_POLLY_CLIENT.getSpeechSynthesisTask(getSpeechSynthesisTaskRequest); - return result.getSynthesisTask(); - } - - private static String getSynthesisTaskStatus(String taskId) { - GetSpeechSynthesisTaskRequest getSpeechSynthesisTaskRequest = new GetSpeechSynthesisTaskRequest() - .withTaskId(taskId); - GetSpeechSynthesisTaskResult result =AMAZON_POLLY_CLIENT.getSpeechSynthesisTask(getSpeechSynthesisTaskRequest); - return result.getSynthesisTask().getTaskStatus(); - } + private static final int SYNTHESIS_TASK_TIMEOUT_SECONDS = 300; + private static final AmazonPolly AMAZON_POLLY_CLIENT = AmazonPollyClientBuilder.defaultClient(); + private static final String PLAIN_TEXT = "This is a sample text to be synthesized."; + private static final String OUTPUT_FORMAT_MP3 = OutputFormat.Mp3.toString(); + private static final String OUTPUT_BUCKET = "synth-books-buckets"; + private static final String SNS_TOPIC_ARN = "arn:aws:sns:eu-west-2:561828872312:synthesize-finish-topic"; + private static final Duration SYNTHESIS_TASK_POLL_INTERVAL = Duration.FIVE_SECONDS; + private static final Duration SYNTHESIS_TASK_POLL_DELAY = Duration.TEN_SECONDS; + + public static void main(String... args) { + StartSpeechSynthesisTaskRequest request = new StartSpeechSynthesisTaskRequest() + .withOutputFormat(OUTPUT_FORMAT_MP3) + .withText(PLAIN_TEXT) + .withTextType(TextType.Text) + .withVoiceId(VoiceId.Amy) + .withOutputS3BucketName(OUTPUT_BUCKET) + .withSnsTopicArn(SNS_TOPIC_ARN); + + StartSpeechSynthesisTaskResult result = AMAZON_POLLY_CLIENT.startSpeechSynthesisTask(request); + String taskId = result.getSynthesisTask().getTaskId(); + + await().with() + .pollInterval(SYNTHESIS_TASK_POLL_INTERVAL) + .pollDelay(SYNTHESIS_TASK_POLL_DELAY) + .atMost(SYNTHESIS_TASK_TIMEOUT_SECONDS, TimeUnit.SECONDS) + .until( + () -> getSynthesisTaskStatus(taskId) + .equals(TaskStatus.Completed.toString())); + } + + private static SynthesisTask getSynthesisTask(String taskId) { + GetSpeechSynthesisTaskRequest getSpeechSynthesisTaskRequest = new GetSpeechSynthesisTaskRequest() + .withTaskId(taskId); + GetSpeechSynthesisTaskResult result = AMAZON_POLLY_CLIENT + .getSpeechSynthesisTask(getSpeechSynthesisTaskRequest); + return result.getSynthesisTask(); + } + + private static String getSynthesisTaskStatus(String taskId) { + GetSpeechSynthesisTaskRequest getSpeechSynthesisTaskRequest = new GetSpeechSynthesisTaskRequest() + .withTaskId(taskId); + GetSpeechSynthesisTaskResult result = AMAZON_POLLY_CLIENT + .getSpeechSynthesisTask(getSpeechSynthesisTaskRequest); + return result.getSynthesisTask().getTaskStatus(); + } } - - - - - - // snippet-end:[polly.java.StartSpeechSynthesisTask.complete] diff --git a/java/example_code/polly/SynthesisSpeech.java b/java/example_code/polly/SynthesisSpeech.java index b2042b0cc0b..e2e7f7cf0b0 100644 --- a/java/example_code/polly/SynthesisSpeech.java +++ b/java/example_code/polly/SynthesisSpeech.java @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[SynthesizeSpeech demonstrates how to synthesize speeches using Amazon Polly with shorter texts for near-real time processing.] -// snippet-service:[polly] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Polly] -// snippet-keyword:[Code Sample] -// snippet-keyword:[SynthesizeSpeech] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] // snippet-start:[polly.java.SynthesizeSpeech.complete] package com.amazonaws.parrot.service.tests.speech.task; @@ -37,57 +16,52 @@ public class StartSpeechSynthesisTaskSample { - private static final int SYNTHESIS_TASK_TIMEOUT_SECONDS = 300; - private static final AmazonPolly AMAZON_POLLY_CLIENT = AmazonPollyClientBuilder.defaultClient(); - private static final String PLAIN_TEXT = "This is a sample text to be synthesized."; - private static final String OUTPUT_FORMAT_MP3 = OutputFormat.Mp3.toString(); - private static final String OUTPUT_BUCKET = "synth-books-buckets"; - private static final String SNS_TOPIC_ARN = "arn:aws:sns:eu-west-2:561828872312:synthesize-finish-topic"; - private static final Duration SYNTHESIS_TASK_POLL_INTERVAL = Duration.FIVE_SECONDS; - private static final Duration SYNTHESIS_TASK_POLL_DELAY = Duration.TEN_SECONDS; - - public static void main(String... args) { - StartSpeechSynthesisTaskRequest request = new StartSpeechSynthesisTaskRequest() - .withOutputFormat(OUTPUT_FORMAT_MP3) - .withText(PLAIN_TEXT) - .withTextType(TextType.Text) - .withVoiceId(VoiceId.Amy) - .withOutputS3BucketName(OUTPUT_BUCKET) - .withSnsTopicArn(SNS_TOPIC_ARN); - - StartSpeechSynthesisTaskResult result = AMAZON_POLLY_CLIENT.startSpeechSynthesisTask(request); - String taskId = result.getSynthesisTask().getTaskId(); - - await().with() - .pollInterval(SYNTHESIS_TASK_POLL_INTERVAL) - .pollDelay(SYNTHESIS_TASK_POLL_DELAY) - .atMost(SYNTHESIS_TASK_TIMEOUT_SECONDS, TimeUnit.SECONDS) - .until( - () -> getSynthesisTaskStatus(taskId).equals(TaskStatus.Completed.toString()) - ); - } - - private static SynthesisTask getSynthesisTask(String taskId) { - GetSpeechSynthesisTaskRequest getSpeechSynthesisTaskRequest = new GetSpeechSynthesisTaskRequest() - .withTaskId(taskId); - GetSpeechSynthesisTaskResult result =AMAZON_POLLY_CLIENT.getSpeechSynthesisTask(getSpeechSynthesisTaskRequest); - return result.getSynthesisTask(); - } - - private static String getSynthesisTaskStatus(String taskId) { - GetSpeechSynthesisTaskRequest getSpeechSynthesisTaskRequest = new GetSpeechSynthesisTaskRequest() - .withTaskId(taskId); - GetSpeechSynthesisTaskResult result =AMAZON_POLLY_CLIENT.getSpeechSynthesisTask(getSpeechSynthesisTaskRequest); - return result.getSynthesisTask().getTaskStatus(); - } + private static final int SYNTHESIS_TASK_TIMEOUT_SECONDS = 300; + private static final AmazonPolly AMAZON_POLLY_CLIENT = AmazonPollyClientBuilder.defaultClient(); + private static final String PLAIN_TEXT = "This is a sample text to be synthesized."; + private static final String OUTPUT_FORMAT_MP3 = OutputFormat.Mp3.toString(); + private static final String OUTPUT_BUCKET = "synth-books-buckets"; + private static final String SNS_TOPIC_ARN = "arn:aws:sns:eu-west-2:561828872312:synthesize-finish-topic"; + private static final Duration SYNTHESIS_TASK_POLL_INTERVAL = Duration.FIVE_SECONDS; + private static final Duration SYNTHESIS_TASK_POLL_DELAY = Duration.TEN_SECONDS; + + public static void main(String... args) { + StartSpeechSynthesisTaskRequest request = new StartSpeechSynthesisTaskRequest() + .withOutputFormat(OUTPUT_FORMAT_MP3) + .withText(PLAIN_TEXT) + .withTextType(TextType.Text) + .withVoiceId(VoiceId.Amy) + .withOutputS3BucketName(OUTPUT_BUCKET) + .withSnsTopicArn(SNS_TOPIC_ARN); + + StartSpeechSynthesisTaskResult result = AMAZON_POLLY_CLIENT.startSpeechSynthesisTask(request); + String taskId = result.getSynthesisTask().getTaskId(); + + await().with() + .pollInterval(SYNTHESIS_TASK_POLL_INTERVAL) + .pollDelay(SYNTHESIS_TASK_POLL_DELAY) + .atMost(SYNTHESIS_TASK_TIMEOUT_SECONDS, TimeUnit.SECONDS) + .until( + () -> getSynthesisTaskStatus(taskId) + .equals(TaskStatus.Completed.toString())); + } + + private static SynthesisTask getSynthesisTask(String taskId) { + GetSpeechSynthesisTaskRequest getSpeechSynthesisTaskRequest = new GetSpeechSynthesisTaskRequest() + .withTaskId(taskId); + GetSpeechSynthesisTaskResult result = AMAZON_POLLY_CLIENT + .getSpeechSynthesisTask(getSpeechSynthesisTaskRequest); + return result.getSynthesisTask(); + } + + private static String getSynthesisTaskStatus(String taskId) { + GetSpeechSynthesisTaskRequest getSpeechSynthesisTaskRequest = new GetSpeechSynthesisTaskRequest() + .withTaskId(taskId); + GetSpeechSynthesisTaskResult result = AMAZON_POLLY_CLIENT + .getSpeechSynthesisTask(getSpeechSynthesisTaskRequest); + return result.getSynthesisTask().getTaskStatus(); + } } - - - - - - - // snippet-end:[polly.java.SynthesizeSpeech.complete] \ No newline at end of file diff --git a/java/example_code/redshift/ConnectToCluster.java b/java/example_code/redshift/ConnectToCluster.java index b6aec5562ea..466a20b2de9 100644 --- a/java/example_code/redshift/ConnectToCluster.java +++ b/java/example_code/redshift/ConnectToCluster.java @@ -1,28 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[ConnectToClusterExample demonstrates how to connect to an Amazon Redshift cluster and run a sample query.] -// snippet-service:[redshift] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Redshift] -// snippet-keyword:[Code Sample] -// snippet-keyword:[Connect] -// snippet-keyword:[JDBC] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-02-01] -// snippet-sourceauthor:[AWS] // snippet-start:[redshift.java.ConnectToCluster.complete] package connection; @@ -31,68 +9,69 @@ import java.util.Properties; public class ConnectToCluster { - //Redshift driver: "jdbc:redshift://x.y.us-west-2.redshift.amazonaws.com:5439/dev"; - static final String dbURL = "***jdbc cluster connection string ****"; - static final String MasterUsername = "***master user name***"; - static final String MasterUserPassword = "***master user password***"; + // Redshift driver: + // "jdbc:redshift://x.y.us-west-2.redshift.amazonaws.com:5439/dev"; + static final String dbURL = "***jdbc cluster connection string ****"; + static final String MasterUsername = "***master user name***"; + static final String MasterUserPassword = "***master user password***"; - public static void main(String[] args) { - Connection conn = null; - Statement stmt = null; - try{ - //Dynamically load driver at runtime. - //Redshift JDBC 4.1 driver: com.amazon.redshift.jdbc41.Driver - //Redshift JDBC 4 driver: com.amazon.redshift.jdbc4.Driver - Class.forName("com.amazon.redshift.jdbc.Driver"); + public static void main(String[] args) { + Connection conn = null; + Statement stmt = null; + try { + // Dynamically load driver at runtime. + // Redshift JDBC 4.1 driver: com.amazon.redshift.jdbc41.Driver + // Redshift JDBC 4 driver: com.amazon.redshift.jdbc4.Driver + Class.forName("com.amazon.redshift.jdbc.Driver"); - //Open a connection and define properties. - System.out.println("Connecting to database..."); - Properties props = new Properties(); + // Open a connection and define properties. + System.out.println("Connecting to database..."); + Properties props = new Properties(); - //Uncomment the following line if using a keystore. - //props.setProperty("ssl", "true"); - props.setProperty("user", MasterUsername); - props.setProperty("password", MasterUserPassword); - conn = DriverManager.getConnection(dbURL, props); + // Uncomment the following line if using a keystore. + // props.setProperty("ssl", "true"); + props.setProperty("user", MasterUsername); + props.setProperty("password", MasterUserPassword); + conn = DriverManager.getConnection(dbURL, props); - //Try a simple query. - System.out.println("Listing system tables..."); - stmt = conn.createStatement(); - String sql; - sql = "select * from information_schema.tables;"; - ResultSet rs = stmt.executeQuery(sql); + // Try a simple query. + System.out.println("Listing system tables..."); + stmt = conn.createStatement(); + String sql; + sql = "select * from information_schema.tables;"; + ResultSet rs = stmt.executeQuery(sql); - //Get the data from the result set. - while(rs.next()){ - //Retrieve two columns. - String catalog = rs.getString("table_catalog"); - String name = rs.getString("table_name"); + // Get the data from the result set. + while (rs.next()) { + // Retrieve two columns. + String catalog = rs.getString("table_catalog"); + String name = rs.getString("table_name"); - //Display values. - System.out.print("Catalog: " + catalog); - System.out.println(", Name: " + name); - } - rs.close(); - stmt.close(); - conn.close(); - }catch(Exception ex){ - //For convenience, handle all errors here. - ex.printStackTrace(); - }finally{ - //Finally block to close resources. - try{ - if(stmt!=null) - stmt.close(); - }catch(Exception ex){ - }// nothing we can do - try{ - if(conn!=null) - conn.close(); - }catch(Exception ex){ - ex.printStackTrace(); - } - } - System.out.println("Finished connectivity test."); - } + // Display values. + System.out.print("Catalog: " + catalog); + System.out.println(", Name: " + name); + } + rs.close(); + stmt.close(); + conn.close(); + } catch (Exception ex) { + // For convenience, handle all errors here. + ex.printStackTrace(); + } finally { + // Finally block to close resources. + try { + if (stmt != null) + stmt.close(); + } catch (Exception ex) { + } // nothing we can do + try { + if (conn != null) + conn.close(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + System.out.println("Finished connectivity test."); + } } // snippet-end:[redshift.java.ConnectToCluster.complete] \ No newline at end of file diff --git a/java/example_code/redshift/ConnectToClusterExample.java b/java/example_code/redshift/ConnectToClusterExample.java index f60995f92af..1d321549c10 100644 --- a/java/example_code/redshift/ConnectToClusterExample.java +++ b/java/example_code/redshift/ConnectToClusterExample.java @@ -1,96 +1,75 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[ConnectToClusterExample demonstrates how to connect to an Amazon Redshift cluster and run a sample query.] -// snippet-service:[redshift] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Redshift] -// snippet-keyword:[Code Sample] -// snippet-keyword:[Connect] -// snippet-keyword:[JDBC] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2015-02-19] -// snippet-sourceauthor:[AWS] package connection; import java.sql.*; import java.util.Properties; public class Docs { - //Redshift driver: "jdbc:redshift://x.y.us-west-2.redshift.amazonaws.com:5439/dev"; - //or "jdbc:postgresql://x.y.us-west-2.redshift.amazonaws.com:5439/dev"; - static final String dbURL = "***jdbc cluster connection string ****"; - static final String MasterUsername = "***master user name***"; - static final String MasterUserPassword = "***master user password***"; + // Redshift driver: + // "jdbc:redshift://x.y.us-west-2.redshift.amazonaws.com:5439/dev"; + // or "jdbc:postgresql://x.y.us-west-2.redshift.amazonaws.com:5439/dev"; + static final String dbURL = "***jdbc cluster connection string ****"; + static final String MasterUsername = "***master user name***"; + static final String MasterUserPassword = "***master user password***"; - public static void main(String[] args) { - Connection conn = null; - Statement stmt = null; - try{ - //Dynamically load driver at runtime. - //Redshift JDBC 4.1 driver: com.amazon.redshift.jdbc41.Driver - //Redshift JDBC 4 driver: com.amazon.redshift.jdbc4.Driver - Class.forName("com.amazon.redshift.jdbc.Driver"); + public static void main(String[] args) { + Connection conn = null; + Statement stmt = null; + try { + // Dynamically load driver at runtime. + // Redshift JDBC 4.1 driver: com.amazon.redshift.jdbc41.Driver + // Redshift JDBC 4 driver: com.amazon.redshift.jdbc4.Driver + Class.forName("com.amazon.redshift.jdbc.Driver"); - //Open a connection and define properties. - System.out.println("Connecting to database..."); - Properties props = new Properties(); + // Open a connection and define properties. + System.out.println("Connecting to database..."); + Properties props = new Properties(); - //Uncomment the following line if using a keystore. - //props.setProperty("ssl", "true"); - props.setProperty("user", MasterUsername); - props.setProperty("password", MasterUserPassword); - conn = DriverManager.getConnection(dbURL, props); + // Uncomment the following line if using a keystore. + // props.setProperty("ssl", "true"); + props.setProperty("user", MasterUsername); + props.setProperty("password", MasterUserPassword); + conn = DriverManager.getConnection(dbURL, props); - //Try a simple query. - System.out.println("Listing system tables..."); - stmt = conn.createStatement(); - String sql; - sql = "select * from information_schema.tables;"; - ResultSet rs = stmt.executeQuery(sql); + // Try a simple query. + System.out.println("Listing system tables..."); + stmt = conn.createStatement(); + String sql; + sql = "select * from information_schema.tables;"; + ResultSet rs = stmt.executeQuery(sql); - //Get the data from the result set. - while(rs.next()){ - //Retrieve two columns. - String catalog = rs.getString("table_catalog"); - String name = rs.getString("table_name"); + // Get the data from the result set. + while (rs.next()) { + // Retrieve two columns. + String catalog = rs.getString("table_catalog"); + String name = rs.getString("table_name"); - //Display values. - System.out.print("Catalog: " + catalog); - System.out.println(", Name: " + name); - } - rs.close(); - stmt.close(); - conn.close(); - }catch(Exception ex){ - //For convenience, handle all errors here. - ex.printStackTrace(); - }finally{ - //Finally block to close resources. - try{ - if(stmt!=null) - stmt.close(); - }catch(Exception ex){ - }// nothing we can do - try{ - if(conn!=null) - conn.close(); - }catch(Exception ex){ - ex.printStackTrace(); - } - } - System.out.println("Finished connectivity test."); - } + // Display values. + System.out.print("Catalog: " + catalog); + System.out.println(", Name: " + name); + } + rs.close(); + stmt.close(); + conn.close(); + } catch (Exception ex) { + // For convenience, handle all errors here. + ex.printStackTrace(); + } finally { + // Finally block to close resources. + try { + if (stmt != null) + stmt.close(); + } catch (Exception ex) { + } // nothing we can do + try { + if (conn != null) + conn.close(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + System.out.println("Finished connectivity test."); + } } diff --git a/java/example_code/redshift/CreateAndDescribeSnapshot.java b/java/example_code/redshift/CreateAndDescribeSnapshot.java index c879560b3c6..c9fa3036360 100644 --- a/java/example_code/redshift/CreateAndDescribeSnapshot.java +++ b/java/example_code/redshift/CreateAndDescribeSnapshot.java @@ -1,37 +1,12 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[CreateAndDescribeSnapshot demonstrates how to create an Amazon Redshift cluster snapshot and describe existing snapshots.] -// snippet-service:[redshift] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Redshift] -// snippet-keyword:[Code Sample] -// snippet-keyword:[CreateClusterSnapshot] -// snippet-keyword:[DeleteClusterSnapshot] -// snippet-keyword:[DescribeClusterSnapshots] -// snippet-sourcetype:[full-example] - -// snippet-sourcedate:[2015-02-19] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[redshift.java.CreateAndDescribeSnapshot.complete] import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; - import com.amazonaws.services.redshift.model.*; public class CreateAndDescribeSnapshot { @@ -42,18 +17,19 @@ public class CreateAndDescribeSnapshot { public static void main(String[] args) throws IOException { - // Default client using the {@link com.amazonaws.auth.DefaultAWSCredentialsProviderChain} + // Default client using the {@link + // com.amazonaws.auth.DefaultAWSCredentialsProviderChain} client = AmazonRedshiftClientBuilder.defaultClient(); try { - // Unique snapshot identifier - String snapshotId = "my-snapshot-" + (new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss")).format(new Date()); + // Unique snapshot identifier + String snapshotId = "my-snapshot-" + (new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss")).format(new Date()); - Date createDate = createManualSnapshot(snapshotId); - waitForSnapshotAvailable(snapshotId); - describeSnapshots(); - deleteManualSnapshotsBefore(createDate); - describeSnapshots(); + Date createDate = createManualSnapshot(snapshotId); + waitForSnapshotAvailable(snapshotId); + describeSnapshots(); + deleteManualSnapshotsBefore(createDate); + describeSnapshots(); } catch (Exception e) { System.err.println("Operation failed: " + e.getMessage()); @@ -63,8 +39,8 @@ public static void main(String[] args) throws IOException { private static Date createManualSnapshot(String snapshotId) { CreateClusterSnapshotRequest request = new CreateClusterSnapshotRequest() - .withClusterIdentifier(clusterIdentifier) - .withSnapshotIdentifier(snapshotId); + .withClusterIdentifier(clusterIdentifier) + .withSnapshotIdentifier(snapshotId); Snapshot snapshot = client.createClusterSnapshot(request); System.out.format("Created cluster snapshot: %s\n", snapshotId); return snapshot.getSnapshotCreateTime(); @@ -73,7 +49,7 @@ private static Date createManualSnapshot(String snapshotId) { private static void describeSnapshots() { DescribeClusterSnapshotsRequest request = new DescribeClusterSnapshotsRequest() - .withClusterIdentifier(clusterIdentifier); + .withClusterIdentifier(clusterIdentifier); DescribeClusterSnapshotsResult result = client.describeClusterSnapshots(request); printResultSnapshots(result); @@ -82,15 +58,15 @@ private static void describeSnapshots() { private static void deleteManualSnapshotsBefore(Date creationDate) { DescribeClusterSnapshotsRequest request = new DescribeClusterSnapshotsRequest() - .withEndTime(creationDate) - .withClusterIdentifier(clusterIdentifier) - .withSnapshotType("manual"); + .withEndTime(creationDate) + .withClusterIdentifier(clusterIdentifier) + .withSnapshotType("manual"); DescribeClusterSnapshotsResult result = client.describeClusterSnapshots(request); for (Snapshot s : result.getSnapshots()) { DeleteClusterSnapshotRequest deleteRequest = new DeleteClusterSnapshotRequest() - .withSnapshotIdentifier(s.getSnapshotIdentifier()); + .withSnapshotIdentifier(s.getSnapshotIdentifier()); Snapshot deleteResult = client.deleteClusterSnapshot(deleteRequest); System.out.format("Deleted snapshot %s\n", deleteResult.getSnapshotIdentifier()); } @@ -110,15 +86,15 @@ private static Boolean waitForSnapshotAvailable(String snapshotId) throws Interr Boolean snapshotAvailable = false; System.out.println("Waiting for snapshot to become available."); while (!snapshotAvailable) { - DescribeClusterSnapshotsResult result = client.describeClusterSnapshots(new DescribeClusterSnapshotsRequest() - .withSnapshotIdentifier(snapshotId)); + DescribeClusterSnapshotsResult result = client + .describeClusterSnapshots(new DescribeClusterSnapshotsRequest() + .withSnapshotIdentifier(snapshotId)); String status = (result.getSnapshots()).get(0).getStatus(); if (status.equalsIgnoreCase("available")) { snapshotAvailable = true; - } - else { + } else { System.out.print("."); - Thread.sleep(sleepTime*1000); + Thread.sleep(sleepTime * 1000); } } return snapshotAvailable; diff --git a/java/example_code/redshift/CreateAndModifyCluster.java b/java/example_code/redshift/CreateAndModifyCluster.java index 77ca8be5073..714884f6632 100644 --- a/java/example_code/redshift/CreateAndModifyCluster.java +++ b/java/example_code/redshift/CreateAndModifyCluster.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * @@ -12,18 +14,6 @@ * specific language governing permissions and limitations under the License. */ -// snippet-sourcedescription:[CreateAndModifyCluster demonstrates how to create and modify an Amazon Redshift cluster.] -// snippet-service:[redshift] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Redshift] -// snippet-keyword:[Code Sample] -// snippet-keyword:[CreateCluster] -// snippet-keyword:[DescribeClusters] -// snippet-keyword:[ModifyCluster] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-02-01] -// snippet-sourceauthor:[AWS] // snippet-start:[redshift.java.CreateAndModifyCluster.complete] package com.amazonaws.services.redshift; @@ -43,7 +33,8 @@ public class CreateAndModifyCluster { public static void main(String[] args) throws IOException { - // Default client using the {@link com.amazonaws.auth.DefaultAWSCredentialsProviderChain} + // Default client using the {@link + // com.amazonaws.auth.DefaultAWSCredentialsProviderChain} client = AmazonRedshiftClientBuilder.defaultClient(); try { @@ -68,7 +59,6 @@ private static void createCluster() { .withNumberOfNodes(2) .withClusterSubnetGroupName("subnetgroup1"); - Cluster createResponse = client.createCluster(request); System.out.println("Created cluster " + createResponse.getClusterIdentifier()); } @@ -91,16 +81,15 @@ private static void modifyCluster() { } - private static void printResult(DescribeClustersResult result) - { - if (result == null) - { + private static void printResult(DescribeClustersResult result) { + if (result == null) { System.out.println("Describe clusters result is null."); return; } System.out.println("Cluster property:"); - System.out.format("Preferred Maintenance Window: %s\n", result.getClusters().get(0).getPreferredMaintenanceWindow()); + System.out.format("Preferred Maintenance Window: %s\n", + result.getClusters().get(0).getPreferredMaintenanceWindow()); } private static void waitForClusterReady() throws InterruptedException { @@ -108,15 +97,14 @@ private static void waitForClusterReady() throws InterruptedException { System.out.println("Waiting for cluster to become available."); while (!clusterReady) { DescribeClustersResult result = client.describeClusters(new DescribeClustersRequest() - .withClusterIdentifier(clusterIdentifier)); + .withClusterIdentifier(clusterIdentifier)); String status = (result.getClusters()).get(0).getClusterStatus(); if (status.equalsIgnoreCase("available")) { clusterReady = true; - } - else { + } else { System.out.print("."); - Thread.sleep(sleepTime*1000); + Thread.sleep(sleepTime * 1000); } } } diff --git a/java/example_code/redshift/CreateAndModifyClusterParameterGroup.java b/java/example_code/redshift/CreateAndModifyClusterParameterGroup.java index f769276a17f..3d9febc6b63 100644 --- a/java/example_code/redshift/CreateAndModifyClusterParameterGroup.java +++ b/java/example_code/redshift/CreateAndModifyClusterParameterGroup.java @@ -1,29 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[CreateAndModifyClusterParameterGroup demonstrates how to create and modify an Amazon Redshift parameter group.] -// snippet-service:[redshift] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Redshift] -// snippet-keyword:[Code Sample] -// snippet-keyword:[CreateClusterParameterGroup] -// snippet-keyword:[DescribeClusterParameterGroups] -// snippet-keyword:[ModifyClusterParameterGroup] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-02-01] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[redshift.java.CreateAndModifyClusterParameterGroup.complete] package com.amazonaws.services.redshift; @@ -32,10 +9,8 @@ import java.util.ArrayList; import java.util.List; - import com.amazonaws.services.redshift.model.*; - public class CreateAndModifyClusterParameterGroup { public static AmazonRedshift client; @@ -46,65 +21,67 @@ public class CreateAndModifyClusterParameterGroup { public static void main(String[] args) throws IOException { - // Default client using the {@link com.amazonaws.auth.DefaultAWSCredentialsProviderChain} - client = AmazonRedshiftClientBuilder.defaultClient(); + // Default client using the {@link + // com.amazonaws.auth.DefaultAWSCredentialsProviderChain} + client = AmazonRedshiftClientBuilder.defaultClient(); try { - createClusterParameterGroup(); - modifyClusterParameterGroup(); - associateParameterGroupWithCluster(); - describeClusterParameterGroups(); + createClusterParameterGroup(); + modifyClusterParameterGroup(); + associateParameterGroupWithCluster(); + describeClusterParameterGroups(); } catch (Exception e) { System.err.println("Operation failed: " + e.getMessage()); } } private static void createClusterParameterGroup() { - CreateClusterParameterGroupRequest request = new CreateClusterParameterGroupRequest() - .withDescription("my cluster parameter group") - .withParameterGroupName(clusterParameterGroupName) - .withParameterGroupFamily(parameterGroupFamily); - client.createClusterParameterGroup(request); - System.out.println("Created cluster parameter group."); + CreateClusterParameterGroupRequest request = new CreateClusterParameterGroupRequest() + .withDescription("my cluster parameter group") + .withParameterGroupName(clusterParameterGroupName) + .withParameterGroupFamily(parameterGroupFamily); + client.createClusterParameterGroup(request); + System.out.println("Created cluster parameter group."); } private static void describeClusterParameterGroups() { - DescribeClusterParameterGroupsResult result = client.describeClusterParameterGroups(); - printResultClusterParameterGroups(result); + DescribeClusterParameterGroupsResult result = client.describeClusterParameterGroups(); + printResultClusterParameterGroups(result); } private static void modifyClusterParameterGroup() { - List parameters = new ArrayList(); - parameters.add(new Parameter() - .withParameterName("extra_float_digits") - .withParameterValue("2")); - // Replace WLM configuration. The new configuration defines a queue (in addition to the default). - parameters.add(new Parameter() - .withParameterName("wlm_json_configuration") - .withParameterValue("[{\"user_group\":[\"example_user_group1\"],\"query_group\":[\"example_query_group1\"],\"query_concurrency\":7},{\"query_concurrency\":5}]")); - - ModifyClusterParameterGroupRequest request = new ModifyClusterParameterGroupRequest() - .withParameterGroupName(clusterParameterGroupName) - .withParameters(parameters); - client.modifyClusterParameterGroup(request); + List parameters = new ArrayList(); + parameters.add(new Parameter() + .withParameterName("extra_float_digits") + .withParameterValue("2")); + // Replace WLM configuration. The new configuration defines a queue (in addition + // to the default). + parameters.add(new Parameter() + .withParameterName("wlm_json_configuration") + .withParameterValue( + "[{\"user_group\":[\"example_user_group1\"],\"query_group\":[\"example_query_group1\"],\"query_concurrency\":7},{\"query_concurrency\":5}]")); + + ModifyClusterParameterGroupRequest request = new ModifyClusterParameterGroupRequest() + .withParameterGroupName(clusterParameterGroupName) + .withParameters(parameters); + client.modifyClusterParameterGroup(request); } private static void associateParameterGroupWithCluster() { ModifyClusterRequest request = new ModifyClusterRequest() - .withClusterIdentifier(clusterIdentifier) - .withClusterParameterGroupName(clusterParameterGroupName); + .withClusterIdentifier(clusterIdentifier) + .withClusterParameterGroupName(clusterParameterGroupName); Cluster result = client.modifyCluster(request); System.out.format("Parameter Group %s is used for Cluster %s\n", clusterParameterGroupName, result.getClusterParameterGroups().get(0).getParameterGroupName()); } - private static void printResultClusterParameterGroups(DescribeClusterParameterGroupsResult result) - { - if (result == null) - { + + private static void printResultClusterParameterGroups(DescribeClusterParameterGroupsResult result) { + if (result == null) { System.out.println("\nDescribe cluster parameter groups result is null."); return; } @@ -120,16 +97,15 @@ private static void printResultClusterParameterGroups(DescribeClusterParameterGr private static void describeClusterParameters(String parameterGroupName) { DescribeClusterParametersRequest request = new DescribeClusterParametersRequest() - .withParameterGroupName(parameterGroupName); + .withParameterGroupName(parameterGroupName); DescribeClusterParametersResult result = client.describeClusterParameters(request); printResultClusterParameters(result, parameterGroupName); } - private static void printResultClusterParameters(DescribeClusterParametersResult result, String parameterGroupName) - { - if (result == null) - { + private static void printResultClusterParameters(DescribeClusterParametersResult result, + String parameterGroupName) { + if (result == null) { System.out.println("\nCluster parameters is null."); return; } @@ -137,9 +113,12 @@ private static void printResultClusterParameters(DescribeClusterParametersResult System.out.format("\nPrinting cluster parameters for \"%s\"\n", parameterGroupName); for (Parameter parameter : result.getParameters()) { System.out.println(" Name: " + parameter.getParameterName() + ", Value: " + parameter.getParameterValue()); - System.out.println(" DataType: " + parameter.getDataType() + ", MinEngineVersion: " + parameter.getMinimumEngineVersion()); - System.out.println(" AllowedValues: " + parameter.getAllowedValues() + ", Source: " + parameter.getSource()); - System.out.println(" IsModifiable: " + parameter.getIsModifiable() + ", Description: " + parameter.getDescription()); + System.out.println(" DataType: " + parameter.getDataType() + ", MinEngineVersion: " + + parameter.getMinimumEngineVersion()); + System.out + .println(" AllowedValues: " + parameter.getAllowedValues() + ", Source: " + parameter.getSource()); + System.out.println( + " IsModifiable: " + parameter.getIsModifiable() + ", Description: " + parameter.getDescription()); } } } diff --git a/java/example_code/redshift/CreateAndModifyClusterSecurityGroup.java b/java/example_code/redshift/CreateAndModifyClusterSecurityGroup.java index e2bdb75ad8d..121e4f8fd28 100644 --- a/java/example_code/redshift/CreateAndModifyClusterSecurityGroup.java +++ b/java/example_code/redshift/CreateAndModifyClusterSecurityGroup.java @@ -1,28 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[CreateAndModifyClusterSecurityGroup demonstrates how to create and modify an Amazon Redshift security group.] -// snippet-service:[redshift] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Redshift] -// snippet-keyword:[Code Sample] -// snippet-keyword:[CreateClusterSecurityGroup] -// snippet-keyword:[DescribeClusterSecurityGroups] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-02-01] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[redshift.java.CreateAndModifyClusterSecurityGroup.complete] package com.amazonaws.services.redshift; @@ -33,7 +11,6 @@ import com.amazonaws.services.redshift.model.*; - public class CreateAndModifyClusterSecurityGroup { public static AmazonRedshift client; @@ -43,14 +20,15 @@ public class CreateAndModifyClusterSecurityGroup { public static void main(String[] args) throws IOException { - // Default client using the {@link com.amazonaws.auth.DefaultAWSCredentialsProviderChain} - client = AmazonRedshiftClientBuilder.defaultClient(); + // Default client using the {@link + // com.amazonaws.auth.DefaultAWSCredentialsProviderChain} + client = AmazonRedshiftClientBuilder.defaultClient(); try { - createClusterSecurityGroup(); - describeClusterSecurityGroups(); - addIngressRules(); - associateSecurityGroupWithCluster(); + createClusterSecurityGroup(); + describeClusterSecurityGroups(); + addIngressRules(); + associateSecurityGroupWithCluster(); } catch (Exception e) { System.err.println("Operation failed: " + e.getMessage()); } @@ -58,8 +36,8 @@ public static void main(String[] args) throws IOException { private static void createClusterSecurityGroup() { CreateClusterSecurityGroupRequest request = new CreateClusterSecurityGroupRequest() - .withDescription("my cluster security group") - .withClusterSecurityGroupName(clusterSecurityGroupName); + .withDescription("my cluster security group") + .withClusterSecurityGroupName(clusterSecurityGroupName); client.createClusterSecurityGroup(request); System.out.format("Created cluster security group: '%s'\n", clusterSecurityGroupName); @@ -68,15 +46,15 @@ private static void createClusterSecurityGroup() { private static void addIngressRules() { AuthorizeClusterSecurityGroupIngressRequest request = new AuthorizeClusterSecurityGroupIngressRequest() - .withClusterSecurityGroupName(clusterSecurityGroupName) - .withCIDRIP("192.168.40.5/32"); + .withClusterSecurityGroupName(clusterSecurityGroupName) + .withCIDRIP("192.168.40.5/32"); ClusterSecurityGroup result = client.authorizeClusterSecurityGroupIngress(request); request = new AuthorizeClusterSecurityGroupIngressRequest() - .withClusterSecurityGroupName(clusterSecurityGroupName) - .withEC2SecurityGroupName("default") - .withEC2SecurityGroupOwnerId(ownerID); + .withClusterSecurityGroupName(clusterSecurityGroupName) + .withEC2SecurityGroupName("default") + .withEC2SecurityGroupOwnerId(ownerID); result = client.authorizeClusterSecurityGroupIngress(request); System.out.format("\nAdded ingress rules to security group '%s'\n", clusterSecurityGroupName); printResultSecurityGroup(result); @@ -86,11 +64,10 @@ private static void associateSecurityGroupWithCluster() { // Get existing security groups used by the cluster. DescribeClustersRequest request = new DescribeClustersRequest() - .withClusterIdentifier(clusterIdentifier); + .withClusterIdentifier(clusterIdentifier); DescribeClustersResult result = client.describeClusters(request); - List membershipList = - result.getClusters().get(0).getClusterSecurityGroups(); + List membershipList = result.getClusters().get(0).getClusterSecurityGroups(); List secGroupNames = new ArrayList(); for (ClusterSecurityGroupMembership mem : membershipList) { @@ -101,12 +78,13 @@ private static void associateSecurityGroupWithCluster() { // Apply the change to the cluster. ModifyClusterRequest request2 = new ModifyClusterRequest() - .withClusterIdentifier(clusterIdentifier) - .withClusterSecurityGroups(secGroupNames); + .withClusterIdentifier(clusterIdentifier) + .withClusterSecurityGroups(secGroupNames); Cluster result2 = client.modifyCluster(request2); - System.out.format("\nAssociated security group '%s' to cluster '%s'.", clusterSecurityGroupName, clusterIdentifier); - } + System.out.format("\nAssociated security group '%s' to cluster '%s'.", clusterSecurityGroupName, + clusterIdentifier); + } private static void describeClusterSecurityGroups() { DescribeClusterSecurityGroupsRequest request = new DescribeClusterSecurityGroupsRequest(); @@ -115,24 +93,24 @@ private static void describeClusterSecurityGroups() { printResultSecurityGroups(result.getClusterSecurityGroups()); } - private static void printResultSecurityGroups(List groups) - { - if (groups == null) - { + private static void printResultSecurityGroups(List groups) { + if (groups == null) { System.out.println("\nDescribe cluster security groups result is null."); return; } System.out.println("\nPrinting security group results:"); - for (ClusterSecurityGroup group : groups) - { + for (ClusterSecurityGroup group : groups) { printResultSecurityGroup(group); } } + private static void printResultSecurityGroup(ClusterSecurityGroup group) { - System.out.format("\nName: '%s', Description: '%s'\n", group.getClusterSecurityGroupName(), group.getDescription()); + System.out.format("\nName: '%s', Description: '%s'\n", group.getClusterSecurityGroupName(), + group.getDescription()); for (EC2SecurityGroup g : group.getEC2SecurityGroups()) { - System.out.format("EC2group: '%s', '%s', '%s'\n", g.getEC2SecurityGroupName(), g.getEC2SecurityGroupOwnerId(), g.getStatus()); + System.out.format("EC2group: '%s', '%s', '%s'\n", g.getEC2SecurityGroupName(), + g.getEC2SecurityGroupOwnerId(), g.getStatus()); } for (IPRange range : group.getIPRanges()) { System.out.format("IPRanges: '%s', '%s'\n", range.getCIDRIP(), range.getStatus()); diff --git a/java/example_code/redshift/CreateAndModifyClusterSubnetGroup.java b/java/example_code/redshift/CreateAndModifyClusterSubnetGroup.java index 8bc1f5012bd..59b43a71658 100644 --- a/java/example_code/redshift/CreateAndModifyClusterSubnetGroup.java +++ b/java/example_code/redshift/CreateAndModifyClusterSubnetGroup.java @@ -1,29 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[CreateAndModifyClusterSubnetGroup demonstrates how to create and modify an Amazon Redshift subnet group.] -// snippet-service:[redshift] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Redshift] -// snippet-keyword:[Code Sample] -// snippet-keyword:[CreateClusterSubnetGroup] -// snippet-keyword:[DescribeClusterSubnetGroups] -// snippet-sourcetype:[full-example] - -// snippet-sourcedate:[2019-02-01] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[redshift.java.CreateAndModifyClusterSubnetGroup.complete] package com.amazonaws.services.redshift; @@ -44,13 +21,14 @@ public class CreateAndModifyClusterSubnetGroup { public static void main(String[] args) throws IOException { - // Default client using the {@link com.amazonaws.auth.DefaultAWSCredentialsProviderChain} - client = AmazonRedshiftClientBuilder.defaultClient(); + // Default client using the {@link + // com.amazonaws.auth.DefaultAWSCredentialsProviderChain} + client = AmazonRedshiftClientBuilder.defaultClient(); try { - createClusterSubnetGroup(); - describeClusterSubnetGroups(); - modifyClusterSubnetGroup(); + createClusterSubnetGroup(); + describeClusterSubnetGroups(); + modifyClusterSubnetGroup(); } catch (Exception e) { System.err.println("Operation failed: " + e.getMessage()); } @@ -58,9 +36,9 @@ public static void main(String[] args) throws IOException { private static void createClusterSubnetGroup() { CreateClusterSubnetGroupRequest request = new CreateClusterSubnetGroupRequest() - .withClusterSubnetGroupName(clusterSubnetGroupName) - .withDescription("my cluster subnet group") - .withSubnetIds(subnetId1); + .withClusterSubnetGroupName(clusterSubnetGroupName) + .withDescription("my cluster subnet group") + .withSubnetIds(subnetId1); client.createClusterSubnetGroup(request); System.out.println("Created cluster subnet group: " + clusterSubnetGroupName); } @@ -68,10 +46,11 @@ private static void createClusterSubnetGroup() { private static void modifyClusterSubnetGroup() { // Get existing subnet list. DescribeClusterSubnetGroupsRequest request1 = new DescribeClusterSubnetGroupsRequest() - .withClusterSubnetGroupName(clusterSubnetGroupName); + .withClusterSubnetGroupName(clusterSubnetGroupName); DescribeClusterSubnetGroupsResult result1 = client.describeClusterSubnetGroups(request1); List subnetNames = new ArrayList(); - // We can work with just the first group returned since we requested info about one group. + // We can work with just the first group returned since we requested info about + // one group. for (Subnet subnet : result1.getClusterSubnetGroups().get(0).getSubnets()) { subnetNames.add(subnet.getSubnetIdentifier()); } @@ -79,36 +58,33 @@ private static void modifyClusterSubnetGroup() { subnetNames.add(subnetId2); ModifyClusterSubnetGroupRequest request = new ModifyClusterSubnetGroupRequest() - .withClusterSubnetGroupName(clusterSubnetGroupName) - .withSubnetIds(subnetNames); + .withClusterSubnetGroupName(clusterSubnetGroupName) + .withSubnetIds(subnetNames); ClusterSubnetGroup result2 = client.modifyClusterSubnetGroup(request); System.out.println("\nSubnet group modified."); printResultSubnetGroup(result2); } - private static void describeClusterSubnetGroups() { DescribeClusterSubnetGroupsRequest request = new DescribeClusterSubnetGroupsRequest() - .withClusterSubnetGroupName(clusterSubnetGroupName); + .withClusterSubnetGroupName(clusterSubnetGroupName); - DescribeClusterSubnetGroupsResult result = client.describeClusterSubnetGroups(request); - printResultSubnetGroups(result); + DescribeClusterSubnetGroupsResult result = client.describeClusterSubnetGroups(request); + printResultSubnetGroups(result); } - private static void printResultSubnetGroups(DescribeClusterSubnetGroupsResult result) - { - if (result == null) - { + private static void printResultSubnetGroups(DescribeClusterSubnetGroupsResult result) { + if (result == null) { System.out.println("\nDescribe cluster subnet groups result is null."); return; } - for (ClusterSubnetGroup group : result.getClusterSubnetGroups()) - { + for (ClusterSubnetGroup group : result.getClusterSubnetGroups()) { printResultSubnetGroup(group); } } + private static void printResultSubnetGroup(ClusterSubnetGroup group) { System.out.format("Name: %s, Description: %s\n", group.getClusterSubnetGroupName(), group.getDescription()); for (Subnet subnet : group.getSubnets()) { diff --git a/java/example_code/redshift/ListAndPurchaseReservedNodeOffering.java b/java/example_code/redshift/ListAndPurchaseReservedNodeOffering.java index 5a952c4ff11..63bad03ac85 100644 --- a/java/example_code/redshift/ListAndPurchaseReservedNodeOffering.java +++ b/java/example_code/redshift/ListAndPurchaseReservedNodeOffering.java @@ -1,29 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[ListAndPurchaseReservedNodeOffering demonstrates how to list and purchase Amazon Redshift reserved node offerings.] -// snippet-service:[redshift] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Redshift] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DescribeReservedNodeOfferings] -// snippet-keyword:[PurchaseReservedNodeOffering] -// snippet-keyword:[ReservedNode] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[redshift.java.ListAndPurchaseReservedNodeOffering.complete] package com.amazonaws.services.redshift; @@ -45,14 +22,14 @@ public class ListAndPurchaseReservedNodeOffering { public static void main(String[] args) throws IOException { - // Default client using the {@link com.amazonaws.auth.DefaultAWSCredentialsProviderChain} - client = AmazonRedshiftClientBuilder.defaultClient(); - + // Default client using the {@link + // com.amazonaws.auth.DefaultAWSCredentialsProviderChain} + client = AmazonRedshiftClientBuilder.defaultClient(); try { - listReservedNodes(); - findReservedNodeOffer(); - purchaseReservedNodeOffer(); + listReservedNodes(); + findReservedNodeOffer(); + purchaseReservedNodeOffer(); } catch (Exception e) { System.err.println("Operation failed: " + e.getMessage()); @@ -67,21 +44,19 @@ private static void listReservedNodes() { } } - private static void findReservedNodeOffer() - { + private static void findReservedNodeOffer() { DescribeReservedNodeOfferingsRequest request = new DescribeReservedNodeOfferingsRequest(); DescribeReservedNodeOfferingsResult result = client.describeReservedNodeOfferings(request); Integer count = 0; System.out.println("\nFinding nodes to purchase."); - for (ReservedNodeOffering offering : result.getReservedNodeOfferings()) - { - if (offering.getNodeType().equals(nodeTypeToPurchase)){ + for (ReservedNodeOffering offering : result.getReservedNodeOfferings()) { + if (offering.getNodeType().equals(nodeTypeToPurchase)) { if (offering.getFixedPrice() < fixedPriceLimit) { matchingNodes.add(offering); printOfferingDetails(offering); - count +=1; + count += 1; } } } @@ -104,21 +79,17 @@ private static void purchaseReservedNodeOffer() throws IOException { System.out.println("Purchase this offering [Y or N]?"); DataInput in = new DataInputStream(System.in); String purchaseOpt = in.readLine(); - if (purchaseOpt.equalsIgnoreCase("y")){ + if (purchaseOpt.equalsIgnoreCase("y")) { try { PurchaseReservedNodeOfferingRequest request = new PurchaseReservedNodeOfferingRequest() - .withReservedNodeOfferingId(offering.getReservedNodeOfferingId()); + .withReservedNodeOfferingId(offering.getReservedNodeOfferingId()); ReservedNode reservedNode = client.purchaseReservedNodeOffering(request); printReservedNodeDetails(reservedNode); - } - catch (ReservedNodeAlreadyExistsException ex1){ - } - catch (ReservedNodeOfferingNotFoundException ex2){ - } - catch (ReservedNodeQuotaExceededException ex3){ - } - catch (Exception ex4){ + } catch (ReservedNodeAlreadyExistsException ex1) { + } catch (ReservedNodeOfferingNotFoundException ex2) { + } catch (ReservedNodeQuotaExceededException ex3) { + } catch (Exception ex4) { } } } diff --git a/java/example_code/redshift/ListEvents.java b/java/example_code/redshift/ListEvents.java index 6cd71327e73..8a3e737e0ab 100644 --- a/java/example_code/redshift/ListEvents.java +++ b/java/example_code/redshift/ListEvents.java @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[ListEvents demonstrates how to list Amazon Redshift events.] -// snippet-service:[redshift] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Redshift] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DescribeEvents] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[redshift.java.ListEvents.complete] package com.amazonaws.services.redshift; @@ -39,29 +18,30 @@ public class ListEvents { public static void main(String[] args) throws IOException { - // Default client using the {@link com.amazonaws.auth.DefaultAWSCredentialsProviderChain} + // Default client using the {@link + // com.amazonaws.auth.DefaultAWSCredentialsProviderChain} - client = AmazonRedshiftClientBuilder.defaultClient(); + client = AmazonRedshiftClientBuilder.defaultClient(); - try { - listEvents(); + try { + listEvents(); } catch (Exception e) { System.err.println("Operation failed: " + e.getMessage()); } } private static void listEvents() { - long oneWeeksAgoMilli = (new Date()).getTime() - (7L*24L*60L*60L*1000L); + long oneWeeksAgoMilli = (new Date()).getTime() - (7L * 24L * 60L * 60L * 1000L); Date oneWeekAgo = new Date(); oneWeekAgo.setTime(oneWeeksAgoMilli); String marker = null; do { DescribeEventsRequest request = new DescribeEventsRequest() - .withSourceIdentifier(clusterIdentifier) - .withSourceType(eventSourceType) - .withStartTime(oneWeekAgo) - .withMaxRecords(20); + .withSourceIdentifier(clusterIdentifier) + .withSourceType(eventSourceType) + .withStartTime(oneWeekAgo) + .withMaxRecords(20); DescribeEventsResult result = client.describeEvents(request); marker = result.getMarker(); for (Event event : result.getEvents()) { @@ -69,12 +49,10 @@ private static void listEvents() { } } while (marker != null); - } - static void printEvent(Event event) - { - if (event == null) - { + + static void printEvent(Event event) { + if (event == null) { System.out.println("\nEvent object is null."); return; } @@ -87,4 +65,4 @@ static void printEvent(Event event) } } - // snippet-end:[redshift.java.ListEvents.complete] +// snippet-end:[redshift.java.ListEvents.complete] diff --git a/java/example_code/rekognition/rekognition-collection-java-add-faces-to-collection.java b/java/example_code/rekognition/rekognition-collection-java-add-faces-to-collection.java index d9161cc17ca..c5853b255d9 100755 --- a/java/example_code/rekognition/rekognition-collection-java-add-faces-to-collection.java +++ b/java/example_code/rekognition/rekognition-collection-java-add-faces-to-collection.java @@ -1,32 +1,7 @@ -// snippet-sourcedescription:[rekognition-collection-java-add-faces-to-collection.java demonstrates how to add faces, detected in an image, to an Amazon Rekognition collection.] -// snippet-service:[rekognition] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Rekognition] -// snippet-keyword:[Code Sample] -// snippet-keyword:[IndexFaces] -// snippet-keyword:[Collection] -// snippet-keyword:[Image] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-18] -// snippet-sourceauthor:[reesch(AWS)] -// snippet-start:[rekognition.java.rekognition-collection-java-add-faces-to-collection.complete] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[rekognition.java.rekognition-collection-java-add-faces-to-collection.complete] package aws.example.rekognition.collection; import com.amazonaws.services.rekognition.AmazonRekognition; @@ -52,9 +27,9 @@ public static void main(String[] args) throws Exception { Image image = new Image() .withS3Object(new S3Object() - .withBucket(bucket) - .withName(photo)); - + .withBucket(bucket) + .withName(photo)); + IndexFacesRequest indexFacesRequest = new IndexFacesRequest() .withImage(image) .withQualityFilter(QualityFilter.AUTO) @@ -64,7 +39,7 @@ public static void main(String[] args) throws Exception { .withDetectionAttributes("DEFAULT"); IndexFacesResult indexFacesResult = rekognitionClient.indexFaces(indexFacesRequest); - + System.out.println("Results for " + photo); System.out.println("Faces indexed:"); List faceRecords = indexFacesResult.getFaceRecords(); @@ -72,7 +47,7 @@ public static void main(String[] args) throws Exception { System.out.println(" Face ID: " + faceRecord.getFace().getFaceId()); System.out.println(" Location:" + faceRecord.getFaceDetail().getBoundingBox().toString()); } - + List unindexedFaces = indexFacesResult.getUnindexedFaces(); System.out.println("Faces not indexed:"); for (UnindexedFace unindexedFace : unindexedFaces) { diff --git a/java/example_code/rekognition/rekognition-collection-java-create-collection.java b/java/example_code/rekognition/rekognition-collection-java-create-collection.java index 690dfabe3e4..9b5379911c8 100755 --- a/java/example_code/rekognition/rekognition-collection-java-create-collection.java +++ b/java/example_code/rekognition/rekognition-collection-java-create-collection.java @@ -1,30 +1,7 @@ -// snippet-sourcedescription:[rekognition-collection-java-create-collection.java demonstrates how to delete an Amazon Rekognition collection.] -// snippet-service:[rekognition] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Rekognition] -// snippet-keyword:[Code Sample] -// snippet-keyword:[CreateCollection] -// snippet-keyword:[Collection] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-18] -// snippet-sourceauthor:[reesch(AWS)] -// snippet-start:[rekognition.java.rekognition-collection-java-create-collection] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[rekognition.java.rekognition-collection-java-create-collection] package aws.example.rekognition.collection; import com.amazonaws.services.rekognition.AmazonRekognition; @@ -32,32 +9,28 @@ import com.amazonaws.services.rekognition.model.CreateCollectionRequest; import com.amazonaws.services.rekognition.model.CreateCollectionResult; - public class CreateCollection { - public static void main(String[] args) throws Exception { + public static void main(String[] args) throws Exception { + + AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient(); + // Replace collectionId with the name of the collection that you want to create. - AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient(); - - //Replace collectionId with the name of the collection that you want to create. - - String collectionId = "MyCollection"; + String collectionId = "MyCollection"; System.out.println("Creating collection: " + - collectionId ); - - CreateCollectionRequest request = new CreateCollectionRequest() - .withCollectionId(collectionId); - - CreateCollectionResult createCollectionResult = rekognitionClient.createCollection(request); - System.out.println("CollectionArn : " + - createCollectionResult.getCollectionArn()); - System.out.println("Status code : " + - createCollectionResult.getStatusCode().toString()); - - } + collectionId); + + CreateCollectionRequest request = new CreateCollectionRequest() + .withCollectionId(collectionId); + + CreateCollectionResult createCollectionResult = rekognitionClient.createCollection(request); + System.out.println("CollectionArn : " + + createCollectionResult.getCollectionArn()); + System.out.println("Status code : " + + createCollectionResult.getStatusCode().toString()); + + } } // snippet-end:[rekognition.java.rekognition-collection-java-create-collection] - - diff --git a/java/example_code/rekognition/rekognition-collection-java-delete-collection.java b/java/example_code/rekognition/rekognition-collection-java-delete-collection.java index f6980cf5ba1..24c7a69f3d8 100755 --- a/java/example_code/rekognition/rekognition-collection-java-delete-collection.java +++ b/java/example_code/rekognition/rekognition-collection-java-delete-collection.java @@ -1,59 +1,32 @@ -// snippet-sourcedescription:[rekognition-collection-java-delete-collection.java demonstrates how to delete an Amazon Rekognition collection.] -// snippet-service:[rekognition] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Rekognition] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DeleteCollection] -// snippet-keyword:[Collection] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-18] -// snippet-sourceauthor:[reesch(AWS)] -// snippet-start:[rekognition.java.rekognition-collection-java-delete-collection.complete] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[rekognition.java.rekognition-collection-java-delete-collection.complete] package aws.example.rekognition.collection; + import com.amazonaws.services.rekognition.AmazonRekognition; import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder; import com.amazonaws.services.rekognition.model.DeleteCollectionRequest; import com.amazonaws.services.rekognition.model.DeleteCollectionResult; - public class DeleteCollection { - public static void main(String[] args) throws Exception { + public static void main(String[] args) throws Exception { - AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient(); - // Replace collectionId with the ID of the collection that you want to delete. - String collectionId = "MyCollection"; + AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient(); + // Replace collectionId with the ID of the collection that you want to delete. + String collectionId = "MyCollection"; - System.out.println("Deleting collections"); - - DeleteCollectionRequest request = new DeleteCollectionRequest() - .withCollectionId(collectionId); - DeleteCollectionResult deleteCollectionResult = rekognitionClient.deleteCollection(request); - - System.out.println(collectionId + ": " + deleteCollectionResult.getStatusCode() - .toString()); + System.out.println("Deleting collections"); - } + DeleteCollectionRequest request = new DeleteCollectionRequest() + .withCollectionId(collectionId); + DeleteCollectionResult deleteCollectionResult = rekognitionClient.deleteCollection(request); -} -// snippet-end:[rekognition.java.rekognition-collection-java-delete-collection.complete] - + System.out.println(collectionId + ": " + deleteCollectionResult.getStatusCode() + .toString()); - + } +} +// snippet-end:[rekognition.java.rekognition-collection-java-delete-collection.complete] diff --git a/java/example_code/rekognition/rekognition-collection-java-describe-collection.java b/java/example_code/rekognition/rekognition-collection-java-describe-collection.java index 4019146c238..1e87d489d15 100644 --- a/java/example_code/rekognition/rekognition-collection-java-describe-collection.java +++ b/java/example_code/rekognition/rekognition-collection-java-describe-collection.java @@ -1,30 +1,7 @@ -// snippet-sourcedescription:[rekognition-collection-java-describe-collection.java demonstrates how to get a description of an Amazon Rekognition collection.] -// snippet-service:[rekognition] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Rekognition] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DescribeCollection] -// snippet-keyword:[Collection] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-18] -// snippet-sourceauthor:[reesch(AWS)] -// snippet-start:[rekognition.java.rekognition-collection-java-describe-collection.complete] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[rekognition.java.rekognition-collection-java-describe-collection.complete] package aws.example.rekognition.collection; import com.amazonaws.services.rekognition.AmazonRekognition; @@ -32,37 +9,32 @@ import com.amazonaws.services.rekognition.model.DescribeCollectionRequest; import com.amazonaws.services.rekognition.model.DescribeCollectionResult; - public class DescribeCollection { - public static void main(String[] args) throws Exception { - //Change collectionID to the name of the desired collection. - String collectionId = "CollectionID"; - - AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient(); + public static void main(String[] args) throws Exception { + // Change collectionID to the name of the desired collection. + String collectionId = "CollectionID"; - - System.out.println("Describing collection: " + - collectionId ); - - - DescribeCollectionRequest request = new DescribeCollectionRequest() - .withCollectionId(collectionId); - - DescribeCollectionResult describeCollectionResult = rekognitionClient.describeCollection(request); - System.out.println("Collection Arn : " + - describeCollectionResult.getCollectionARN()); - System.out.println("Face count : " + - describeCollectionResult.getFaceCount().toString()); - System.out.println("Face model version : " + - describeCollectionResult.getFaceModelVersion()); - System.out.println("Created : " + - describeCollectionResult.getCreationTimestamp().toString()); + AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient(); - } + System.out.println("Describing collection: " + + collectionId); + + DescribeCollectionRequest request = new DescribeCollectionRequest() + .withCollectionId(collectionId); + + DescribeCollectionResult describeCollectionResult = rekognitionClient.describeCollection(request); + System.out.println("Collection Arn : " + + describeCollectionResult.getCollectionARN()); + System.out.println("Face count : " + + describeCollectionResult.getFaceCount().toString()); + System.out.println("Face model version : " + + describeCollectionResult.getFaceModelVersion()); + System.out.println("Created : " + + describeCollectionResult.getCreationTimestamp().toString()); + + } } // snippet-end:[rekognition.java.rekognition-collection-java-describe-collection.complete] - - diff --git a/java/example_code/rekognition/rekognition-collection-java-list-collections.java b/java/example_code/rekognition/rekognition-collection-java-list-collections.java index b803d3d5f82..1fa8a69299f 100755 --- a/java/example_code/rekognition/rekognition-collection-java-list-collections.java +++ b/java/example_code/rekognition/rekognition-collection-java-list-collections.java @@ -1,31 +1,7 @@ -// snippet-sourcedescription:[rekognition-collection-java-list-collections.java demonstrates how to list the available Amazon Rekognition collections.] -// snippet-service:[rekognition] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Rekognition] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ListCollections] -// snippet-keyword:[Collection] -// snippet-keyword:[Image] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-18] -// snippet-sourceauthor:[reesch(AWS)] -// snippet-start:[rekognition.java.rekognition-collection-java-list-collections.complete] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[rekognition.java.rekognition-collection-java-list-collections.complete] package aws.example.rekognition.collection; import java.util.List; @@ -38,9 +14,7 @@ public class ListCollections { public static void main(String[] args) throws Exception { - AmazonRekognition amazonRekognition = AmazonRekognitionClientBuilder.defaultClient(); - System.out.println("Listing collections"); int limit = 10; @@ -51,17 +25,16 @@ public static void main(String[] args) throws Exception { paginationToken = listCollectionsResult.getNextToken(); } ListCollectionsRequest listCollectionsRequest = new ListCollectionsRequest() - .withMaxResults(limit) - .withNextToken(paginationToken); - listCollectionsResult=amazonRekognition.listCollections(listCollectionsRequest); - - List < String > collectionIds = listCollectionsResult.getCollectionIds(); - for (String resultId: collectionIds) { + .withMaxResults(limit) + .withNextToken(paginationToken); + listCollectionsResult = amazonRekognition.listCollections(listCollectionsRequest); + + List collectionIds = listCollectionsResult.getCollectionIds(); + for (String resultId : collectionIds) { System.out.println(resultId); } - } while (listCollectionsResult != null && listCollectionsResult.getNextToken() != - null); - - } + } while (listCollectionsResult != null && listCollectionsResult.getNextToken() != null); + + } } // snippet-end:[rekognition.java.rekognition-collection-java-list-collections.complete] \ No newline at end of file diff --git a/java/example_code/rekognition/rekognition-collection-java-list-faces-in-collection.java b/java/example_code/rekognition/rekognition-collection-java-list-faces-in-collection.java index 9e1a9600f41..8ef332ad454 100755 --- a/java/example_code/rekognition/rekognition-collection-java-list-faces-in-collection.java +++ b/java/example_code/rekognition/rekognition-collection-java-list-faces-in-collection.java @@ -1,31 +1,9 @@ -// snippet-sourcedescription:[rekognition-collection-java-list-faces-in-collection.java demonstrates how to list the faces in an Amazon Rekognition collection.] -// snippet-service:[rekognition] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Rekognition] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ListFaces] -// snippet-keyword:[Collection] -// snippet-keyword:[Image] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-18] -// snippet-sourceauthor:[reesch(AWS)] -// snippet-start:[rekognition.java.rekognition-collection-java-list-faces-in-collection.complete] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[rekognition.java.rekognition-collection-java-list-faces-in-collection.complete] package aws.example.rekognition.collection; + import com.amazonaws.services.rekognition.AmazonRekognition; import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder; import com.amazonaws.services.rekognition.model.Face; @@ -34,14 +12,12 @@ import java.util.List; import com.fasterxml.jackson.databind.ObjectMapper; - - public class ListFacesInCollection { - // Change collectionId to the required collection. - public static final String collectionId = "MyCollection"; + // Change collectionId to the required collection. + public static final String collectionId = "MyCollection"; public static void main(String[] args) throws Exception { - + AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient(); ObjectMapper objectMapper = new ObjectMapper(); @@ -54,23 +30,20 @@ public static void main(String[] args) throws Exception { if (listFacesResult != null) { paginationToken = listFacesResult.getNextToken(); } - + ListFacesRequest listFacesRequest = new ListFacesRequest() - .withCollectionId(collectionId) - .withMaxResults(1) - .withNextToken(paginationToken); - - listFacesResult = rekognitionClient.listFaces(listFacesRequest); - List < Face > faces = listFacesResult.getFaces(); - for (Face face: faces) { + .withCollectionId(collectionId) + .withMaxResults(1) + .withNextToken(paginationToken); + + listFacesResult = rekognitionClient.listFaces(listFacesRequest); + List faces = listFacesResult.getFaces(); + for (Face face : faces) { System.out.println(objectMapper.writerWithDefaultPrettyPrinter() - .writeValueAsString(face)); + .writeValueAsString(face)); } - } while (listFacesResult != null && listFacesResult.getNextToken() != - null); + } while (listFacesResult != null && listFacesResult.getNextToken() != null); } } // snippet-end:[rekognition.java.rekognition-collection-java-list-faces-in-collection.complete] - - \ No newline at end of file diff --git a/java/example_code/rekognition/rekognition-collection-java-search-face-matching-id-collection.java b/java/example_code/rekognition/rekognition-collection-java-search-face-matching-id-collection.java index e4312fc306b..78c51196a89 100755 --- a/java/example_code/rekognition/rekognition-collection-java-search-face-matching-id-collection.java +++ b/java/example_code/rekognition/rekognition-collection-java-search-face-matching-id-collection.java @@ -1,32 +1,9 @@ -// snippet-sourcedescription:[rekognition-collection-java-search-face-matching-id-collection.java demonstrates how to search for faces in a collection that match a face ID.] -// snippet-service:[rekognition] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Rekognition] -// snippet-keyword:[Code Sample] -// snippet-keyword:[SearchFacesById] -// snippet-keyword:[Collection] -// snippet-keyword:[Image] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-18] -// snippet-sourceauthor:[reesch(AWS)] -// snippet-start:[rekognition.java.rekognition-collection-java-search-face-matching-id-collection.complete] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[rekognition.java.rekognition-collection-java-search-face-matching-id-collection.complete] package aws.example.rekognition.collection; + import com.amazonaws.services.rekognition.AmazonRekognition; import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder; import com.fasterxml.jackson.databind.ObjectMapper; @@ -35,38 +12,35 @@ import com.amazonaws.services.rekognition.model.SearchFacesResult; import java.util.List; +public class SearchFaceMatchingIdCollection { + // Replace collectionId and faceId with the values you want to use. + public static final String collectionId = "MyCollection"; + public static final String faceId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; + + public static void main(String[] args) throws Exception { + + AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient(); + + ObjectMapper objectMapper = new ObjectMapper(); + // Search collection for faces matching the face id. + + SearchFacesRequest searchFacesRequest = new SearchFacesRequest() + .withCollectionId(collectionId) + .withFaceId(faceId) + .withFaceMatchThreshold(70F) + .withMaxFaces(2); + + SearchFacesResult searchFacesByIdResult = rekognitionClient.searchFaces(searchFacesRequest); - public class SearchFaceMatchingIdCollection { - //Replace collectionId and faceId with the values you want to use. - public static final String collectionId = "MyCollection"; - public static final String faceId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; - - public static void main(String[] args) throws Exception { - - AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient(); - - ObjectMapper objectMapper = new ObjectMapper(); - // Search collection for faces matching the face id. - - SearchFacesRequest searchFacesRequest = new SearchFacesRequest() - .withCollectionId(collectionId) - .withFaceId(faceId) - .withFaceMatchThreshold(70F) - .withMaxFaces(2); - - SearchFacesResult searchFacesByIdResult = - rekognitionClient.searchFaces(searchFacesRequest); + System.out.println("Face matching faceId " + faceId); + List faceImageMatches = searchFacesByIdResult.getFaceMatches(); + for (FaceMatch face : faceImageMatches) { + System.out.println(objectMapper.writerWithDefaultPrettyPrinter() + .writeValueAsString(face)); - System.out.println("Face matching faceId " + faceId); - List < FaceMatch > faceImageMatches = searchFacesByIdResult.getFaceMatches(); - for (FaceMatch face: faceImageMatches) { - System.out.println(objectMapper.writerWithDefaultPrettyPrinter() - .writeValueAsString(face)); - - System.out.println(); - } - } + System.out.println(); + } + } } // snippet-end:[rekognition.java.rekognition-collection-java-search-face-matching-id-collection.complete] - \ No newline at end of file diff --git a/java/example_code/rekognition/rekognition-collection-java-search-face-matching-image-collection.java b/java/example_code/rekognition/rekognition-collection-java-search-face-matching-image-collection.java index b76bc0f2671..e83f98b0444 100755 --- a/java/example_code/rekognition/rekognition-collection-java-search-face-matching-image-collection.java +++ b/java/example_code/rekognition/rekognition-collection-java-search-face-matching-image-collection.java @@ -1,32 +1,9 @@ -// snippet-sourcedescription:[rekognition-collection-java-search-face-matching-image-collection.java demonstrates how to search for matching faces in an Amazon Rekognition collection.] -// snippet-service:[rekognition] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Rekognition] -// snippet-keyword:[Code Sample] -// snippet-keyword:[SearchFacesByImage] -// snippet-keyword:[Collection] -// snippet-keyword:[Image] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-18] -// snippet-sourceauthor:[reesch(AWS)] -// snippet-start:[rekognition.java.rekognition-collection-java-search-face-matching-image-collection.complete] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[rekognition.java.rekognition-collection-java-search-face-matching-image-collection.complete] package aws.example.rekognition.collection; + import com.amazonaws.services.rekognition.AmazonRekognition; import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder; import com.amazonaws.services.rekognition.model.FaceMatch; @@ -37,45 +14,41 @@ import java.util.List; import com.fasterxml.jackson.databind.ObjectMapper; - public class SearchFaceMatchingImageCollection { - //Replace bucket, collectionId and photo with your values. - public static final String collectionId = "MyCollection"; - public static final String bucket = "bucket"; - public static final String photo = "input.jpg"; - - public static void main(String[] args) throws Exception { - - AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient(); - - ObjectMapper objectMapper = new ObjectMapper(); - - // Get an image object from S3 bucket. - Image image=new Image() - .withS3Object(new S3Object() - .withBucket(bucket) - .withName(photo)); - - // Search collection for faces similar to the largest face in the image. - SearchFacesByImageRequest searchFacesByImageRequest = new SearchFacesByImageRequest() - .withCollectionId(collectionId) - .withImage(image) - .withFaceMatchThreshold(70F) - .withMaxFaces(2); - - SearchFacesByImageResult searchFacesByImageResult = - rekognitionClient.searchFacesByImage(searchFacesByImageRequest); - - System.out.println("Faces matching largest face in image from" + photo); - List < FaceMatch > faceImageMatches = searchFacesByImageResult.getFaceMatches(); - for (FaceMatch face: faceImageMatches) { - System.out.println(objectMapper.writerWithDefaultPrettyPrinter() - .writeValueAsString(face)); - System.out.println(); - } - } + // Replace bucket, collectionId and photo with your values. + public static final String collectionId = "MyCollection"; + public static final String bucket = "bucket"; + public static final String photo = "input.jpg"; + + public static void main(String[] args) throws Exception { + + AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient(); + + ObjectMapper objectMapper = new ObjectMapper(); + + // Get an image object from S3 bucket. + Image image = new Image() + .withS3Object(new S3Object() + .withBucket(bucket) + .withName(photo)); + + // Search collection for faces similar to the largest face in the image. + SearchFacesByImageRequest searchFacesByImageRequest = new SearchFacesByImageRequest() + .withCollectionId(collectionId) + .withImage(image) + .withFaceMatchThreshold(70F) + .withMaxFaces(2); + + SearchFacesByImageResult searchFacesByImageResult = rekognitionClient + .searchFacesByImage(searchFacesByImageRequest); + + System.out.println("Faces matching largest face in image from" + photo); + List faceImageMatches = searchFacesByImageResult.getFaceMatches(); + for (FaceMatch face : faceImageMatches) { + System.out.println(objectMapper.writerWithDefaultPrettyPrinter() + .writeValueAsString(face)); + System.out.println(); + } + } } // snippet-end:[rekognition.java.rekognition-collection-java-search-face-matching-image-collection.complete] - - - \ No newline at end of file diff --git a/java/example_code/rekognition/rekognition-image-java-celebrity-info.java b/java/example_code/rekognition/rekognition-image-java-celebrity-info.java index a7bf810a597..e5a10d09cad 100755 --- a/java/example_code/rekognition/rekognition-image-java-celebrity-info.java +++ b/java/example_code/rekognition/rekognition-image-java-celebrity-info.java @@ -1,58 +1,36 @@ -// snippet-sourcedescription:[rekognition-image-java-celebrity-info.java demonstrates how to get information about a detected celebrity.] -// snippet-service:[rekognition] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Rekognition] -// snippet-keyword:[Code Sample] -// snippet-keyword:[GetCelebrityInfo] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-18] -// snippet-sourceauthor:[reesch(AWS)] -// snippet-start:[rekognition.java.rekognition-image-java-celebrity-info.] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[rekognition.java.rekognition-image-java-celebrity-info.] package aws.example.rekognition.image; + import com.amazonaws.services.rekognition.AmazonRekognition; import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder; import com.amazonaws.services.rekognition.model.GetCelebrityInfoRequest; import com.amazonaws.services.rekognition.model.GetCelebrityInfoResult; - public class CelebrityInfo { public static void main(String[] args) { - //Change the value of id to an ID value returned by RecognizeCelebrities or GetCelebrityRecognition + // Change the value of id to an ID value returned by RecognizeCelebrities or + // GetCelebrityRecognition String id = "nnnnnnnn"; AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient(); GetCelebrityInfoRequest request = new GetCelebrityInfoRequest() - .withId(id); + .withId(id); System.out.println("Getting information for celebrity: " + id); - GetCelebrityInfoResult result=rekognitionClient.getCelebrityInfo(request); + GetCelebrityInfoResult result = rekognitionClient.getCelebrityInfo(request); - //Display celebrity information + // Display celebrity information System.out.println("celebrity name: " + result.getName()); System.out.println("Further information (if available):"); - for (String url: result.getUrls()){ + for (String url : result.getUrls()) { System.out.println(url); } } } // snippet-end:[rekognition.java.rekognition-image-java-celebrity-info.] - \ No newline at end of file diff --git a/java/example_code/rekognition/rekognition-image-java-compare-faces.java b/java/example_code/rekognition/rekognition-image-java-compare-faces.java index ce6df3e5196..bd021752e01 100755 --- a/java/example_code/rekognition/rekognition-image-java-compare-faces.java +++ b/java/example_code/rekognition/rekognition-image-java-compare-faces.java @@ -1,32 +1,9 @@ -// snippet-sourcedescription:[rekognition-image-java-compare-faces.java demonstrates how to compare 2 faces.] -// snippet-service:[rekognition] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Rekognition] -// snippet-keyword:[Code Sample] -// snippet-keyword:[CompareFaces] -// snippet-keyword:[Image] -// snippet-keyword:[Local] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-18] -// snippet-sourceauthor:[reesch(AWS)] -// snippet-start:[rekognition.java.rekognition-image-java-compare-faces] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[rekognition.java.rekognition-image-java-compare-faces] package aws.example.rekognition.image; + import com.amazonaws.services.rekognition.AmazonRekognition; import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder; import com.amazonaws.services.rekognition.model.Image; @@ -44,65 +21,60 @@ public class CompareFaces { - public static void main(String[] args) throws Exception{ - Float similarityThreshold = 70F; - //Replace sourceFile and targetFile with the image files you want to compare. - String sourceImage = "source.jpg"; - String targetImage = "target.jpg"; - ByteBuffer sourceImageBytes=null; - ByteBuffer targetImageBytes=null; - - AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient(); + public static void main(String[] args) throws Exception { + Float similarityThreshold = 70F; + // Replace sourceFile and targetFile with the image files you want to compare. + String sourceImage = "source.jpg"; + String targetImage = "target.jpg"; + ByteBuffer sourceImageBytes = null; + ByteBuffer targetImageBytes = null; - //Load source and target images and create input parameters - try (InputStream inputStream = new FileInputStream(new File(sourceImage))) { - sourceImageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream)); - } - catch(Exception e) - { - System.out.println("Failed to load source image " + sourceImage); - System.exit(1); - } - try (InputStream inputStream = new FileInputStream(new File(targetImage))) { - targetImageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream)); - } - catch(Exception e) - { - System.out.println("Failed to load target images: " + targetImage); - System.exit(1); - } + AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient(); - Image source=new Image() - .withBytes(sourceImageBytes); - Image target=new Image() - .withBytes(targetImageBytes); + // Load source and target images and create input parameters + try (InputStream inputStream = new FileInputStream(new File(sourceImage))) { + sourceImageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream)); + } catch (Exception e) { + System.out.println("Failed to load source image " + sourceImage); + System.exit(1); + } + try (InputStream inputStream = new FileInputStream(new File(targetImage))) { + targetImageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream)); + } catch (Exception e) { + System.out.println("Failed to load target images: " + targetImage); + System.exit(1); + } - CompareFacesRequest request = new CompareFacesRequest() - .withSourceImage(source) - .withTargetImage(target) - .withSimilarityThreshold(similarityThreshold); + Image source = new Image() + .withBytes(sourceImageBytes); + Image target = new Image() + .withBytes(targetImageBytes); - // Call operation - CompareFacesResult compareFacesResult=rekognitionClient.compareFaces(request); + CompareFacesRequest request = new CompareFacesRequest() + .withSourceImage(source) + .withTargetImage(target) + .withSimilarityThreshold(similarityThreshold); + // Call operation + CompareFacesResult compareFacesResult = rekognitionClient.compareFaces(request); - // Display results - List faceDetails = compareFacesResult.getFaceMatches(); - for (CompareFacesMatch match: faceDetails){ - ComparedFace face= match.getFace(); - BoundingBox position = face.getBoundingBox(); - System.out.println("Face at " + position.getLeft().toString() - + " " + position.getTop() - + " matches with " + face.getConfidence().toString() - + "% confidence."); + // Display results + List faceDetails = compareFacesResult.getFaceMatches(); + for (CompareFacesMatch match : faceDetails) { + ComparedFace face = match.getFace(); + BoundingBox position = face.getBoundingBox(); + System.out.println("Face at " + position.getLeft().toString() + + " " + position.getTop() + + " matches with " + face.getConfidence().toString() + + "% confidence."); - } - List uncompared = compareFacesResult.getUnmatchedFaces(); + } + List uncompared = compareFacesResult.getUnmatchedFaces(); - System.out.println("There was " + uncompared.size() - + " face(s) that did not match"); - System.out.println("Source image rotation: " + compareFacesResult.getSourceImageOrientationCorrection()); - System.out.println("target image rotation: " + compareFacesResult.getTargetImageOrientationCorrection()); - } + System.out.println("There was " + uncompared.size() + + " face(s) that did not match"); + System.out.println("Source image rotation: " + compareFacesResult.getSourceImageOrientationCorrection()); + System.out.println("target image rotation: " + compareFacesResult.getTargetImageOrientationCorrection()); + } } // snippet-end:[rekognition.java.rekognition-image-java-compare-faces] \ No newline at end of file diff --git a/java/example_code/rekognition/rekognition-image-java-delete-faces-from-collection.java b/java/example_code/rekognition/rekognition-image-java-delete-faces-from-collection.java index 5c92869053d..a3a797bab3d 100755 --- a/java/example_code/rekognition/rekognition-image-java-delete-faces-from-collection.java +++ b/java/example_code/rekognition/rekognition-image-java-delete-faces-from-collection.java @@ -1,31 +1,9 @@ -// snippet-sourcedescription:[rekognition-image-java-delete-faces-from-collection.java demonstrates how to delete a face from an Amazon Rekognition collection.] -// snippet-service:[rekognition] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Rekognition] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DeleteFaces] -// snippet-keyword:[Collection] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-18] -// snippet-sourceauthor:[reesch(AWS)] -// snippet-start:[rekognition.java.rekognition-image-java-delete-faces-from-collection.complete] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[rekognition.java.rekognition-image-java-delete-faces-from-collection.complete] package aws.example.rekognition.image; + import com.amazonaws.services.rekognition.AmazonRekognition; import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder; import com.amazonaws.services.rekognition.model.DeleteFacesRequest; @@ -33,36 +11,27 @@ import java.util.List; - public class DeleteFacesFromCollection { - //Change collectionID to the collection that contains the face. - //Change "xxxxxx..." to the ID of the face that you want to delete. + // Change collectionID to the collection that contains the face. + // Change "xxxxxx..." to the ID of the face that you want to delete. public static final String collectionId = "MyCollection"; - public static final String faces[] = {"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}; + public static final String faces[] = { "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" }; public static void main(String[] args) throws Exception { - + AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient(); - - + DeleteFacesRequest deleteFacesRequest = new DeleteFacesRequest() - .withCollectionId(collectionId) - .withFaceIds(faces); - - DeleteFacesResult deleteFacesResult=rekognitionClient.deleteFaces(deleteFacesRequest); - - - List < String > faceRecords = deleteFacesResult.getDeletedFaces(); + .withCollectionId(collectionId) + .withFaceIds(faces); + + DeleteFacesResult deleteFacesResult = rekognitionClient.deleteFaces(deleteFacesRequest); + + List faceRecords = deleteFacesResult.getDeletedFaces(); System.out.println(Integer.toString(faceRecords.size()) + " face(s) deleted:"); - for (String face: faceRecords) { + for (String face : faceRecords) { System.out.println("FaceID: " + face); } } } // snippet-end:[rekognition.java.rekognition-image-java-delete-faces-from-collection.complete] - - - - - - diff --git a/java/example_code/rekognition/rekognition-image-java-detect-faces.java b/java/example_code/rekognition/rekognition-image-java-detect-faces.java index 2655538e048..0409045c77e 100755 --- a/java/example_code/rekognition/rekognition-image-java-detect-faces.java +++ b/java/example_code/rekognition/rekognition-image-java-detect-faces.java @@ -1,31 +1,7 @@ -// snippet-sourcedescription:[rekognition-image-java-detect-faces.java demonstrates how to detect faces in an image loaded from an S3 Bucket.] -// snippet-service:[rekognition] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Rekognition] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DetectFaces] -// snippet-keyword:[S3 Bucket] -// snippet-keyword:[Image] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-18] -// snippet-sourceauthor:[reesch(AWS)] -// snippet-start:[rekognition.java.rekognition-image-java-detect-faces.complete] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[rekognition.java.rekognition-image-java-detect-faces.complete] package aws.example.rekognition.image; import com.amazonaws.services.rekognition.AmazonRekognition; @@ -41,10 +17,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; - public class DetectFaces { - - + public static void main(String[] args) throws Exception { // Change bucket to your S3 bucket that contains the image file. // Change photo to your image file. @@ -53,25 +27,24 @@ public static void main(String[] args) throws Exception { AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient(); - DetectFacesRequest request = new DetectFacesRequest() - .withImage(new Image() - .withS3Object(new S3Object() - .withName(photo) - .withBucket(bucket))) - .withAttributes(Attribute.ALL); + .withImage(new Image() + .withS3Object(new S3Object() + .withName(photo) + .withBucket(bucket))) + .withAttributes(Attribute.ALL); // Replace Attribute.ALL with Attribute.DEFAULT to get default values. try { DetectFacesResult result = rekognitionClient.detectFaces(request); - List < FaceDetail > faceDetails = result.getFaceDetails(); + List faceDetails = result.getFaceDetails(); - for (FaceDetail face: faceDetails) { + for (FaceDetail face : faceDetails) { if (request.getAttributes().contains("ALL")) { AgeRange ageRange = face.getAgeRange(); System.out.println("The detected face is estimated to be between " - + ageRange.getLow().toString() + " and " + ageRange.getHigh().toString() - + " years old."); + + ageRange.getLow().toString() + " and " + ageRange.getHigh().toString() + + " years old."); System.out.println("Here's the complete set of attributes:"); } else { // non-default attributes have null values. System.out.println("Here's the default set of attributes:"); @@ -89,4 +62,3 @@ public static void main(String[] args) throws Exception { } // snippet-end:[rekognition.java.rekognition-image-java-detect-faces.complete] - diff --git a/java/example_code/rekognition/rekognition-image-java-detect-labels-local-file.java b/java/example_code/rekognition/rekognition-image-java-detect-labels-local-file.java index 4497885e346..ea962672f67 100755 --- a/java/example_code/rekognition/rekognition-image-java-detect-labels-local-file.java +++ b/java/example_code/rekognition/rekognition-image-java-detect-labels-local-file.java @@ -1,32 +1,9 @@ -// snippet-sourcedescription:[rekognition-image-java-detect-labels-local-file.java demonstrates how to detect unsafe content in an image loaded from a local file.] -// snippet-service:[rekognition] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Rekognition] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DetectLabels] -// snippet-keyword:[Local] -// snippet-keyword:[Image] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-18] -// snippet-sourceauthor:[reesch(AWS)] -// snippet-start:[rekognition.java.rekognition-image-java-detect-labels-local-file.complete] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[rekognition.java.rekognition-image-java-detect-labels-local-file.complete] package aws.example.rekognition.image; + import java.io.File; import java.io.FileInputStream; import java.io.InputStream; @@ -45,15 +22,13 @@ public class DetectLabelsLocalFile { public static void main(String[] args) throws Exception { // Change photo to the path and filename of your image. - String photo="input.jpg"; - + String photo = "input.jpg"; ByteBuffer imageBytes; try (InputStream inputStream = new FileInputStream(new File(photo))) { imageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream)); } - AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient(); DetectLabelsRequest request = new DetectLabelsRequest() @@ -65,11 +40,11 @@ public static void main(String[] args) throws Exception { try { DetectLabelsResult result = rekognitionClient.detectLabels(request); - List

- * This file is 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/ - *

- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -// snippet-sourcedescription:[CrossRegionReplication.java demonstrates how to set and get cross-region replication rules.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[PUT Bucket replication] -// snippet-keyword:[GET Bucket replication] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[s3.java.cross_region_replication.complete] import com.amazonaws.AmazonServiceException; @@ -57,130 +35,140 @@ public class CrossRegionReplication { - public static void main(String[] args) throws IOException { - Regions clientRegion = Regions.DEFAULT_REGION; - String accountId = "*** Account ID ***"; - String roleName = "*** Role name ***"; - String sourceBucketName = "*** Source bucket name ***"; - String destBucketName = "*** Destination bucket name ***"; - String prefix = "Tax/"; - - String roleARN = String.format("arn:aws:iam::%s:%s", accountId, roleName); - String destinationBucketARN = "arn:aws:s3:::" + destBucketName; - - AmazonS3 s3Client = AmazonS3Client.builder() - .withCredentials(new ProfileCredentialsProvider()) - .withRegion(clientRegion) - .build(); - - createBucket(s3Client, clientRegion, sourceBucketName); - createBucket(s3Client, clientRegion, destBucketName); - assignRole(roleName, clientRegion, sourceBucketName, destBucketName); - - - try { - - - // Create the replication rule. - List andOperands = new ArrayList(); - andOperands.add(new ReplicationPrefixPredicate(prefix)); - - - Map replicationRules = new HashMap(); - replicationRules.put("ReplicationRule1", - new ReplicationRule() - .withPriority(0) - .withStatus(ReplicationRuleStatus.Enabled) - .withDeleteMarkerReplication(new DeleteMarkerReplication().withStatus(DeleteMarkerReplicationStatus.DISABLED)) - .withFilter(new ReplicationFilter().withPredicate(new ReplicationPrefixPredicate(prefix))) - .withDestinationConfig(new ReplicationDestinationConfig() - .withBucketARN(destinationBucketARN) - .withStorageClass(StorageClass.Standard))); - - // Save the replication rule to the source bucket. - s3Client.setBucketReplicationConfiguration(sourceBucketName, - new BucketReplicationConfiguration() - .withRoleARN(roleARN) - .withRules(replicationRules)); - - // Retrieve the replication configuration and verify that the configuration - // matches the rule we just set. - BucketReplicationConfiguration replicationConfig = s3Client.getBucketReplicationConfiguration(sourceBucketName); - ReplicationRule rule = replicationConfig.getRule("ReplicationRule1"); - System.out.println("Retrieved destination bucket ARN: " + rule.getDestinationConfig().getBucketARN()); - System.out.println("Retrieved priority: " + rule.getPriority()); - System.out.println("Retrieved source-bucket replication rule status: " + rule.getStatus()); - } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process - // it, so it returned an error response. - e.printStackTrace(); - } catch (SdkClientException e) { - // Amazon S3 couldn't be contacted for a response, or the client - // couldn't parse the response from Amazon S3. - e.printStackTrace(); + public static void main(String[] args) throws IOException { + Regions clientRegion = Regions.DEFAULT_REGION; + String accountId = "*** Account ID ***"; + String roleName = "*** Role name ***"; + String sourceBucketName = "*** Source bucket name ***"; + String destBucketName = "*** Destination bucket name ***"; + String prefix = "Tax/"; + + String roleARN = String.format("arn:aws:iam::%s:%s", accountId, roleName); + String destinationBucketARN = "arn:aws:s3:::" + destBucketName; + + AmazonS3 s3Client = AmazonS3Client.builder() + .withCredentials(new ProfileCredentialsProvider()) + .withRegion(clientRegion) + .build(); + + createBucket(s3Client, clientRegion, sourceBucketName); + createBucket(s3Client, clientRegion, destBucketName); + assignRole(roleName, clientRegion, sourceBucketName, destBucketName); + + try { + + // Create the replication rule. + List andOperands = new ArrayList(); + andOperands.add(new ReplicationPrefixPredicate(prefix)); + + Map replicationRules = new HashMap(); + replicationRules.put("ReplicationRule1", + new ReplicationRule() + .withPriority(0) + .withStatus(ReplicationRuleStatus.Enabled) + .withDeleteMarkerReplication( + new DeleteMarkerReplication().withStatus( + DeleteMarkerReplicationStatus.DISABLED)) + .withFilter(new ReplicationFilter().withPredicate( + new ReplicationPrefixPredicate(prefix))) + .withDestinationConfig(new ReplicationDestinationConfig() + .withBucketARN(destinationBucketARN) + .withStorageClass(StorageClass.Standard))); + + // Save the replication rule to the source bucket. + s3Client.setBucketReplicationConfiguration(sourceBucketName, + new BucketReplicationConfiguration() + .withRoleARN(roleARN) + .withRules(replicationRules)); + + // Retrieve the replication configuration and verify that the configuration + // matches the rule we just set. + BucketReplicationConfiguration replicationConfig = s3Client + .getBucketReplicationConfiguration(sourceBucketName); + ReplicationRule rule = replicationConfig.getRule("ReplicationRule1"); + System.out.println("Retrieved destination bucket ARN: " + + rule.getDestinationConfig().getBucketARN()); + System.out.println("Retrieved priority: " + rule.getPriority()); + System.out.println("Retrieved source-bucket replication rule status: " + rule.getStatus()); + } catch (AmazonServiceException e) { + // The call was transmitted successfully, but Amazon S3 couldn't process + // it, so it returned an error response. + e.printStackTrace(); + } catch (SdkClientException e) { + // Amazon S3 couldn't be contacted for a response, or the client + // couldn't parse the response from Amazon S3. + e.printStackTrace(); + } + } + + private static void createBucket(AmazonS3 s3Client, Regions region, String bucketName) { + CreateBucketRequest request = new CreateBucketRequest(bucketName, region.getName()); + s3Client.createBucket(request); + BucketVersioningConfiguration configuration = new BucketVersioningConfiguration() + .withStatus(BucketVersioningConfiguration.ENABLED); + + SetBucketVersioningConfigurationRequest enableVersioningRequest = new SetBucketVersioningConfigurationRequest( + bucketName, configuration); + s3Client.setBucketVersioningConfiguration(enableVersioningRequest); + + } + + private static void assignRole(String roleName, Regions region, String sourceBucket, String destinationBucket) { + AmazonIdentityManagement iamClient = AmazonIdentityManagementClientBuilder.standard() + .withRegion(region) + .withCredentials(new ProfileCredentialsProvider()) + .build(); + StringBuilder trustPolicy = new StringBuilder(); + trustPolicy.append("{\\r\\n "); + trustPolicy.append("\\\"Version\\\":\\\"2012-10-17\\\",\\r\\n "); + trustPolicy.append("\\\"Statement\\\":[\\r\\n {\\r\\n "); + trustPolicy.append("\\\"Effect\\\":\\\"Allow\\\",\\r\\n \\\"Principal\\\":{\\r\\n "); + trustPolicy.append("\\\"Service\\\":\\\"s3.amazonaws.com\\\"\\r\\n },\\r\\n "); + trustPolicy.append("\\\"Action\\\":\\\"sts:AssumeRole\\\"\\r\\n }\\r\\n ]\\r\\n}"); + + CreateRoleRequest createRoleRequest = new CreateRoleRequest() + .withRoleName(roleName) + .withAssumeRolePolicyDocument(trustPolicy.toString()); + + iamClient.createRole(createRoleRequest); + + StringBuilder permissionPolicy = new StringBuilder(); + permissionPolicy.append( + "{\\r\\n \\\"Version\\\":\\\"2012-10-17\\\",\\r\\n \\\"Statement\\\":[\\r\\n {\\r\\n "); + permissionPolicy.append( + "\\\"Effect\\\":\\\"Allow\\\",\\r\\n \\\"Action\\\":[\\r\\n "); + permissionPolicy.append("\\\"s3:GetObjectVersionForReplication\\\",\\r\\n "); + permissionPolicy.append( + "\\\"s3:GetObjectVersionAcl\\\"\\r\\n ],\\r\\n \\\"Resource\\\":[\\r\\n "); + permissionPolicy.append("\\\"arn:aws:s3:::"); + permissionPolicy.append(sourceBucket); + permissionPolicy.append("/*\\\"\\r\\n ]\\r\\n },\\r\\n {\\r\\n "); + permissionPolicy.append( + "\\\"Effect\\\":\\\"Allow\\\",\\r\\n \\\"Action\\\":[\\r\\n "); + permissionPolicy.append( + "\\\"s3:ListBucket\\\",\\r\\n \\\"s3:GetReplicationConfiguration\\\"\\r\\n "); + permissionPolicy.append("],\\r\\n \\\"Resource\\\":[\\r\\n \\\"arn:aws:s3:::"); + permissionPolicy.append(sourceBucket); + permissionPolicy.append("\\r\\n "); + permissionPolicy + .append("]\\r\\n },\\r\\n {\\r\\n \\\"Effect\\\":\\\"Allow\\\",\\r\\n "); + permissionPolicy.append( + "\\\"Action\\\":[\\r\\n \\\"s3:ReplicateObject\\\",\\r\\n "); + permissionPolicy + .append("\\\"s3:ReplicateDelete\\\",\\r\\n \\\"s3:ReplicateTags\\\",\\r\\n "); + permissionPolicy.append("\\\"s3:GetObjectVersionTagging\\\"\\r\\n\\r\\n ],\\r\\n "); + permissionPolicy.append("\\\"Resource\\\":\\\"arn:aws:s3:::"); + permissionPolicy.append(destinationBucket); + permissionPolicy.append("/*\\\"\\r\\n }\\r\\n ]\\r\\n}"); + + PutRolePolicyRequest putRolePolicyRequest = new PutRolePolicyRequest() + .withRoleName(roleName) + .withPolicyDocument(permissionPolicy.toString()) + .withPolicyName("crrRolePolicy"); + + iamClient.putRolePolicy(putRolePolicyRequest); + } - } - - private static void createBucket(AmazonS3 s3Client, Regions region, String bucketName) { - CreateBucketRequest request = new CreateBucketRequest(bucketName, region.getName()); - s3Client.createBucket(request); - BucketVersioningConfiguration configuration = new BucketVersioningConfiguration().withStatus(BucketVersioningConfiguration.ENABLED); - - SetBucketVersioningConfigurationRequest enableVersioningRequest = new SetBucketVersioningConfigurationRequest(bucketName, configuration); - s3Client.setBucketVersioningConfiguration(enableVersioningRequest); - - - } - - private static void assignRole(String roleName, Regions region, String sourceBucket, String destinationBucket) { - AmazonIdentityManagement iamClient = AmazonIdentityManagementClientBuilder.standard() - .withRegion(region) - .withCredentials(new ProfileCredentialsProvider()) - .build(); - StringBuilder trustPolicy = new StringBuilder(); - trustPolicy.append("{\\r\\n "); - trustPolicy.append("\\\"Version\\\":\\\"2012-10-17\\\",\\r\\n "); - trustPolicy.append("\\\"Statement\\\":[\\r\\n {\\r\\n "); - trustPolicy.append("\\\"Effect\\\":\\\"Allow\\\",\\r\\n \\\"Principal\\\":{\\r\\n "); - trustPolicy.append("\\\"Service\\\":\\\"s3.amazonaws.com\\\"\\r\\n },\\r\\n "); - trustPolicy.append("\\\"Action\\\":\\\"sts:AssumeRole\\\"\\r\\n }\\r\\n ]\\r\\n}"); - - CreateRoleRequest createRoleRequest = new CreateRoleRequest() - .withRoleName(roleName) - .withAssumeRolePolicyDocument(trustPolicy.toString()); - - iamClient.createRole(createRoleRequest); - - StringBuilder permissionPolicy = new StringBuilder(); - permissionPolicy.append("{\\r\\n \\\"Version\\\":\\\"2012-10-17\\\",\\r\\n \\\"Statement\\\":[\\r\\n {\\r\\n "); - permissionPolicy.append("\\\"Effect\\\":\\\"Allow\\\",\\r\\n \\\"Action\\\":[\\r\\n "); - permissionPolicy.append("\\\"s3:GetObjectVersionForReplication\\\",\\r\\n "); - permissionPolicy.append("\\\"s3:GetObjectVersionAcl\\\"\\r\\n ],\\r\\n \\\"Resource\\\":[\\r\\n "); - permissionPolicy.append("\\\"arn:aws:s3:::"); - permissionPolicy.append(sourceBucket); - permissionPolicy.append("/*\\\"\\r\\n ]\\r\\n },\\r\\n {\\r\\n "); - permissionPolicy.append("\\\"Effect\\\":\\\"Allow\\\",\\r\\n \\\"Action\\\":[\\r\\n "); - permissionPolicy.append("\\\"s3:ListBucket\\\",\\r\\n \\\"s3:GetReplicationConfiguration\\\"\\r\\n "); - permissionPolicy.append("],\\r\\n \\\"Resource\\\":[\\r\\n \\\"arn:aws:s3:::"); - permissionPolicy.append(sourceBucket); - permissionPolicy.append("\\r\\n "); - permissionPolicy.append("]\\r\\n },\\r\\n {\\r\\n \\\"Effect\\\":\\\"Allow\\\",\\r\\n "); - permissionPolicy.append("\\\"Action\\\":[\\r\\n \\\"s3:ReplicateObject\\\",\\r\\n "); - permissionPolicy.append("\\\"s3:ReplicateDelete\\\",\\r\\n \\\"s3:ReplicateTags\\\",\\r\\n "); - permissionPolicy.append("\\\"s3:GetObjectVersionTagging\\\"\\r\\n\\r\\n ],\\r\\n "); - permissionPolicy.append("\\\"Resource\\\":\\\"arn:aws:s3:::"); - permissionPolicy.append(destinationBucket); - permissionPolicy.append("/*\\\"\\r\\n }\\r\\n ]\\r\\n}"); - - PutRolePolicyRequest putRolePolicyRequest = new PutRolePolicyRequest() - .withRoleName(roleName) - .withPolicyDocument(permissionPolicy.toString()) - .withPolicyName("crrRolePolicy"); - - iamClient.putRolePolicy(putRolePolicyRequest); - - - } } // snippet-end:[s3.java.cross_region_replication.complete] diff --git a/java/example_code/s3/src/main/java/aws/example/s3/DeleteBucket.java b/java/example_code/s3/src/main/java/aws/example/s3/DeleteBucket.java index d9fb35d6960..9f3886acf50 100755 --- a/java/example_code/s3/src/main/java/aws/example/s3/DeleteBucket.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/DeleteBucket.java @@ -1,26 +1,5 @@ -//snippet-sourcedescription:[DeleteBucket.java demonstrates how to delete an existing bucket.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[deleteObject] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2017-05-25] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.s3; import com.amazonaws.AmazonServiceException; @@ -60,9 +39,7 @@ public static void main(String[] args) { System.out.println(" - removing objects from bucket"); ObjectListing object_listing = s3.listObjects(bucket_name); while (true) { - for (Iterator iterator = - object_listing.getObjectSummaries().iterator(); - iterator.hasNext(); ) { + for (Iterator iterator = object_listing.getObjectSummaries().iterator(); iterator.hasNext();) { S3ObjectSummary summary = (S3ObjectSummary) iterator.next(); s3.deleteObject(bucket_name, summary.getKey()); } @@ -79,9 +56,7 @@ public static void main(String[] args) { VersionListing version_listing = s3.listVersions( new ListVersionsRequest().withBucketName(bucket_name)); while (true) { - for (Iterator iterator = - version_listing.getVersionSummaries().iterator(); - iterator.hasNext(); ) { + for (Iterator iterator = version_listing.getVersionSummaries().iterator(); iterator.hasNext();) { S3VersionSummary vs = (S3VersionSummary) iterator.next(); s3.deleteVersion( bucket_name, vs.getKey(), vs.getVersionId()); diff --git a/java/example_code/s3/src/main/java/aws/example/s3/DeleteBucket2.java b/java/example_code/s3/src/main/java/aws/example/s3/DeleteBucket2.java index b530d81b0bb..e4a235e4bd5 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/DeleteBucket2.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/DeleteBucket2.java @@ -1,29 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[DeleteBucket.java demonstrates how to empty and then delete an S3 bucket.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DELETE Bucket] -// snippet-keyword:[GET Bucket] -// snippet-keyword:[DELETE Object] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.delete_bucket.complete] import com.amazonaws.AmazonServiceException; @@ -49,9 +26,11 @@ public static void main(String[] args) { .build(); // Delete all objects from the bucket. This is sufficient - // for unversioned buckets. For versioned buckets, when you attempt to delete objects, Amazon S3 inserts + // for unversioned buckets. For versioned buckets, when you attempt to delete + // objects, Amazon S3 inserts // delete markers for all objects, but doesn't delete the object versions. - // To delete objects from versioned buckets, delete all of the object versions before deleting + // To delete objects from versioned buckets, delete all of the object versions + // before deleting // the bucket (see below for an example). ObjectListing objectListing = s3Client.listObjects(bucketName); while (true) { @@ -62,7 +41,8 @@ public static void main(String[] args) { // If the bucket contains many objects, the listObjects() call // might not return all of the objects in the first listing. Check to - // see whether the listing was truncated. If so, retrieve the next page of objects + // see whether the listing was truncated. If so, retrieve the next page of + // objects // and delete them. if (objectListing.isTruncated()) { objectListing = s3Client.listNextBatchOfObjects(objectListing); @@ -90,7 +70,7 @@ public static void main(String[] args) { // After all objects and object versions are deleted, delete the bucket. s3Client.deleteBucket(bucketName); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/DeleteBucketPolicy.java b/java/example_code/s3/src/main/java/aws/example/s3/DeleteBucketPolicy.java index 529e8a969d8..8f7ed767079 100755 --- a/java/example_code/s3/src/main/java/aws/example/s3/DeleteBucketPolicy.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/DeleteBucketPolicy.java @@ -1,26 +1,5 @@ -//snippet-sourcedescription:[DeleteBucketPolicy.java demonstrates how to delete a bucket policy on an existing S3 bucket.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[deleteBucketPolicy] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* -Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -This file is 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/ - -This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -CONDITIONS OF ANY KIND, either express or implied. See the License for the -specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.s3; import com.amazonaws.AmazonServiceException; diff --git a/java/example_code/s3/src/main/java/aws/example/s3/DeleteMultipleObjectsNonVersionedBucket.java b/java/example_code/s3/src/main/java/aws/example/s3/DeleteMultipleObjectsNonVersionedBucket.java index f3da33dfe2a..582518fe879 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/DeleteMultipleObjectsNonVersionedBucket.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/DeleteMultipleObjectsNonVersionedBucket.java @@ -1,27 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[DeleteMultipleObjectsNonVersionedBucket.java demonstrates how to delete multiple S3 objects from a non-versioned bucket.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DELETE Object] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.delete_multiple_objects_non_versioned_bucket.complete] import com.amazonaws.AmazonServiceException; @@ -66,7 +45,7 @@ public static void main(String[] args) throws IOException { int successfulDeletes = delObjRes.getDeletedObjects().size(); System.out.println(successfulDeletes + " objects successfully deleted."); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/DeleteMultipleObjectsVersionEnabledBucket.java b/java/example_code/s3/src/main/java/aws/example/s3/DeleteMultipleObjectsVersionEnabledBucket.java index 05cb91d0640..1f2695ae2aa 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/DeleteMultipleObjectsVersionEnabledBucket.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/DeleteMultipleObjectsVersionEnabledBucket.java @@ -1,27 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -// snippet-sourcedescription:[DeleteMultipleObjectsVersionEnabledBucket.java demonstrates how to delete S3 object versions and remove delete markers from objects in versioned S3 buckets.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DELETE Object] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[s3.java.delete_multiple_objects_version_enabled_bucket.complete] import com.amazonaws.AmazonServiceException; @@ -68,11 +47,12 @@ public static void main(String[] args) throws IOException { // specific versions. DeleteObjectsResult unversionedDeleteResult = uploadAndDeleteObjectsWithoutVersions(); - // Remove the delete markers placed on objects in the non-versioned create/delete method. + // Remove the delete markers placed on objects in the non-versioned + // create/delete method. multiObjectVersionedDeleteRemoveDeleteMarkers(unversionedDeleteResult); } } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/DeleteObject.java b/java/example_code/s3/src/main/java/aws/example/s3/DeleteObject.java index b96aead84f1..65ee6f589cc 100755 --- a/java/example_code/s3/src/main/java/aws/example/s3/DeleteObject.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/DeleteObject.java @@ -1,26 +1,5 @@ -//snippet-sourcedescription:[DeleteObject.java demonstrates how to delete an existing object.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[deleteObject] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.s3; import com.amazonaws.AmazonServiceException; diff --git a/java/example_code/s3/src/main/java/aws/example/s3/DeleteObjectNonVersionedBucket.java b/java/example_code/s3/src/main/java/aws/example/s3/DeleteObjectNonVersionedBucket.java index fe4f60d8267..ebb8795102a 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/DeleteObjectNonVersionedBucket.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/DeleteObjectNonVersionedBucket.java @@ -1,27 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -// snippet-sourcedescription:[DeleteObjectNonVersionedBucket.java demonstrates how to delete an S3 object from a non-versioned bucket.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DELETE Object] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[s3.java.delete_object_non_versioned_bucket.complete] import com.amazonaws.AmazonServiceException; @@ -49,7 +28,7 @@ public static void main(String[] args) throws IOException { s3Client.deleteObject(new DeleteObjectRequest(bucketName, keyName)); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/DeleteObjectVersionEnabledBucket.java b/java/example_code/s3/src/main/java/aws/example/s3/DeleteObjectVersionEnabledBucket.java index 957f02a22db..1d99c200b72 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/DeleteObjectVersionEnabledBucket.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/DeleteObjectVersionEnabledBucket.java @@ -1,27 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[DeleteObjectVersionEnabledBucket.java demonstrates how to delete an S3 object version from a version-enabled bucket.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DELETE Object] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.delete_object_version_enabled_bucket.complete] import com.amazonaws.AmazonServiceException; @@ -55,7 +34,8 @@ public static void main(String[] args) throws IOException { System.out.printf("Bucket %s is not versioning-enabled.", bucketName); } else { // Add an object. - PutObjectResult putResult = s3Client.putObject(bucketName, keyName, "Sample content for deletion example."); + PutObjectResult putResult = s3Client.putObject(bucketName, keyName, + "Sample content for deletion example."); System.out.printf("Object %s added to bucket %s\n", keyName, bucketName); // Delete the version of the object that we just created. @@ -64,7 +44,7 @@ public static void main(String[] args) throws IOException { System.out.printf("Object %s, version %s deleted\n", keyName, putResult.getVersionId()); } } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/DeleteObjects.java b/java/example_code/s3/src/main/java/aws/example/s3/DeleteObjects.java index 778ffda0620..7a8e8253673 100755 --- a/java/example_code/s3/src/main/java/aws/example/s3/DeleteObjects.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/DeleteObjects.java @@ -1,26 +1,5 @@ -//snippet-sourcedescription:[DeleteObjects.java demonstrates how to delete multiple objects in an S3 bucket.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[deleteObjects] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.s3; import com.amazonaws.AmazonServiceException; diff --git a/java/example_code/s3/src/main/java/aws/example/s3/DeleteWebsiteConfiguration.java b/java/example_code/s3/src/main/java/aws/example/s3/DeleteWebsiteConfiguration.java index 97551d8dc0b..5290ec162fe 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/DeleteWebsiteConfiguration.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/DeleteWebsiteConfiguration.java @@ -1,25 +1,5 @@ -//snippet-sourcedescription:[DeleteWebsiteConfiguration.java demonstrates how to delete the website configuration for an S3 bucket set up as a static website.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.s3; // snippet-start:[s3.java1.s3_delete_website_config.import] diff --git a/java/example_code/s3/src/main/java/aws/example/s3/DualStackEndpoints.java b/java/example_code/s3/src/main/java/aws/example/s3/DualStackEndpoints.java index bc6daaf30c1..665377050d3 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/DualStackEndpoints.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/DualStackEndpoints.java @@ -1,27 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[DualStackEndpoints.java demonstrates how to create an S3 client with dual-stack endpoints enabled.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[GET Bucket] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.dual_stack_endpoints.complete] import com.amazonaws.AmazonServiceException; @@ -47,7 +26,7 @@ public static void main(String[] args) { s3Client.listObjects(bucketName); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/EnableNotificationOnABucket.java b/java/example_code/s3/src/main/java/aws/example/s3/EnableNotificationOnABucket.java index fe9314e0ca6..056d5c3c5c3 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/EnableNotificationOnABucket.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/EnableNotificationOnABucket.java @@ -1,27 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[EnableNotificationsOnABucket.java demonstrates how to configure an S3 bucket to work with Amazon Simple Notification Service and Simple Queue Service.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[PUT Bucket notification] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.enable_notification_on_a_bucket.complete] import com.amazonaws.AmazonServiceException; @@ -58,12 +37,13 @@ public static void main(String[] args) throws IOException { notificationConfiguration.addConfiguration("sqsQueueConfig", new QueueConfiguration(sqsQueueARN, EnumSet.of(S3Event.ObjectCreated))); - // Create the notification configuration request and set the bucket notification configuration. + // Create the notification configuration request and set the bucket notification + // configuration. SetBucketNotificationConfigurationRequest request = new SetBucketNotificationConfigurationRequest( bucketName, notificationConfiguration); s3Client.setBucketNotificationConfiguration(request); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { @@ -74,4 +54,4 @@ public static void main(String[] args) throws IOException { } } -//snippet-end:[s3.java.enable_notification_on_a_bucket.complete] \ No newline at end of file +// snippet-end:[s3.java.enable_notification_on_a_bucket.complete] \ No newline at end of file diff --git a/java/example_code/s3/src/main/java/aws/example/s3/GeneratePresignedPutUrl.java b/java/example_code/s3/src/main/java/aws/example/s3/GeneratePresignedPutUrl.java index 7314ae1c42e..3d5f294027b 100755 --- a/java/example_code/s3/src/main/java/aws/example/s3/GeneratePresignedPutUrl.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/GeneratePresignedPutUrl.java @@ -1,26 +1,5 @@ -//snippet-sourcedescription:[GeneratePresignedPutUrl.java demonstrates how to generatee a pre-signed PUT URL for uploading a file to an Amazon S3 bucket.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[GeneratePresignedUrlRequest] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-11-01] -//snippet-sourceauthor:[walkerk1980] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.s3; import com.amazonaws.AmazonServiceException; @@ -64,19 +43,20 @@ public static void main(String[] args) { expiration.setTime(expirationInMs); try { - GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucket_name, key_name) + GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucket_name, + key_name) .withMethod(HttpMethod.PUT) .withExpiration(expiration); URL url = s3.generatePresignedUrl(generatePresignedUrlRequest); - //print URL + // print URL System.out.println("\n\rGenerated URL: " + url.toString()); - //Print curl command to consume URL + // Print curl command to consume URL System.out.println("\n\rExample command to use URL for file upload: \n\r"); - System.out.println("curl --request PUT --upload-file /path/to/" + key_name + " '" + url.toString() + "' -# > /dev/null"); + System.out.println("curl --request PUT --upload-file /path/to/" + key_name + " '" + url.toString() + + "' -# > /dev/null"); } catch (AmazonServiceException e) { System.err.println(e.getErrorMessage()); System.exit(1); } } } - diff --git a/java/example_code/s3/src/main/java/aws/example/s3/GeneratePresignedURL.java b/java/example_code/s3/src/main/java/aws/example/s3/GeneratePresignedURL.java index f82df4773bf..286d21aca70 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/GeneratePresignedURL.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/GeneratePresignedURL.java @@ -1,26 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[GeneratePresignedURL.java demonstrates how to generate a presigned URL with the S3 Java SDK.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.generate_presigned_url.complete] import com.amazonaws.AmazonServiceException; @@ -57,15 +37,15 @@ public static void main(String[] args) throws IOException { // Generate the presigned URL. System.out.println("Generating pre-signed URL."); - GeneratePresignedUrlRequest generatePresignedUrlRequest = - new GeneratePresignedUrlRequest(bucketName, objectKey) - .withMethod(HttpMethod.GET) - .withExpiration(expiration); + GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, + objectKey) + .withMethod(HttpMethod.GET) + .withExpiration(expiration); URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest); System.out.println("Pre-Signed URL: " + url.toString()); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/GeneratePresignedUrlAndUploadObject.java b/java/example_code/s3/src/main/java/aws/example/s3/GeneratePresignedUrlAndUploadObject.java index 061d413974f..061bd45e980 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/GeneratePresignedUrlAndUploadObject.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/GeneratePresignedUrlAndUploadObject.java @@ -1,26 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[GeneratePresignedUrlAndUploadObject.java demonstrates how to generate a presigned URL with the S3 Java SDK and use the URL to upload an object.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.generate_presigned_url_and_upload_object.complete] import com.amazonaws.AmazonServiceException; @@ -59,12 +39,14 @@ public static void main(String[] args) throws IOException { // Generate the pre-signed URL. System.out.println("Generating pre-signed URL."); - GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, objectKey) + GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, + objectKey) .withMethod(HttpMethod.PUT) .withExpiration(expiration); URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest); - // Create the connection and use it to upload the new object using the pre-signed URL. + // Create the connection and use it to upload the new object using the + // pre-signed URL. HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("PUT"); @@ -72,7 +54,8 @@ public static void main(String[] args) throws IOException { out.write("This text uploaded as an object via presigned URL."); out.close(); - // Check the HTTP response code. To complete the upload and make the object available, + // Check the HTTP response code. To complete the upload and make the object + // available, // you must interact with the connection object in some way. connection.getResponseCode(); System.out.println("HTTP response code: " + connection.getResponseCode()); @@ -81,11 +64,11 @@ public static void main(String[] args) throws IOException { S3Object object = s3Client.getObject(bucketName, objectKey); System.out.println("Object " + object.getKey() + " created in bucket " + object.getBucketName()); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { - // Amazon S3 couldn't be contacted for a response, or the client + // Amazon S3 couldn't be contacted for a response, or the client // couldn't parse the response from Amazon S3. e.printStackTrace(); } diff --git a/java/example_code/s3/src/main/java/aws/example/s3/GetAcl.java b/java/example_code/s3/src/main/java/aws/example/s3/GetAcl.java index b2455929832..f44985b9cd8 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/GetAcl.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/GetAcl.java @@ -1,27 +1,5 @@ -//snippet-sourcedescription:[GetAcl.java demonstrates how to get the access control list (ACL) of an S3 bucket and an object.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[getBucketAcl] -//snippet-keyword:[getObjectAcl] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* -Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -This file is 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/ - -This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -CONDITIONS OF ANY KIND, either express or implied. See the License for the -specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.s3; import com.amazonaws.AmazonServiceException; diff --git a/java/example_code/s3/src/main/java/aws/example/s3/GetBucketPolicy.java b/java/example_code/s3/src/main/java/aws/example/s3/GetBucketPolicy.java index f5f5b9aeb41..c0547f30a75 100755 --- a/java/example_code/s3/src/main/java/aws/example/s3/GetBucketPolicy.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/GetBucketPolicy.java @@ -1,26 +1,5 @@ -//snippet-sourcedescription:[GetBucketPolicy.java demonstrates how to get the bucket policy from an existing S3 bucket.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[getBucketPolicy] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* -Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -This file is 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/ - -This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -CONDITIONS OF ANY KIND, either express or implied. See the License for the -specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.s3; import com.amazonaws.AmazonServiceException; diff --git a/java/example_code/s3/src/main/java/aws/example/s3/GetObject.java b/java/example_code/s3/src/main/java/aws/example/s3/GetObject.java index c03ea20efa0..a7d723e2cbe 100755 --- a/java/example_code/s3/src/main/java/aws/example/s3/GetObject.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/GetObject.java @@ -1,26 +1,5 @@ -//snippet-sourcedescription:[GetObject.java demonstrates how to get an object within an Amazon S3 bucket.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[getObject] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.s3; import com.amazonaws.AmazonServiceException; diff --git a/java/example_code/s3/src/main/java/aws/example/s3/GetObject2.java b/java/example_code/s3/src/main/java/aws/example/s3/GetObject2.java index 50c52d9c4af..d1af4f1220c 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/GetObject2.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/GetObject2.java @@ -1,27 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[GetObject.java demonstrates several ways to retrieve an entire or partial S3 object.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[GET Object] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.get_object.complete] import com.amazonaws.AmazonServiceException; @@ -67,7 +46,8 @@ public static void main(String[] args) throws IOException { System.out.println("Printing bytes retrieved."); displayTextInputStream(objectPortion.getObjectContent()); - // Get an entire object, overriding the specified response headers, and print the object's content. + // Get an entire object, overriding the specified response headers, and print + // the object's content. ResponseHeaderOverrides headerOverrides = new ResponseHeaderOverrides() .withCacheControl("No-cache") .withContentDisposition("attachment; filename=example.txt"); @@ -76,7 +56,7 @@ public static void main(String[] args) throws IOException { headerOverrideObject = s3Client.getObject(getObjectRequestHeaderOverride); displayTextInputStream(headerOverrideObject.getObjectContent()); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { @@ -84,7 +64,8 @@ public static void main(String[] args) throws IOException { // couldn't parse the response from Amazon S3. e.printStackTrace(); } finally { - // To ensure that the network connection doesn't remain open, close any open input streams. + // To ensure that the network connection doesn't remain open, close any open + // input streams. if (fullObject != null) { fullObject.close(); } diff --git a/java/example_code/s3/src/main/java/aws/example/s3/GetObjectTags.java b/java/example_code/s3/src/main/java/aws/example/s3/GetObjectTags.java index 2929804502b..df7b99e73e1 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/GetObjectTags.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/GetObjectTags.java @@ -1,27 +1,5 @@ -/** - * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[GetObjectTags.java demonstrates how to read tags that belong to an object located in an S3 bucket] -// snippet-service:[S3] -// snippet-keyword:[Java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-01-09] -// snippet-sourceauthor:[AWS-scmacdon] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.s3; @@ -37,7 +15,6 @@ public class GetObjectTags { - public static void main(String[] args) throws IOException { if (args.length < 2) { @@ -58,14 +35,14 @@ public static void main(String[] args) throws IOException { GetObjectTaggingResult tags = s3.getObjectTagging(getTaggingRequest); - List tagSet= tags.getTagSet(); + List tagSet = tags.getTagSet(); - //Iterate through the list + // Iterate through the list Iterator tagIterator = tagSet.iterator(); - while(tagIterator.hasNext()) { + while (tagIterator.hasNext()) { - Tag tag = (Tag)tagIterator.next(); + Tag tag = (Tag) tagIterator.next(); System.out.println(tag.getKey()); System.out.println(tag.getValue()); diff --git a/java/example_code/s3/src/main/java/aws/example/s3/GetObjectTags2.java b/java/example_code/s3/src/main/java/aws/example/s3/GetObjectTags2.java index 7af6bf1f699..d1b573acf17 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/GetObjectTags2.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/GetObjectTags2.java @@ -1,27 +1,5 @@ -/** - * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[GetObjectTags.java demonstrates how to read tags that belong to an object located in an S3 bucket] -// snippet-service:[S3] -// snippet-keyword:[Java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-01-09] -// snippet-sourceauthor:[AWS-scmacdon] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.java.getobjecttags.complete] @@ -62,14 +40,14 @@ public static void main(String[] args) { GetObjectTaggingResult tags = s3.getObjectTagging(getTaggingRequest); - List tagSet= tags.getTagSet(); + List tagSet = tags.getTagSet(); - //Iterate through the list + // Iterate through the list Iterator tagIterator = tagSet.iterator(); - while(tagIterator.hasNext()) { + while (tagIterator.hasNext()) { - Tag tag = (Tag)tagIterator.next(); + Tag tag = (Tag) tagIterator.next(); System.out.println(tag.getKey()); System.out.println(tag.getValue()); diff --git a/java/example_code/s3/src/main/java/aws/example/s3/GetPDFandSave.java b/java/example_code/s3/src/main/java/aws/example/s3/GetPDFandSave.java index 9d6bba1ad15..756d62c96ed 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/GetPDFandSave.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/GetPDFandSave.java @@ -1,5 +1,5 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.s3; @@ -32,7 +32,7 @@ public static void main(String[] args) { .build(); try { - + // Download the PDF file from S3 S3Object s3object = s3Client.getObject(new GetObjectRequest(BUCKET_NAME, OBJECT_KEY)); InputStream inputStream = s3object.getObjectContent(); @@ -52,7 +52,7 @@ public static void main(String[] args) { inputStream.close(); } catch (Exception e) { - + e.printStackTrace(); } } diff --git a/java/example_code/s3/src/main/java/aws/example/s3/GetWebsiteConfiguration.java b/java/example_code/s3/src/main/java/aws/example/s3/GetWebsiteConfiguration.java index b7cbf4ff3ee..4dcc868e485 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/GetWebsiteConfiguration.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/GetWebsiteConfiguration.java @@ -1,26 +1,5 @@ -//snippet-sourcedescription:[GetWebsiteConfiguration.java demonstrates how to get the website configuration for an S3 bucket.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[getBucketWebsiteConfiguration] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.s3; // snippet-start:[s3.java1.s3_get_website_config.import] @@ -43,8 +22,7 @@ public static void getWebsiteConfig(String bucket_name) { // snippet-start:[s3.java1.s3_get_website_config.main] final AmazonS3 s3 = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); try { - BucketWebsiteConfiguration config = - s3.getBucketWebsiteConfiguration(bucket_name); + BucketWebsiteConfiguration config = s3.getBucketWebsiteConfiguration(bucket_name); if (config == null) { System.out.println("No website configuration found!"); } else { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/HighLevelAbortMultipartUpload.java b/java/example_code/s3/src/main/java/aws/example/s3/HighLevelAbortMultipartUpload.java index 2b951e1d9ee..736ace9fd06 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/HighLevelAbortMultipartUpload.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/HighLevelAbortMultipartUpload.java @@ -1,27 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[HighLevelAbortMultipartUpload.java demonstrates how to abort a multipart upload to S3 using the TransferManager class.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DELETE Multipart upload] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.high_level_abort_multipart_upload.complete] import com.amazonaws.AmazonServiceException; @@ -55,11 +34,11 @@ public static void main(String[] args) { Date oneWeekAgo = new Date(System.currentTimeMillis() - sevenDays); tm.abortMultipartUploads(bucketName, oneWeekAgo); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { - // Amazon S3 couldn't be contacted for a response, or the client couldn't + // Amazon S3 couldn't be contacted for a response, or the client couldn't // parse the response from Amazon S3. e.printStackTrace(); } diff --git a/java/example_code/s3/src/main/java/aws/example/s3/HighLevelMultipartUpload.java b/java/example_code/s3/src/main/java/aws/example/s3/HighLevelMultipartUpload.java index d3bcc688a31..9abf93f2c92 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/HighLevelMultipartUpload.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/HighLevelMultipartUpload.java @@ -1,27 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[HighLevelMultipartUpload.java demonstrates how to upload a file to S3 using the TransferManager class.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[PUT Object] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.high_level_multipart_upload.complete] import com.amazonaws.AmazonServiceException; @@ -62,7 +41,7 @@ public static void main(String[] args) throws Exception { upload.waitForCompletion(); System.out.println("Object upload complete"); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/HighLevelTrackMultipartUpload.java b/java/example_code/s3/src/main/java/aws/example/s3/HighLevelTrackMultipartUpload.java index a88aaaaa98f..beb5b030639 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/HighLevelTrackMultipartUpload.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/HighLevelTrackMultipartUpload.java @@ -1,27 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[HighLevelTrackMultipartUpload.java demonstrates how to upload a file to S3 and monitor the upload using the TransferManager class.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[PUT Object] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.high_level_track_multipart_upload.complete] import com.amazonaws.AmazonServiceException; @@ -57,7 +36,7 @@ public static void main(String[] args) throws Exception { .build(); PutObjectRequest request = new PutObjectRequest(bucketName, keyName, new File(filePath)); - // To receive notifications when bytes are transferred, add a + // To receive notifications when bytes are transferred, add a // ProgressListener to your request. request.setGeneralProgressListener(new ProgressListener() { public void progressChanged(ProgressEvent progressEvent) { @@ -71,11 +50,11 @@ public void progressChanged(ProgressEvent progressEvent) { // Optionally, you can wait for the upload to finish before continuing. upload.waitForCompletion(); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { - // Amazon S3 couldn't be contacted for a response, or the client + // Amazon S3 couldn't be contacted for a response, or the client // couldn't parse the response from Amazon S3. e.printStackTrace(); } diff --git a/java/example_code/s3/src/main/java/aws/example/s3/LifecycleConfiguration.java b/java/example_code/s3/src/main/java/aws/example/s3/LifecycleConfiguration.java index a0e52f0914b..5476190ea17 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/LifecycleConfiguration.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/LifecycleConfiguration.java @@ -1,29 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -// snippet-sourcedescription:[LifecycleConfiguration.java demonstrates how to set and get S3 bucket lifecycle configurations.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[GET Bucket lifecycle] -// snippet-keyword:[PUT Bucket lifecycle] -// snippet-keyword:[DELETE Bucket lifecycle] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[s3.java.lifecycle_configuration.complete] import com.amazonaws.AmazonServiceException; @@ -46,79 +23,85 @@ public class LifecycleConfiguration { - public static void main(String[] args) throws IOException { - Regions clientRegion = Regions.DEFAULT_REGION; - String bucketName = "*** Bucket name ***"; - - // Create a rule to archive objects with the "glacierobjects/" prefix to Glacier immediately. - BucketLifecycleConfiguration.Rule rule1 = new BucketLifecycleConfiguration.Rule() - .withId("Archive immediately rule") - .withFilter(new LifecycleFilter(new LifecyclePrefixPredicate("glacierobjects/"))) - .addTransition(new Transition().withDays(0).withStorageClass(StorageClass.Glacier)) - .withStatus(BucketLifecycleConfiguration.ENABLED); - - // Create a rule to transition objects to the Standard-Infrequent Access storage class - // after 30 days, then to Glacier after 365 days. Amazon S3 will delete the objects after 3650 days. - // The rule applies to all objects with the tag "archive" set to "true". - BucketLifecycleConfiguration.Rule rule2 = new BucketLifecycleConfiguration.Rule() - .withId("Archive and then delete rule") - .withFilter(new LifecycleFilter(new LifecycleTagPredicate(new Tag("archive", "true")))) - .addTransition(new Transition().withDays(30).withStorageClass(StorageClass.StandardInfrequentAccess)) - .addTransition(new Transition().withDays(365).withStorageClass(StorageClass.Glacier)) - .withExpirationInDays(3650) - .withStatus(BucketLifecycleConfiguration.ENABLED); - - // Add the rules to a new BucketLifecycleConfiguration. - BucketLifecycleConfiguration configuration = new BucketLifecycleConfiguration() - .withRules(Arrays.asList(rule1, rule2)); - - try { - AmazonS3 s3Client = AmazonS3ClientBuilder.standard() - .withCredentials(new ProfileCredentialsProvider()) - .withRegion(clientRegion) - .build(); - - // Save the configuration. - s3Client.setBucketLifecycleConfiguration(bucketName, configuration); - - // Retrieve the configuration. - configuration = s3Client.getBucketLifecycleConfiguration(bucketName); - - // Add a new rule with both a prefix predicate and a tag predicate. - configuration.getRules().add(new BucketLifecycleConfiguration.Rule().withId("NewRule") - .withFilter(new LifecycleFilter(new LifecycleAndOperator( - Arrays.asList(new LifecyclePrefixPredicate("YearlyDocuments/"), - new LifecycleTagPredicate(new Tag("expire_after", "ten_years")))))) - .withExpirationInDays(3650) - .withStatus(BucketLifecycleConfiguration.ENABLED)); - - // Save the configuration. - s3Client.setBucketLifecycleConfiguration(bucketName, configuration); - - // Retrieve the configuration. - configuration = s3Client.getBucketLifecycleConfiguration(bucketName); - - // Verify that the configuration now has three rules. - configuration = s3Client.getBucketLifecycleConfiguration(bucketName); - System.out.println("Expected # of rules = 3; found: " + configuration.getRules().size()); - - // Delete the configuration. - s3Client.deleteBucketLifecycleConfiguration(bucketName); - - // Verify that the configuration has been deleted by attempting to retrieve it. - configuration = s3Client.getBucketLifecycleConfiguration(bucketName); - String s = (configuration == null) ? "No configuration found." : "Configuration found."; - System.out.println(s); - } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process - // it, so it returned an error response. - e.printStackTrace(); - } catch (SdkClientException e) { - // Amazon S3 couldn't be contacted for a response, or the client - // couldn't parse the response from Amazon S3. - e.printStackTrace(); + public static void main(String[] args) throws IOException { + Regions clientRegion = Regions.DEFAULT_REGION; + String bucketName = "*** Bucket name ***"; + + // Create a rule to archive objects with the "glacierobjects/" prefix to Glacier + // immediately. + BucketLifecycleConfiguration.Rule rule1 = new BucketLifecycleConfiguration.Rule() + .withId("Archive immediately rule") + .withFilter(new LifecycleFilter(new LifecyclePrefixPredicate("glacierobjects/"))) + .addTransition(new Transition().withDays(0).withStorageClass(StorageClass.Glacier)) + .withStatus(BucketLifecycleConfiguration.ENABLED); + + // Create a rule to transition objects to the Standard-Infrequent Access storage + // class + // after 30 days, then to Glacier after 365 days. Amazon S3 will delete the + // objects after 3650 days. + // The rule applies to all objects with the tag "archive" set to "true". + BucketLifecycleConfiguration.Rule rule2 = new BucketLifecycleConfiguration.Rule() + .withId("Archive and then delete rule") + .withFilter(new LifecycleFilter(new LifecycleTagPredicate(new Tag("archive", "true")))) + .addTransition(new Transition().withDays(30) + .withStorageClass(StorageClass.StandardInfrequentAccess)) + .addTransition(new Transition().withDays(365).withStorageClass(StorageClass.Glacier)) + .withExpirationInDays(3650) + .withStatus(BucketLifecycleConfiguration.ENABLED); + + // Add the rules to a new BucketLifecycleConfiguration. + BucketLifecycleConfiguration configuration = new BucketLifecycleConfiguration() + .withRules(Arrays.asList(rule1, rule2)); + + try { + AmazonS3 s3Client = AmazonS3ClientBuilder.standard() + .withCredentials(new ProfileCredentialsProvider()) + .withRegion(clientRegion) + .build(); + + // Save the configuration. + s3Client.setBucketLifecycleConfiguration(bucketName, configuration); + + // Retrieve the configuration. + configuration = s3Client.getBucketLifecycleConfiguration(bucketName); + + // Add a new rule with both a prefix predicate and a tag predicate. + configuration.getRules().add(new BucketLifecycleConfiguration.Rule().withId("NewRule") + .withFilter(new LifecycleFilter(new LifecycleAndOperator( + Arrays.asList(new LifecyclePrefixPredicate("YearlyDocuments/"), + new LifecycleTagPredicate(new Tag( + "expire_after", + "ten_years")))))) + .withExpirationInDays(3650) + .withStatus(BucketLifecycleConfiguration.ENABLED)); + + // Save the configuration. + s3Client.setBucketLifecycleConfiguration(bucketName, configuration); + + // Retrieve the configuration. + configuration = s3Client.getBucketLifecycleConfiguration(bucketName); + + // Verify that the configuration now has three rules. + configuration = s3Client.getBucketLifecycleConfiguration(bucketName); + System.out.println("Expected # of rules = 3; found: " + configuration.getRules().size()); + + // Delete the configuration. + s3Client.deleteBucketLifecycleConfiguration(bucketName); + + // Verify that the configuration has been deleted by attempting to retrieve it. + configuration = s3Client.getBucketLifecycleConfiguration(bucketName); + String s = (configuration == null) ? "No configuration found." : "Configuration found."; + System.out.println(s); + } catch (AmazonServiceException e) { + // The call was transmitted successfully, but Amazon S3 couldn't process + // it, so it returned an error response. + e.printStackTrace(); + } catch (SdkClientException e) { + // Amazon S3 couldn't be contacted for a response, or the client + // couldn't parse the response from Amazon S3. + e.printStackTrace(); + } } - } } // snippet-end:[s3.java.lifecycle_configuration.complete] \ No newline at end of file diff --git a/java/example_code/s3/src/main/java/aws/example/s3/ListBuckets.java b/java/example_code/s3/src/main/java/aws/example/s3/ListBuckets.java index 9eb9b6758ea..e38c8716984 100755 --- a/java/example_code/s3/src/main/java/aws/example/s3/ListBuckets.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/ListBuckets.java @@ -1,26 +1,5 @@ -//snippet-sourcedescription:[ListBuckets.java demonstrates how to get a list of buckets in your AWS account.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[listBuckets] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.s3; import com.amazonaws.regions.Regions; diff --git a/java/example_code/s3/src/main/java/aws/example/s3/ListKeys.java b/java/example_code/s3/src/main/java/aws/example/s3/ListKeys.java index 445e94d7655..7052e55769b 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/ListKeys.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/ListKeys.java @@ -1,27 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[ListKeys.java demonstrates how to retrieve and iterate through a list of the keys contained in an S3 bucket.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[GET Bucket v2] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.list_keys.complete] import com.amazonaws.AmazonServiceException; @@ -68,7 +47,7 @@ public static void main(String[] args) throws IOException { req.setContinuationToken(token); } while (result.isTruncated()); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/ListKeysVersioningEnabledBucket.java b/java/example_code/s3/src/main/java/aws/example/s3/ListKeysVersioningEnabledBucket.java index 7a4858687c9..c98487e5059 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/ListKeysVersioningEnabledBucket.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/ListKeysVersioningEnabledBucket.java @@ -1,27 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[ListKeysVersioningEnabledBucket.java demonstrates how to list object versions in a version-enabled S3 bucket.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[GET Bucket] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.list_keys_versioning_enabled_bucket.complete] import com.amazonaws.AmazonServiceException; @@ -56,8 +35,7 @@ public static void main(String[] args) { int numVersions = 0, numPages = 0; while (true) { numPages++; - for (S3VersionSummary objectSummary : - versionListing.getVersionSummaries()) { + for (S3VersionSummary objectSummary : versionListing.getVersionSummaries()) { System.out.printf("Retrieved object %s, version %s\n", objectSummary.getKey(), objectSummary.getVersionId()); @@ -73,7 +51,7 @@ public static void main(String[] args) { } System.out.println(numVersions + " object versions retrieved in " + numPages + " pages"); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/ListMultipartUploads.java b/java/example_code/s3/src/main/java/aws/example/s3/ListMultipartUploads.java index 506142fbc5a..c78a324a331 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/ListMultipartUploads.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/ListMultipartUploads.java @@ -1,27 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[ListMultipartUploads.java demonstrates how to list all in-progress multipart uploads.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[List Multipart Uploads] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.list_multipart_uploads.complete] import com.amazonaws.AmazonServiceException; @@ -59,11 +38,11 @@ public static void main(String[] args) { System.out.println("Upload in progress: Key = \"" + u.getKey() + "\", id = " + u.getUploadId()); } } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { - // Amazon S3 couldn't be contacted for a response, or the client + // Amazon S3 couldn't be contacted for a response, or the client // couldn't parse the response from Amazon S3. e.printStackTrace(); } diff --git a/java/example_code/s3/src/main/java/aws/example/s3/ListObjects.java b/java/example_code/s3/src/main/java/aws/example/s3/ListObjects.java index 21e1e5bb949..ab002eeb278 100755 --- a/java/example_code/s3/src/main/java/aws/example/s3/ListObjects.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/ListObjects.java @@ -1,26 +1,5 @@ -//snippet-sourcedescription:[ListObjects.java demonstrates how to list objects within an Amazon S3 bucket.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[listObjectsV2] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.s3; import com.amazonaws.regions.Regions; diff --git a/java/example_code/s3/src/main/java/aws/example/s3/LowLevelAbortMultipartUpload.java b/java/example_code/s3/src/main/java/aws/example/s3/LowLevelAbortMultipartUpload.java index 63143707c1f..1714bd07490 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/LowLevelAbortMultipartUpload.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/LowLevelAbortMultipartUpload.java @@ -1,27 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[LowLevelAbortMultipartUpload.java demonstrates how to abort an in-progress multipart upload.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[Abort Multipart Upload] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.low_level_abort_multipart_upload.complete] import com.amazonaws.AmazonServiceException; @@ -68,7 +47,7 @@ public static void main(String[] args) { uploads = multipartUploadListing.getMultipartUploads(); System.out.println("After aborting uploads, " + uploads.size() + " multipart uploads in progress."); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/LowLevelMultipartCopy.java b/java/example_code/s3/src/main/java/aws/example/s3/LowLevelMultipartCopy.java index 6b25e532d5b..4ba03cb9bb7 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/LowLevelMultipartCopy.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/LowLevelMultipartCopy.java @@ -1,29 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[LowLevelMultipartCopy.java demonstrates how to perform a multipart upload of an S3 object.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[Initiate Multipart Upload] -// snippet-keyword:[Upload Part] -// snippet-keyword:[Complete Multipart Upload] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.low_level_multipart_copy.complete] import com.amazonaws.AmazonServiceException; @@ -54,7 +31,8 @@ public static void main(String[] args) throws IOException { .build(); // Initiate the multipart upload. - InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(destBucketName, destObjectKey); + InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(destBucketName, + destObjectKey); InitiateMultipartUploadResult initResult = s3Client.initiateMultipartUpload(initRequest); // Get the object size to track the end of the copy operation. @@ -86,7 +64,8 @@ public static void main(String[] args) throws IOException { bytePosition += partSize; } - // Complete the upload request to concatenate all uploaded parts and make the copied object available. + // Complete the upload request to concatenate all uploaded parts and make the + // copied object available. CompleteMultipartUploadRequest completeRequest = new CompleteMultipartUploadRequest( destBucketName, destObjectKey, @@ -95,11 +74,11 @@ public static void main(String[] args) throws IOException { s3Client.completeMultipartUpload(completeRequest); System.out.println("Multipart copy complete."); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { - // Amazon S3 couldn't be contacted for a response, or the client + // Amazon S3 couldn't be contacted for a response, or the client // couldn't parse the response from Amazon S3. e.printStackTrace(); } diff --git a/java/example_code/s3/src/main/java/aws/example/s3/LowLevelMultipartUpload.java b/java/example_code/s3/src/main/java/aws/example/s3/LowLevelMultipartUpload.java index 8015a06d783..fa7e635d3ab 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/LowLevelMultipartUpload.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/LowLevelMultipartUpload.java @@ -1,29 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[LowLevelMultipartUpload.java demonstrates how to use the low-level APIs to upload an object to S3 in multiple parts.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[Initiate Multipart Upload] -// snippet-keyword:[Upload Part] -// snippet-keyword:[Complete Multipart Upload] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.low_level_multipart_upload.complete] import com.amazonaws.AmazonServiceException; @@ -49,7 +26,7 @@ public static void main(String[] args) throws IOException { File file = new File(filePath); long contentLength = file.length(); - long partSize = 5 * 1024 * 1024; // Set part size to 5 MB. + long partSize = 5 * 1024 * 1024; // Set part size to 5 MB. try { AmazonS3 s3Client = AmazonS3ClientBuilder.standard() @@ -57,8 +34,9 @@ public static void main(String[] args) throws IOException { .withCredentials(new ProfileCredentialsProvider()) .build(); - // Create a list of ETag objects. You retrieve ETags for each object part uploaded, - // then, after each individual part has been uploaded, pass the list of ETags to + // Create a list of ETag objects. You retrieve ETags for each object part + // uploaded, + // then, after each individual part has been uploaded, pass the list of ETags to // the request to complete the upload. List partETags = new ArrayList(); @@ -69,7 +47,8 @@ public static void main(String[] args) throws IOException { // Upload the file parts. long filePosition = 0; for (int i = 1; filePosition < contentLength; i++) { - // Because the last part could be less than 5 MB, adjust the part size as needed. + // Because the last part could be less than 5 MB, adjust the part size as + // needed. partSize = Math.min(partSize, (contentLength - filePosition)); // Create the request to upload a part. @@ -94,7 +73,7 @@ public static void main(String[] args) throws IOException { initResponse.getUploadId(), partETags); s3Client.completeMultipartUpload(compRequest); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/MakingRequests.java b/java/example_code/s3/src/main/java/aws/example/s3/MakingRequests.java index d1ffcc8590d..dd818c580d2 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/MakingRequests.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/MakingRequests.java @@ -1,27 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[MakingRequests.java demonstrates how to make basic requests against Amazon S3 resources.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[GET Bucket] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.making_requests.complete] import com.amazonaws.AmazonServiceException; @@ -49,7 +28,7 @@ public static void main(String[] args) throws IOException { .withRegion(clientRegion) .build(); - // Get a list of objects in the bucket, two at a time, and + // Get a list of objects in the bucket, two at a time, and // print the name and size of each object. ListObjectsRequest listRequest = new ListObjectsRequest().withBucketName(bucketName).withMaxKeys(2); ObjectListing objects = s3Client.listObjects(listRequest); @@ -65,7 +44,7 @@ public static void main(String[] args) throws IOException { } } } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/MakingRequestsWithFederatedTempCredentials.java b/java/example_code/s3/src/main/java/aws/example/s3/MakingRequestsWithFederatedTempCredentials.java index 69df553b62a..6de59953617 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/MakingRequestsWithFederatedTempCredentials.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/MakingRequestsWithFederatedTempCredentials.java @@ -1,27 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[MakingRequestsWithFederatedTempCredentials.java demonstrates how to make requests against Amazon S3 using federated temporary credentials.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[GET Bucket] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.making_requests_with_federated_temp_credentials.complete] import com.amazonaws.AmazonServiceException; @@ -87,12 +66,12 @@ public static void main(String[] args) throws IOException { .withRegion(clientRegion) .build(); - // To verify that the client works, send a listObjects request using + // To verify that the client works, send a listObjects request using // the temporary security credentials. ObjectListing objects = s3Client.listObjects(bucketName); System.out.println("No. of Objects = " + objects.getObjectSummaries().size()); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/MakingRequestsWithIAMTempCredentials.java b/java/example_code/s3/src/main/java/aws/example/s3/MakingRequestsWithIAMTempCredentials.java index 93b4d701c57..a65a04ab350 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/MakingRequestsWithIAMTempCredentials.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/MakingRequestsWithIAMTempCredentials.java @@ -1,26 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[MakingRequestsWithIAMTempCredentials.java demonstrates how to assume an IAM role temporarily and use it to make requests against Amazon S3.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[GET Bucket] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.making_requests_with_IAM_temp_credentials.complete] import com.amazonaws.AmazonServiceException; @@ -48,43 +28,44 @@ public static void main(String[] args) { // Creating the STS client is part of your trusted code. It has // the security credentials you use to obtain temporary security credentials. AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard() - .withCredentials(new ProfileCredentialsProvider()) - .withRegion(clientRegion) - .build(); + .withCredentials(new ProfileCredentialsProvider()) + .withRegion(clientRegion) + .build(); - // Obtain credentials for the IAM role. Note that you cannot assume the role of an AWS root account; - // Amazon S3 will deny access. You must use credentials for an IAM user or an IAM role. + // Obtain credentials for the IAM role. Note that you cannot assume the role of + // an AWS root account; + // Amazon S3 will deny access. You must use credentials for an IAM user or an + // IAM role. AssumeRoleRequest roleRequest = new AssumeRoleRequest() - .withRoleArn(roleARN) - .withRoleSessionName(roleSessionName); + .withRoleArn(roleARN) + .withRoleSessionName(roleSessionName); AssumeRoleResult roleResponse = stsClient.assumeRole(roleRequest); Credentials sessionCredentials = roleResponse.getCredentials(); - - // Create a BasicSessionCredentials object that contains the credentials you just retrieved. + + // Create a BasicSessionCredentials object that contains the credentials you + // just retrieved. BasicSessionCredentials awsCredentials = new BasicSessionCredentials( sessionCredentials.getAccessKeyId(), sessionCredentials.getSecretAccessKey(), sessionCredentials.getSessionToken()); - // Provide temporary security credentials so that the Amazon S3 client - // can send authenticated requests to Amazon S3. You create the client - // using the sessionCredentials object. + // Provide temporary security credentials so that the Amazon S3 client + // can send authenticated requests to Amazon S3. You create the client + // using the sessionCredentials object. AmazonS3 s3Client = AmazonS3ClientBuilder.standard() - .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)) - .withRegion(clientRegion) - .build(); + .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)) + .withRegion(clientRegion) + .build(); // Verify that assuming the role worked and the permissions are set correctly // by getting a set of object keys from the bucket. ObjectListing objects = s3Client.listObjects(bucketName); System.out.println("No. of Objects: " + objects.getObjectSummaries().size()); - } - catch(AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + } catch (AmazonServiceException e) { + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); - } - catch(SdkClientException e) { + } catch (SdkClientException e) { // Amazon S3 couldn't be contacted for a response, or the client // couldn't parse the response from Amazon S3. e.printStackTrace(); diff --git a/java/example_code/s3/src/main/java/aws/example/s3/ManagingObjectTags.java b/java/example_code/s3/src/main/java/aws/example/s3/ManagingObjectTags.java index 4c465f4a643..7d4347d5a48 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/ManagingObjectTags.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/ManagingObjectTags.java @@ -1,28 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[ManagingObjectTags.java demonstrates how to set, get, and replace an S3 object's tags.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[GET Object tagging] -// snippet-keyword:[PUT Object tagging] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.managing_object_tags.complete] import com.amazonaws.AmazonServiceException; @@ -69,7 +47,7 @@ public static void main(String[] args) { newTags.add(new Tag("Tag 4", "This is tag 4")); s3Client.setObjectTagging(new SetObjectTaggingRequest(bucketName, keyName, new ObjectTagging(newTags))); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/ModifyACLExistingObject.java b/java/example_code/s3/src/main/java/aws/example/s3/ModifyACLExistingObject.java index d7d5f51fede..8a5983a42c3 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/ModifyACLExistingObject.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/ModifyACLExistingObject.java @@ -1,28 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[ModifyACLExistingObject.java demonstrates how to retrieve, modify, and set the ACL grants for an S3 object.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[GET Object acl] -// snippet-keyword:[PUT Object acl] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.modify_acl_existing_object.complete] import com.amazonaws.AmazonServiceException; @@ -58,14 +36,15 @@ public static void main(String[] args) throws IOException { // Clear the existing list of grants. acl.getGrantsAsList().clear(); - // Grant a sample set of permissions, using the existing ACL owner for Full Control permissions. + // Grant a sample set of permissions, using the existing ACL owner for Full + // Control permissions. acl.grantPermission(new CanonicalGrantee(acl.getOwner().getId()), Permission.FullControl); acl.grantPermission(new EmailAddressGrantee(emailGrantee), Permission.WriteAcp); // Save the modified ACL back to the object. s3Client.setObjectAcl(bucketName, keyName, acl); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/PutObject.java b/java/example_code/s3/src/main/java/aws/example/s3/PutObject.java index 9d5c852d8db..b4e84e7f243 100755 --- a/java/example_code/s3/src/main/java/aws/example/s3/PutObject.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/PutObject.java @@ -1,26 +1,5 @@ -//snippet-sourcedescription:[PutObject.java demonstrates how to upload a file to an Amazon S3 bucket.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[putObject] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.s3; import com.amazonaws.AmazonServiceException; diff --git a/java/example_code/s3/src/main/java/aws/example/s3/RestoreArchivedObject.java b/java/example_code/s3/src/main/java/aws/example/s3/RestoreArchivedObject.java index 48e91edf17b..b3d4aa653a9 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/RestoreArchivedObject.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/RestoreArchivedObject.java @@ -1,27 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[RestoreArchivedObject.java demonstrates how to restore an S3 object temporarily from a Glacier archive.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[POST Object restore] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.restore_archived_object.complete] import com.amazonaws.AmazonServiceException; @@ -58,7 +37,7 @@ public static void main(String[] args) throws IOException { System.out.format("Restoration status: %s.\n", restoreFlag ? "in progress" : "not in progress (finished or failed)"); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/S3ClientSideEncryptionAsymmetricMasterKey.java b/java/example_code/s3/src/main/java/aws/example/s3/S3ClientSideEncryptionAsymmetricMasterKey.java index 6958a3db8c7..f6232b80ad7 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/S3ClientSideEncryptionAsymmetricMasterKey.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/S3ClientSideEncryptionAsymmetricMasterKey.java @@ -1,28 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -// snippet-sourcedescription:[S3ClientSideEncryptionAsymmetricMasterKey.java demonstrates how to upload and download encrypted objects using S3 with a client-side asymmetric master key.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[PUT Object] -// snippet-keyword:[GET Object] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[s3.java.s3_client_side_encryption_asymmetric_master_key.complete] import com.amazonaws.AmazonServiceException; @@ -91,7 +69,7 @@ public static void main(String[] args) throws Exception { System.out.println("Plaintext: " + new String(plaintext)); System.out.println("Decrypted text: " + new String(decrypted)); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { @@ -102,9 +80,9 @@ public static void main(String[] args) throws Exception { } private static void saveKeyPair(String dir, - String publicKeyName, - String privateKeyName, - KeyPair keyPair) throws IOException { + String publicKeyName, + String privateKeyName, + KeyPair keyPair) throws IOException { PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); @@ -122,9 +100,9 @@ private static void saveKeyPair(String dir, } private static KeyPair loadKeyPair(String dir, - String publicKeyName, - String privateKeyName, - String algorithm) + String publicKeyName, + String privateKeyName, + String algorithm) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { // Read the public key from the specified file. File publicKeyFile = new File(dir + File.separator + publicKeyName); diff --git a/java/example_code/s3/src/main/java/aws/example/s3/S3ClientSideEncryptionSymMasterKey.java b/java/example_code/s3/src/main/java/aws/example/s3/S3ClientSideEncryptionSymMasterKey.java index be120d53612..2a7d2a02299 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/S3ClientSideEncryptionSymMasterKey.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/S3ClientSideEncryptionSymMasterKey.java @@ -1,28 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[S3ClientSideEncryptionSymMasterKey.java demonstrates how to upload and download encrypted objects using S3 with a client-side symmetric master key.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[PUT Object] -// snippet-keyword:[GET Object] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.s3_client_side_encryption_sym_master_key.complete] import com.amazonaws.AmazonServiceException; @@ -84,7 +62,7 @@ public static void main(String[] args) throws Exception { System.out.println("Plaintext: " + new String(plaintext)); System.out.println("Decrypted text: " + new String(decrypted)); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { @@ -94,7 +72,8 @@ public static void main(String[] args) throws Exception { } } - private static void saveSymmetricKey(String masterKeyDir, String masterKeyName, SecretKey secretKey) throws IOException { + private static void saveSymmetricKey(String masterKeyDir, String masterKeyName, SecretKey secretKey) + throws IOException { X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(secretKey.getEncoded()); FileOutputStream keyOutputStream = new FileOutputStream(masterKeyDir + File.separator + masterKeyName); keyOutputStream.write(x509EncodedKeySpec.getEncoded()); diff --git a/java/example_code/s3/src/main/java/aws/example/s3/S3Encrypt.java b/java/example_code/s3/src/main/java/aws/example/s3/S3Encrypt.java index f2615144cc6..4c86710313f 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/S3Encrypt.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/S3Encrypt.java @@ -1,344 +1,358 @@ -//snippet-sourcedescription:[This example is depreciated.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[AmazonS3Encryption] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ -package aws.example.s3; - -// snippet-start:[s3.java1.s3_encrypt.complete] -// snippet-start:[s3.java1.s3_encrypt.import] - -import com.amazonaws.regions.Region; -import com.amazonaws.regions.Regions; -import com.amazonaws.services.s3.AmazonS3; -import com.amazonaws.services.s3.AmazonS3ClientBuilder; -import com.amazonaws.services.s3.AmazonS3Encryption; -import com.amazonaws.services.s3.AmazonS3EncryptionClientBuilder; -import com.amazonaws.services.s3.model.*; - -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -// snippet-end:[s3.java1.s3_encrypt.import] - -/** - * This AWS Code Example is Depreciated. To encrypt S3 content, see the S3EncryptV2 example. - */ -public class S3Encrypt { - public static final String BUCKET_NAME = "bucketscott2"; //add your bucket name - public static final String ENCRYPTED_KEY = "enc-key"; - public static final String NON_ENCRYPTED_KEY = "some-key"; - - public static void main(String[] args) { - System.out.println("calling encryption with customer managed keys"); - S3Encrypt encrypt = new S3Encrypt(); - - try { - //can change to call the other encryption methods - encrypt.authenticatedEncryption_CustomerManagedKey(); - } catch (NoSuchAlgorithmException ex) { - System.out.println(ex.getMessage()); - } - } - - /** - * Uses AES/GCM with AESWrap key wrapping to encrypt the key. Uses v2 metadata schema. Note that authenticated - * encryption requires the bouncy castle provider to be on the classpath. Also, for authenticated encryption the size - * of the data can be no longer than 64 GB. - */ - // snippet-start:[s3.java1.s3_encrypt.authenticated_encryption] - public void authenticatedEncryption_CustomerManagedKey() throws NoSuchAlgorithmException { - // snippet-start:[s3.java1.s3_encrypt.authenticated_encryption_build] - - SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey(); - AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder - .standard() - .withRegion(Regions.US_WEST_2) - .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.AuthenticatedEncryption)) - .withEncryptionMaterials(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(secretKey))) - .build(); - - AmazonS3 s3NonEncrypt = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); - // snippet-end:[s3.java1.s3_encrypt.authenticated_encryption_build] - - s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); - s3NonEncrypt.putObject(BUCKET_NAME, NON_ENCRYPTED_KEY, "some other contents"); - System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, ENCRYPTED_KEY)); - System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, NON_ENCRYPTED_KEY)); - } - // snippet-end:[s3.java1.s3_encrypt.authenticated_encryption] - - /** - * For ranged GET we do not use authenticated encryption since we aren't reading the entire message and can't produce the - * MAC. Instead we use AES/CTR, an unauthenticated encryption algorithm. If {@link CryptoMode#StrictAuthenticatedEncryption} - * is enabled, ranged GETs will not be allowed since they do not use authenticated encryption.. - */ - - public void authenticatedEncryption_RangeGet_CustomerManagedKey() throws NoSuchAlgorithmException { - SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey(); - AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder - .standard() - .withRegion(Regions.US_WEST_2) - .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.AuthenticatedEncryption)) - .withEncryptionMaterials(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(secretKey))) - .build(); - - AmazonS3 s3NonEncrypt = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); - - s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); - s3NonEncrypt.putObject(BUCKET_NAME, NON_ENCRYPTED_KEY, "some other contents"); - System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, ENCRYPTED_KEY)); - System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, NON_ENCRYPTED_KEY)); - } - - - /** - * Same as {@link #authenticatedEncryption_CustomerManagedKey()} except uses an asymmetric key pair and - * RSA/ECB/OAEPWithSHA-256AndMGF1Padding as the key wrapping algorithm. - */ - public void authenticatedEncryption_CustomerManagedAsymmetricKey() throws NoSuchAlgorithmException { - KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); - AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder - .standard() - .withRegion(Regions.US_WEST_2) - .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.AuthenticatedEncryption)) - .withEncryptionMaterials(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(keyPair))) - .build(); - - AmazonS3 s3NonEncrypt = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); - - s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); - s3NonEncrypt.putObject(BUCKET_NAME, NON_ENCRYPTED_KEY, "some other contents"); - System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, ENCRYPTED_KEY)); - System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, NON_ENCRYPTED_KEY)); - } - - /** - * Uses AES/GCM with AESWrap key wrapping to encrypt the key. Uses v2 metadata schema. The only difference between this and - * {@link #authenticatedEncryption_CustomerManagedKey()} is that attempting to retrieve an object non - * encrypted with AES/GCM will thrown an exception instead of falling back to encryption only or plaintext GET. - */ - // snippet-start:[s3.java1.s3_encrypt.strict_authenticated_encryption] - public void strictAuthenticatedEncryption_CustomerManagedKey() throws NoSuchAlgorithmException { - // snippet-start:[s3.java1.s3_encrypt.strict_authenticated_encryption_build] - SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey(); - AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder - .standard() - .withRegion(Regions.US_WEST_2) - .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.StrictAuthenticatedEncryption)) - .withEncryptionMaterials(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(secretKey))) - .build(); - - AmazonS3 s3NonEncrypt = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); - // snippet-end:[s3.java1.s3_encrypt.strict_authenticated_encryption_build] - - s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); - s3NonEncrypt.putObject(BUCKET_NAME, NON_ENCRYPTED_KEY, "some other contents"); - System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, ENCRYPTED_KEY)); - try { - s3Encryption.getObjectAsString(BUCKET_NAME, NON_ENCRYPTED_KEY); - } catch (SecurityException e) { - // Strict authenticated encryption will throw an exception if an object is not encrypted with AES/GCM - System.err.println(NON_ENCRYPTED_KEY + " was not encrypted with AES/GCM"); - } - } - // snippet-end:[s3.java1.s3_encrypt.strict_authenticated_encryption] - - /** - * Strict authenticated encryption mode does not support ranged GETs. This is because we must use AES/CTR for ranged - * GETs which is not an authenticated encryption algorithm. To do a partial get using authenticated encryption you have to - * get the whole object and filter to the data you want. - */ - public void strictAuthenticatedEncryption_RangeGet_CustomerManagedKey() throws NoSuchAlgorithmException { - SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey(); - AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder - .standard() - .withRegion(Regions.US_WEST_2) - .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.StrictAuthenticatedEncryption)) - .withEncryptionMaterials(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(secretKey))) - .build(); - - s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); - try { - s3Encryption.getObject(new GetObjectRequest(BUCKET_NAME, ENCRYPTED_KEY).withRange(0, 2)); - } catch (SecurityException e) { - System.err.println("Range GET is not supported with authenticated encryption"); - } - } - - /** - * Uses AES/CBC algorithm, no key wrapping. - */ - public void encryptionOnly_CustomerManagedKey() throws NoSuchAlgorithmException { - SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey(); - AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder - .standard() - .withRegion(Regions.US_WEST_2) - .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.EncryptionOnly)) - .withEncryptionMaterials(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(secretKey))) - .build(); - - AmazonS3 s3NonEncrypt = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); - - s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); - s3NonEncrypt.putObject(BUCKET_NAME, NON_ENCRYPTED_KEY, "some other contents"); - System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, ENCRYPTED_KEY)); - System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, NON_ENCRYPTED_KEY)); - } - - /** - * Non-authenticated encryption schemes can do range GETs without an issue. - */ - // snippet-start:[s3.java1.s3_encrypt.encryption_only] - public void encryptionOnly_RangeGet_CustomerManagedKey() throws NoSuchAlgorithmException { - SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey(); - AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder - .standard() - .withRegion(Regions.US_WEST_2) - .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.EncryptionOnly)) - .withEncryptionMaterials(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(secretKey))) - .build(); - - s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); - System.out.println(s3Encryption.getObject(new GetObjectRequest(BUCKET_NAME, ENCRYPTED_KEY) - .withRange(0, 2))); - } - // snippet-end:[s3.java1.s3_encrypt.encryption_only] - - /** - * Uses an asymmetric key pair instead of a symmetric key. Note this does not change the algorithm used to encrypt - * the content, that will still be a symmetric key algorithm (AES/CBC in this case) using the derived CEK. It does impact - * the algorithm used to encrypt the CEK, in this case we use RSA/ECB/OAEPWithSHA-256AndMGF1Padding. - */ - // snippet-start:[s3.java1.s3_encrypt.encryption_only_asymetric_key] - public void encryptionOnly_CustomerManagedAsymetricKey() throws NoSuchAlgorithmException { - // snippet-start:[s3.java1.s3_encrypt.encryption_only_asymetric_key_build] - KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); - AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder - .standard() - .withRegion(Regions.US_WEST_2) - .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.EncryptionOnly)) - .withEncryptionMaterials(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(keyPair))) - .build(); - - AmazonS3 s3NonEncrypt = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); - // snippet-end:[s3.java1.s3_encrypt.encryption_only_asymetric_key_build] - - // snippet-start:[s3.java1.s3_encrypt.encryption_only_asymetric_key_put_object] - s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); - s3NonEncrypt.putObject(BUCKET_NAME, NON_ENCRYPTED_KEY, "some other contents"); - // snippet-end:[s3.java1.s3_encrypt.encryption_only_asymetric_key_put_object] - // snippet-start:[s3.java1.s3_encrypt.encryption_only_asymetric_key_retrieve] - System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, ENCRYPTED_KEY)); - System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, NON_ENCRYPTED_KEY)); - // snippet-end:[s3.java1.s3_encrypt.encryption_only_asymetric_key_retrieve] - } - // snippet-end:[s3.java1.s3_encrypt.encryption_only_asymetric_key] - - /** - * This uses the V2 metadata schema with a key wrap algorithm of 'kms' and a CEK algorithm of AES/CBC/PKCS5Padding. - */ - // snippet-start:[s3.java1.s3_encrypt.kms_encryption_only] - public void encryptionOnly_KmsManagedKey() throws NoSuchAlgorithmException { - // snippet-start:[s3.java1.s3_encrypt.kms_encryption_only_build] - AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder - .standard() - .withRegion(Regions.US_WEST_2) - .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.EncryptionOnly).withAwsKmsRegion(Region.getRegion(Regions.US_WEST_2))) - // Can either be Key ID or alias (prefixed with 'alias/') - .withEncryptionMaterials(new KMSEncryptionMaterialsProvider("alias/s3-kms-key")) - .build(); - - AmazonS3 s3NonEncrypt = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); - // snippet-end:[s3.java1.s3_encrypt.kms_encryption_only_build] - - // snippet-start:[s3.java1.s3_encrypt.kms_encryption_only_put_object] - s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); - s3NonEncrypt.putObject(BUCKET_NAME, NON_ENCRYPTED_KEY, "some other contents"); - // snippet-end:[s3.java1.s3_encrypt.kms_encryption_only_put_object] - // snippet-start:[s3.java1.s3_encrypt.kms_encryption_only_retrieve] - System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, ENCRYPTED_KEY)); - System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, NON_ENCRYPTED_KEY)); - // snippet-end:[s3.java1.s3_encrypt.kms_encryption_only_retrieve] - } - // snippet-end:[s3.java1.s3_encrypt.kms_encryption_only] - - /** - * This uses the V2 metadata schema with a key wrap algorithm of 'kms' and a CEK algorithm of AES/GCM/NoPadding. - */ - // snippet-start:[s3.java1.s3_encrypt.kms_authenticated_encryption] - public void authenticatedEncryption_KmsManagedKey() throws NoSuchAlgorithmException { - // snippet-start:[s3.java1.s3_encrypt.kms_authenticated_encryption_builder] - AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder - .standard() - .withRegion(Regions.US_WEST_2) - .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.AuthenticatedEncryption).withAwsKmsRegion(Region.getRegion(Regions.US_WEST_2))) - // Can either be Key ID or alias (prefixed with 'alias/') - .withEncryptionMaterials(new KMSEncryptionMaterialsProvider("alias/s3-kms-key")) - .build(); - - AmazonS3 s3NonEncrypt = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); - // snippet-end:[s3.java1.s3_encrypt.kms_authenticated_encryption_builder] - - // snippet-start:[s3.java1.s3_encrypt.kms_authenticated_encryption_put_object] - s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); - s3NonEncrypt.putObject(BUCKET_NAME, NON_ENCRYPTED_KEY, "some other contents"); - System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, ENCRYPTED_KEY)); - System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, NON_ENCRYPTED_KEY)); - // snippet-end:[s3.java1.s3_encrypt.kms_authenticated_encryption_put_object] - } - // snippet-end:[s3.java1.s3_encrypt.kms_authenticated_encryption] - - /** - * Same as authenticatedEncryption_KmsManagedKey except throws an exception when trying to get objects not encrypted with - * AES/GCM. - */ - // snippet-start:[s3.java1.s3_encrypt.kms_authenticated_encryption_strict] - public void strictAuthenticatedEncryption_KmsManagedKey() throws NoSuchAlgorithmException { - // snippet-start:[s3.java1.s3_encrypt.kms_authenticated_encryption_strict_builder] - AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder - .standard() - .withRegion(Regions.US_WEST_2) - .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.StrictAuthenticatedEncryption).withAwsKmsRegion(Region.getRegion(Regions.US_WEST_2))) - // Can either be Key ID or alias (prefixed with 'alias/') - .withEncryptionMaterials(new KMSEncryptionMaterialsProvider("alias/s3-kms-key")) - .build(); - - AmazonS3 s3NonEncrypt = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); - // snippet-end:[s3.java1.s3_encrypt.kms_authenticated_encryption_strict_builder] - - // snippet-start:[s3.java1.s3_encrypt.kms_authenticated_encryption_strict_put_object] - s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); - s3NonEncrypt.putObject(BUCKET_NAME, NON_ENCRYPTED_KEY, "some other contents"); - // snippet-end:[s3.java1.s3_encrypt.kms_authenticated_encryption_strict_put_object] - // snippet-start:[s3.java1.s3_encrypt.kms_authenticated_encryption_strict_exception] - try { - s3Encryption.getObjectAsString(BUCKET_NAME, NON_ENCRYPTED_KEY); - } catch (SecurityException e) { - // Strict authenticated encryption will throw an exception if an object is not encrypted with AES/GCM - System.err.println(NON_ENCRYPTED_KEY + " was not encrypted with AES/GCM"); - } - - // snippet-end:[s3.java1.s3_encrypt.kms_authenticated_encryption_strict_exception] - } - // snippet-end:[s3.java1.s3_encrypt.kms_authenticated_encryption_strict] - -} -// snippet-end:[s3.java1.s3_encrypt.complete] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* + Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + This file is 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/ + This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. See the License for the + specific language governing permissions and limitations under the License. +*/ +package aws.example.s3; + +// snippet-start:[s3.java1.s3_encrypt.complete] +// snippet-start:[s3.java1.s3_encrypt.import] + +import com.amazonaws.regions.Region; +import com.amazonaws.regions.Regions; +import com.amazonaws.services.s3.AmazonS3; +import com.amazonaws.services.s3.AmazonS3ClientBuilder; +import com.amazonaws.services.s3.AmazonS3Encryption; +import com.amazonaws.services.s3.AmazonS3EncryptionClientBuilder; +import com.amazonaws.services.s3.model.*; + +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +// snippet-end:[s3.java1.s3_encrypt.import] + +/** + * This AWS Code Example is Depreciated. To encrypt S3 content, see the + * S3EncryptV2 example. + */ +public class S3Encrypt { + public static final String BUCKET_NAME = "bucketscott2"; // add your bucket name + public static final String ENCRYPTED_KEY = "enc-key"; + public static final String NON_ENCRYPTED_KEY = "some-key"; + + public static void main(String[] args) { + System.out.println("calling encryption with customer managed keys"); + S3Encrypt encrypt = new S3Encrypt(); + + try { + // can change to call the other encryption methods + encrypt.authenticatedEncryption_CustomerManagedKey(); + } catch (NoSuchAlgorithmException ex) { + System.out.println(ex.getMessage()); + } + } + + /** + * Uses AES/GCM with AESWrap key wrapping to encrypt the key. Uses v2 metadata + * schema. Note that authenticated + * encryption requires the bouncy castle provider to be on the classpath. Also, + * for authenticated encryption the size + * of the data can be no longer than 64 GB. + */ + // snippet-start:[s3.java1.s3_encrypt.authenticated_encryption] + public void authenticatedEncryption_CustomerManagedKey() throws NoSuchAlgorithmException { + // snippet-start:[s3.java1.s3_encrypt.authenticated_encryption_build] + + SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey(); + AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder + .standard() + .withRegion(Regions.US_WEST_2) + .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.AuthenticatedEncryption)) + .withEncryptionMaterials(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(secretKey))) + .build(); + + AmazonS3 s3NonEncrypt = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); + // snippet-end:[s3.java1.s3_encrypt.authenticated_encryption_build] + + s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); + s3NonEncrypt.putObject(BUCKET_NAME, NON_ENCRYPTED_KEY, "some other contents"); + System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, ENCRYPTED_KEY)); + System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, NON_ENCRYPTED_KEY)); + } + // snippet-end:[s3.java1.s3_encrypt.authenticated_encryption] + + /** + * For ranged GET we do not use authenticated encryption since we aren't reading + * the entire message and can't produce the + * MAC. Instead we use AES/CTR, an unauthenticated encryption algorithm. If + * {@link CryptoMode#StrictAuthenticatedEncryption} + * is enabled, ranged GETs will not be allowed since they do not use + * authenticated encryption.. + */ + + public void authenticatedEncryption_RangeGet_CustomerManagedKey() throws NoSuchAlgorithmException { + SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey(); + AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder + .standard() + .withRegion(Regions.US_WEST_2) + .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.AuthenticatedEncryption)) + .withEncryptionMaterials(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(secretKey))) + .build(); + + AmazonS3 s3NonEncrypt = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); + + s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); + s3NonEncrypt.putObject(BUCKET_NAME, NON_ENCRYPTED_KEY, "some other contents"); + System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, ENCRYPTED_KEY)); + System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, NON_ENCRYPTED_KEY)); + } + + /** + * Same as {@link #authenticatedEncryption_CustomerManagedKey()} except uses an + * asymmetric key pair and + * RSA/ECB/OAEPWithSHA-256AndMGF1Padding as the key wrapping algorithm. + */ + public void authenticatedEncryption_CustomerManagedAsymmetricKey() throws NoSuchAlgorithmException { + KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); + AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder + .standard() + .withRegion(Regions.US_WEST_2) + .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.AuthenticatedEncryption)) + .withEncryptionMaterials(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(keyPair))) + .build(); + + AmazonS3 s3NonEncrypt = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); + + s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); + s3NonEncrypt.putObject(BUCKET_NAME, NON_ENCRYPTED_KEY, "some other contents"); + System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, ENCRYPTED_KEY)); + System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, NON_ENCRYPTED_KEY)); + } + + /** + * Uses AES/GCM with AESWrap key wrapping to encrypt the key. Uses v2 metadata + * schema. The only difference between this and + * {@link #authenticatedEncryption_CustomerManagedKey()} is that attempting to + * retrieve an object non + * encrypted with AES/GCM will thrown an exception instead of falling back to + * encryption only or plaintext GET. + */ + // snippet-start:[s3.java1.s3_encrypt.strict_authenticated_encryption] + public void strictAuthenticatedEncryption_CustomerManagedKey() throws NoSuchAlgorithmException { + // snippet-start:[s3.java1.s3_encrypt.strict_authenticated_encryption_build] + SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey(); + AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder + .standard() + .withRegion(Regions.US_WEST_2) + .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.StrictAuthenticatedEncryption)) + .withEncryptionMaterials(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(secretKey))) + .build(); + + AmazonS3 s3NonEncrypt = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); + // snippet-end:[s3.java1.s3_encrypt.strict_authenticated_encryption_build] + + s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); + s3NonEncrypt.putObject(BUCKET_NAME, NON_ENCRYPTED_KEY, "some other contents"); + System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, ENCRYPTED_KEY)); + try { + s3Encryption.getObjectAsString(BUCKET_NAME, NON_ENCRYPTED_KEY); + } catch (SecurityException e) { + // Strict authenticated encryption will throw an exception if an object is not + // encrypted with AES/GCM + System.err.println(NON_ENCRYPTED_KEY + " was not encrypted with AES/GCM"); + } + } + // snippet-end:[s3.java1.s3_encrypt.strict_authenticated_encryption] + + /** + * Strict authenticated encryption mode does not support ranged GETs. This is + * because we must use AES/CTR for ranged + * GETs which is not an authenticated encryption algorithm. To do a partial get + * using authenticated encryption you have to + * get the whole object and filter to the data you want. + */ + public void strictAuthenticatedEncryption_RangeGet_CustomerManagedKey() throws NoSuchAlgorithmException { + SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey(); + AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder + .standard() + .withRegion(Regions.US_WEST_2) + .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.StrictAuthenticatedEncryption)) + .withEncryptionMaterials(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(secretKey))) + .build(); + + s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); + try { + s3Encryption.getObject(new GetObjectRequest(BUCKET_NAME, ENCRYPTED_KEY).withRange(0, 2)); + } catch (SecurityException e) { + System.err.println("Range GET is not supported with authenticated encryption"); + } + } + + /** + * Uses AES/CBC algorithm, no key wrapping. + */ + public void encryptionOnly_CustomerManagedKey() throws NoSuchAlgorithmException { + SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey(); + AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder + .standard() + .withRegion(Regions.US_WEST_2) + .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.EncryptionOnly)) + .withEncryptionMaterials(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(secretKey))) + .build(); + + AmazonS3 s3NonEncrypt = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); + + s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); + s3NonEncrypt.putObject(BUCKET_NAME, NON_ENCRYPTED_KEY, "some other contents"); + System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, ENCRYPTED_KEY)); + System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, NON_ENCRYPTED_KEY)); + } + + /** + * Non-authenticated encryption schemes can do range GETs without an issue. + */ + // snippet-start:[s3.java1.s3_encrypt.encryption_only] + public void encryptionOnly_RangeGet_CustomerManagedKey() throws NoSuchAlgorithmException { + SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey(); + AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder + .standard() + .withRegion(Regions.US_WEST_2) + .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.EncryptionOnly)) + .withEncryptionMaterials(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(secretKey))) + .build(); + + s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); + System.out.println(s3Encryption.getObject(new GetObjectRequest(BUCKET_NAME, ENCRYPTED_KEY) + .withRange(0, 2))); + } + // snippet-end:[s3.java1.s3_encrypt.encryption_only] + + /** + * Uses an asymmetric key pair instead of a symmetric key. Note this does not + * change the algorithm used to encrypt + * the content, that will still be a symmetric key algorithm (AES/CBC in this + * case) using the derived CEK. It does impact + * the algorithm used to encrypt the CEK, in this case we use + * RSA/ECB/OAEPWithSHA-256AndMGF1Padding. + */ + // snippet-start:[s3.java1.s3_encrypt.encryption_only_asymetric_key] + public void encryptionOnly_CustomerManagedAsymetricKey() throws NoSuchAlgorithmException { + // snippet-start:[s3.java1.s3_encrypt.encryption_only_asymetric_key_build] + KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); + AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder + .standard() + .withRegion(Regions.US_WEST_2) + .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.EncryptionOnly)) + .withEncryptionMaterials(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(keyPair))) + .build(); + + AmazonS3 s3NonEncrypt = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); + // snippet-end:[s3.java1.s3_encrypt.encryption_only_asymetric_key_build] + + // snippet-start:[s3.java1.s3_encrypt.encryption_only_asymetric_key_put_object] + s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); + s3NonEncrypt.putObject(BUCKET_NAME, NON_ENCRYPTED_KEY, "some other contents"); + // snippet-end:[s3.java1.s3_encrypt.encryption_only_asymetric_key_put_object] + // snippet-start:[s3.java1.s3_encrypt.encryption_only_asymetric_key_retrieve] + System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, ENCRYPTED_KEY)); + System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, NON_ENCRYPTED_KEY)); + // snippet-end:[s3.java1.s3_encrypt.encryption_only_asymetric_key_retrieve] + } + // snippet-end:[s3.java1.s3_encrypt.encryption_only_asymetric_key] + + /** + * This uses the V2 metadata schema with a key wrap algorithm of 'kms' and a CEK + * algorithm of AES/CBC/PKCS5Padding. + */ + // snippet-start:[s3.java1.s3_encrypt.kms_encryption_only] + public void encryptionOnly_KmsManagedKey() throws NoSuchAlgorithmException { + // snippet-start:[s3.java1.s3_encrypt.kms_encryption_only_build] + AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder + .standard() + .withRegion(Regions.US_WEST_2) + .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.EncryptionOnly) + .withAwsKmsRegion(Region.getRegion(Regions.US_WEST_2))) + // Can either be Key ID or alias (prefixed with 'alias/') + .withEncryptionMaterials(new KMSEncryptionMaterialsProvider("alias/s3-kms-key")) + .build(); + + AmazonS3 s3NonEncrypt = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); + // snippet-end:[s3.java1.s3_encrypt.kms_encryption_only_build] + + // snippet-start:[s3.java1.s3_encrypt.kms_encryption_only_put_object] + s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); + s3NonEncrypt.putObject(BUCKET_NAME, NON_ENCRYPTED_KEY, "some other contents"); + // snippet-end:[s3.java1.s3_encrypt.kms_encryption_only_put_object] + // snippet-start:[s3.java1.s3_encrypt.kms_encryption_only_retrieve] + System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, ENCRYPTED_KEY)); + System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, NON_ENCRYPTED_KEY)); + // snippet-end:[s3.java1.s3_encrypt.kms_encryption_only_retrieve] + } + // snippet-end:[s3.java1.s3_encrypt.kms_encryption_only] + + /** + * This uses the V2 metadata schema with a key wrap algorithm of 'kms' and a CEK + * algorithm of AES/GCM/NoPadding. + */ + // snippet-start:[s3.java1.s3_encrypt.kms_authenticated_encryption] + public void authenticatedEncryption_KmsManagedKey() throws NoSuchAlgorithmException { + // snippet-start:[s3.java1.s3_encrypt.kms_authenticated_encryption_builder] + AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder + .standard() + .withRegion(Regions.US_WEST_2) + .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.AuthenticatedEncryption) + .withAwsKmsRegion(Region.getRegion(Regions.US_WEST_2))) + // Can either be Key ID or alias (prefixed with 'alias/') + .withEncryptionMaterials(new KMSEncryptionMaterialsProvider("alias/s3-kms-key")) + .build(); + + AmazonS3 s3NonEncrypt = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); + // snippet-end:[s3.java1.s3_encrypt.kms_authenticated_encryption_builder] + + // snippet-start:[s3.java1.s3_encrypt.kms_authenticated_encryption_put_object] + s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); + s3NonEncrypt.putObject(BUCKET_NAME, NON_ENCRYPTED_KEY, "some other contents"); + System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, ENCRYPTED_KEY)); + System.out.println(s3Encryption.getObjectAsString(BUCKET_NAME, NON_ENCRYPTED_KEY)); + // snippet-end:[s3.java1.s3_encrypt.kms_authenticated_encryption_put_object] + } + // snippet-end:[s3.java1.s3_encrypt.kms_authenticated_encryption] + + /** + * Same as authenticatedEncryption_KmsManagedKey except throws an exception when + * trying to get objects not encrypted with + * AES/GCM. + */ + // snippet-start:[s3.java1.s3_encrypt.kms_authenticated_encryption_strict] + public void strictAuthenticatedEncryption_KmsManagedKey() throws NoSuchAlgorithmException { + // snippet-start:[s3.java1.s3_encrypt.kms_authenticated_encryption_strict_builder] + AmazonS3Encryption s3Encryption = AmazonS3EncryptionClientBuilder + .standard() + .withRegion(Regions.US_WEST_2) + .withCryptoConfiguration(new CryptoConfiguration(CryptoMode.StrictAuthenticatedEncryption) + .withAwsKmsRegion(Region.getRegion(Regions.US_WEST_2))) + // Can either be Key ID or alias (prefixed with 'alias/') + .withEncryptionMaterials(new KMSEncryptionMaterialsProvider("alias/s3-kms-key")) + .build(); + + AmazonS3 s3NonEncrypt = AmazonS3ClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); + // snippet-end:[s3.java1.s3_encrypt.kms_authenticated_encryption_strict_builder] + + // snippet-start:[s3.java1.s3_encrypt.kms_authenticated_encryption_strict_put_object] + s3Encryption.putObject(BUCKET_NAME, ENCRYPTED_KEY, "some contents"); + s3NonEncrypt.putObject(BUCKET_NAME, NON_ENCRYPTED_KEY, "some other contents"); + // snippet-end:[s3.java1.s3_encrypt.kms_authenticated_encryption_strict_put_object] + // snippet-start:[s3.java1.s3_encrypt.kms_authenticated_encryption_strict_exception] + try { + s3Encryption.getObjectAsString(BUCKET_NAME, NON_ENCRYPTED_KEY); + } catch (SecurityException e) { + // Strict authenticated encryption will throw an exception if an object is not + // encrypted with AES/GCM + System.err.println(NON_ENCRYPTED_KEY + " was not encrypted with AES/GCM"); + } + + // snippet-end:[s3.java1.s3_encrypt.kms_authenticated_encryption_strict_exception] + } + // snippet-end:[s3.java1.s3_encrypt.kms_authenticated_encryption_strict] + +} +// snippet-end:[s3.java1.s3_encrypt.complete] diff --git a/java/example_code/s3/src/main/java/aws/example/s3/S3EncryptV2.java b/java/example_code/s3/src/main/java/aws/example/s3/S3EncryptV2.java index a9639552777..b8b47b305db 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/S3EncryptV2.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/S3EncryptV2.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[S3EncryptV2.java demonstrates how to encrypt S3 content by using the AmazonS3EncryptionV2 object] -//snippet-keyword:[SDK for Java] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[8/6/2020] -//snippet-sourceauthor:[scmacdon] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. @@ -58,7 +53,8 @@ public static void main(String[] args) throws NoSuchAlgorithmException { .withRegion(Regions.DEFAULT_REGION) .build(); - // create a bucket for testing; will be deleted automatically upon successful completion + // create a bucket for testing; will be deleted automatically upon successful + // completion // of this example try { s3Client.createBucket(bucketName); @@ -73,9 +69,7 @@ public static void main(String[] args) throws NoSuchAlgorithmException { try { ObjectListing objectListing = s3Client.listObjects(bucketName); while (true) { - for (Iterator iterator = - objectListing.getObjectSummaries().iterator(); - iterator.hasNext(); ) { + for (Iterator iterator = objectListing.getObjectSummaries().iterator(); iterator.hasNext();) { S3ObjectSummary summary = (S3ObjectSummary) iterator.next(); s3Client.deleteObject(bucketName, summary.getKey()); } @@ -116,8 +110,10 @@ public static void putEncryptedData1() throws NoSuchAlgorithmException { AmazonS3EncryptionV2 s3Encryption = AmazonS3EncryptionClientV2Builder.standard() .withRegion(Regions.DEFAULT_REGION) .withClientConfiguration(new ClientConfiguration()) - .withCryptoConfiguration(new CryptoConfigurationV2().withCryptoMode(CryptoMode.StrictAuthenticatedEncryption)) - .withEncryptionMaterialsProvider(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(secretKey))) + .withCryptoConfiguration( + new CryptoConfigurationV2().withCryptoMode(CryptoMode.StrictAuthenticatedEncryption)) + .withEncryptionMaterialsProvider( + new StaticEncryptionMaterialsProvider(new EncryptionMaterials(secretKey))) .build(); s3Encryption.putObject(bucketName, s3ObjectKey, s3ObjectContent); @@ -142,8 +138,10 @@ public static void putEncryptedData2() throws NoSuchAlgorithmException { AmazonS3EncryptionV2 s3Encryption = AmazonS3EncryptionClientV2Builder.standard() .withRegion(Regions.US_WEST_2) - .withCryptoConfiguration(new CryptoConfigurationV2().withCryptoMode(CryptoMode.StrictAuthenticatedEncryption)) - .withEncryptionMaterialsProvider(new StaticEncryptionMaterialsProvider(new EncryptionMaterials(keyPair))) + .withCryptoConfiguration( + new CryptoConfigurationV2().withCryptoMode(CryptoMode.StrictAuthenticatedEncryption)) + .withEncryptionMaterialsProvider( + new StaticEncryptionMaterialsProvider(new EncryptionMaterials(keyPair))) .build(); s3Encryption.putObject(bucketName, s3ObjectKey, s3ObjectContent); @@ -172,7 +170,8 @@ public static void putEncryptedData3_Kms() { AmazonS3EncryptionV2 s3Encryption = AmazonS3EncryptionClientV2Builder.standard() .withRegion(Regions.US_WEST_2) - .withCryptoConfiguration(new CryptoConfigurationV2().withCryptoMode(CryptoMode.StrictAuthenticatedEncryption)) + .withCryptoConfiguration( + new CryptoConfigurationV2().withCryptoMode(CryptoMode.StrictAuthenticatedEncryption)) .withEncryptionMaterialsProvider(new KMSEncryptionMaterialsProvider(keyId)) .build(); @@ -180,12 +179,12 @@ public static void putEncryptedData3_Kms() { System.out.println(s3Encryption.getObjectAsString(bucketName, s3ObjectKey)); // schedule deletion of CMK generated for testing - ScheduleKeyDeletionRequest scheduleKeyDeletionRequest = - new ScheduleKeyDeletionRequest().withKeyId(keyId).withPendingWindowInDays(7); + ScheduleKeyDeletionRequest scheduleKeyDeletionRequest = new ScheduleKeyDeletionRequest().withKeyId(keyId) + .withPendingWindowInDays(7); kmsClient.scheduleKeyDeletion(scheduleKeyDeletionRequest); s3Encryption.shutdown(); kmsClient.shutdown(); - // snippet-end:[s3.java.s3_cse-v2.kms] + // snippet-end:[s3.java.s3_cse-v2.kms] } } diff --git a/java/example_code/s3/src/main/java/aws/example/s3/ServerSideEncryptionCopyObjectUsingHLwithSSEC.java b/java/example_code/s3/src/main/java/aws/example/s3/ServerSideEncryptionCopyObjectUsingHLwithSSEC.java index c32e894c458..5193a0c2442 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/ServerSideEncryptionCopyObjectUsingHLwithSSEC.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/ServerSideEncryptionCopyObjectUsingHLwithSSEC.java @@ -1,27 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[ServerSideEncryptionCopyObjectUsingHLwithSSEC.java demonstrates how to perform various operations with the high-level TransferManager class using S3 server-side encryption with a customer-generated encryption key.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[PUT Object] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.server_side_encryption_copy_object_using_hl_with_sse_c.complete] import com.amazonaws.AmazonServiceException; @@ -68,7 +47,8 @@ public static void main(String[] args) throws Exception { keyGenerator.init(256, new SecureRandom()); SSECustomerKey sseCustomerEncryptionKey = new SSECustomerKey(keyGenerator.generateKey()); - // Upload the object. TransferManager uploads asynchronously, so this call returns immediately. + // Upload the object. TransferManager uploads asynchronously, so this call + // returns immediately. putObjectRequest.setSSECustomerKey(sseCustomerEncryptionKey); Upload upload = tm.upload(putObjectRequest); @@ -82,14 +62,15 @@ public static void main(String[] args) throws Exception { copyObjectRequest.setSourceSSECustomerKey(sseCustomerEncryptionKey); copyObjectRequest.setDestinationSSECustomerKey(sseTargetObjectEncryptionKey); - // Copy the object. TransferManager copies asynchronously, so this call returns immediately. + // Copy the object. TransferManager copies asynchronously, so this call returns + // immediately. Copy copy = tm.copy(copyObjectRequest); // Optionally, wait for the upload to finish before continuing. copy.waitForCompletion(); System.out.println("Copy complete."); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/ServerSideEncryptionUsingClientSideEncryptionKey.java b/java/example_code/s3/src/main/java/aws/example/s3/ServerSideEncryptionUsingClientSideEncryptionKey.java index fce638283cb..1c1815bb8c0 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/ServerSideEncryptionUsingClientSideEncryptionKey.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/ServerSideEncryptionUsingClientSideEncryptionKey.java @@ -1,29 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -// snippet-sourcedescription:[ServerSideEncryptionUsingClientSideEncryptionKey.java demonstrates how to perform various operations with S3 using server-side encryption with a customer-provided encryption key.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[GET Object] -// snippet-keyword:[PUT Object] -// snippet-keyword:[HEAD Object] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[s3.java.server_side_encryption_using_client_side_encryption_key.complete] import com.amazonaws.AmazonServiceException; @@ -78,7 +55,7 @@ public static void main(String[] args) throws IOException, NoSuchAlgorithmExcept // Copy the object into a new object that also uses SSE-C. copyObject(bucketName, keyName, targetKeyName); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { @@ -111,7 +88,8 @@ private static void retrieveObjectMetadata(String bucketName, String keyName) { private static void copyObject(String bucketName, String keyName, String targetKeyName) throws NoSuchAlgorithmException { - // Create a new encryption key for target so that the target is saved using SSE-C. + // Create a new encryption key for target so that the target is saved using + // SSE-C. SSECustomerKey newSSEKey = new SSECustomerKey(KEY_GENERATOR.generateKey()); CopyObjectRequest copyRequest = new CopyObjectRequest(bucketName, keyName, bucketName, targetKeyName) diff --git a/java/example_code/s3/src/main/java/aws/example/s3/SetAcl.java b/java/example_code/s3/src/main/java/aws/example/s3/SetAcl.java index 706ef975af8..0bfba22aa80 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/SetAcl.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/SetAcl.java @@ -1,27 +1,5 @@ -//snippet-sourcedescription:[SetAcl.java demonstrates how to add an access policy to an existing S3 bucket or object.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[setBucketAcl] -//snippet-keyword:[setObjectAcl] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* -Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -This file is 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/ - -This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -CONDITIONS OF ANY KIND, either express or implied. See the License for the -specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.s3; import com.amazonaws.AmazonServiceException; diff --git a/java/example_code/s3/src/main/java/aws/example/s3/SetBucketPolicy.java b/java/example_code/s3/src/main/java/aws/example/s3/SetBucketPolicy.java index eed8cb2aea1..6dca612ba38 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/SetBucketPolicy.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/SetBucketPolicy.java @@ -1,26 +1,5 @@ -//snippet-sourcedescription:[SetBucketPolicy.java demonstrates how to create a Policy object and set it on an S3 bucket.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[setBucketPolicy] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* -Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -This file is 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/ - -This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -CONDITIONS OF ANY KIND, either express or implied. See the License for the -specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.s3; import com.amazonaws.AmazonServiceException; diff --git a/java/example_code/s3/src/main/java/aws/example/s3/SetWebsiteConfiguration.java b/java/example_code/s3/src/main/java/aws/example/s3/SetWebsiteConfiguration.java index d1352ecacdd..693ee67d2a9 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/SetWebsiteConfiguration.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/SetWebsiteConfiguration.java @@ -1,29 +1,5 @@ -//snippet-sourcedescription:[SetWebsiteConfiguration.java demonstrates how to set the website configuration for an S3 bucket.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[setBucketWebsiteConfiguration] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ -package aws.example.s3; +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0package aws.example.s3; // snippet-start:[s3.java1.s3_set_website_config.import] import com.amazonaws.AmazonServiceException; diff --git a/java/example_code/s3/src/main/java/aws/example/s3/SpecifyServerSideEncryption.java b/java/example_code/s3/src/main/java/aws/example/s3/SpecifyServerSideEncryption.java index 8dc8a748e5b..8957686a25d 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/SpecifyServerSideEncryption.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/SpecifyServerSideEncryption.java @@ -1,27 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -// snippet-sourcedescription:[SpecifyServerSideEncryption.java demonstrates how to upload an object using S3 server-side encryption.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[PUT Object] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[s3.java.specify_server_side_encryption.complete] import com.amazonaws.AmazonServiceException; @@ -60,7 +39,7 @@ public static void main(String[] args) { keyNameToCopyAndEncrypt, copiedObjectKeyName); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { @@ -90,15 +69,16 @@ private static void uploadObjectWithSSEEncryption(AmazonS3 s3Client, String buck } private static void changeSSEEncryptionStatusByCopying(AmazonS3 s3Client, - String bucketName, - String sourceKey, - String destKey) { + String bucketName, + String sourceKey, + String destKey) { // Upload a new, unencrypted object. PutObjectResult putResult = s3Client.putObject(bucketName, sourceKey, "Object example to encrypt by copying"); System.out.println("Unencrypted object \"" + sourceKey + "\" uploaded."); printEncryptionStatus(putResult); - // Make a copy of the object and use server-side encryption when storing the copy. + // Make a copy of the object and use server-side encryption when storing the + // copy. CopyObjectRequest request = new CopyObjectRequest(bucketName, sourceKey, bucketName, @@ -112,7 +92,8 @@ private static void changeSSEEncryptionStatusByCopying(AmazonS3 s3Client, System.out.println("Object \"" + destKey + "\" uploaded with SSE."); printEncryptionStatus(response); - // Delete the original, unencrypted object, leaving only the encrypted copy in Amazon S3. + // Delete the original, unencrypted object, leaving only the encrypted copy in + // Amazon S3. s3Client.deleteObject(bucketName, sourceKey); System.out.println("Unencrypted object \"" + sourceKey + "\" deleted."); } diff --git a/java/example_code/s3/src/main/java/aws/example/s3/TransferAcceleration.java b/java/example_code/s3/src/main/java/aws/example/s3/TransferAcceleration.java index 7c6eb26abac..b3d176a66eb 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/TransferAcceleration.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/TransferAcceleration.java @@ -1,29 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[TransferAcceleration.java demonstrates how to enable and use transfer acceleration with Amazon S3.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[PUT Bucket accelerate] -// snippet-keyword:[GET Bucket accelerate] -// snippet-keyword:[PUT Object] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.transfer_acceleration.complete] import com.amazonaws.AmazonServiceException; @@ -67,7 +44,7 @@ public static void main(String[] args) { s3Client.putObject(bucketName, keyName, "Test object for transfer acceleration"); System.out.println("Object \"" + keyName + "\" uploaded with transfer acceleration."); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/UploadObject.java b/java/example_code/s3/src/main/java/aws/example/s3/UploadObject.java index 238985bb28b..6b1f0be1669 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/UploadObject.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/UploadObject.java @@ -1,27 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[UploadObject.java demonstrates how to perform a basic object upload using Amazon S3.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[PUT Object] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.upload_object.complete] import com.amazonaws.AmazonServiceException; @@ -45,7 +24,7 @@ public static void main(String[] args) throws IOException { String fileName = "*** Path to file to upload ***"; try { - //This code expects that you have AWS credentials set up per: + // This code expects that you have AWS credentials set up per: // https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/setup-credentials.html AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withRegion(clientRegion) @@ -62,7 +41,7 @@ public static void main(String[] args) throws IOException { request.setMetadata(metadata); s3Client.putObject(request); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/UploadObjectKMSKey.java b/java/example_code/s3/src/main/java/aws/example/s3/UploadObjectKMSKey.java index 3ec1f5c33b9..6504aa33807 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/UploadObjectKMSKey.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/UploadObjectKMSKey.java @@ -1,28 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[UploadObjectKMSKey.java demonstrates how to upload and download S3 objects using a KMS key.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[GET Object] -// snippet-keyword:[PUT Object] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.upload_object_kms_key.complete] import com.amazonaws.AmazonServiceException; @@ -97,7 +75,7 @@ public static void main(String[] args) throws IOException { System.out.println("Original content length: " + origContentLength); System.out.println("Decrypted content length: " + decryptedContentLength); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/WebsiteConfiguration.java b/java/example_code/s3/src/main/java/aws/example/s3/WebsiteConfiguration.java index b563a8f00fb..6cc99504628 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/WebsiteConfiguration.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/WebsiteConfiguration.java @@ -1,29 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[WebsiteConfiguration.java demonstrates how to set, get, and delete S3 bucket website configurations.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[PUT Bucket website] -// snippet-keyword:[GET Bucket website] -// snippet-keyword:[DELETE Bucket website] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-28] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.website_configuration.complete] import com.amazonaws.AmazonServiceException; @@ -54,7 +31,8 @@ public static void main(String[] args) throws IOException { printWebsiteConfig(s3Client, bucketName); // Set the new website configuration. - s3Client.setBucketWebsiteConfiguration(bucketName, new BucketWebsiteConfiguration(indexDocName, errorDocName)); + s3Client.setBucketWebsiteConfiguration(bucketName, + new BucketWebsiteConfiguration(indexDocName, errorDocName)); // Verify that the configuration was set properly by printing it. printWebsiteConfig(s3Client, bucketName); @@ -65,7 +43,7 @@ public static void main(String[] args) throws IOException { // Verify that the website configuration was deleted by printing it. printWebsiteConfig(s3Client, bucketName); } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process + // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/XferMgrCopy.java b/java/example_code/s3/src/main/java/aws/example/s3/XferMgrCopy.java index 16d74b753de..188aa173c08 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/XferMgrCopy.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/XferMgrCopy.java @@ -1,29 +1,5 @@ -//snippet-sourcedescription:[XferMgrCopy.java demonstrates how to copy an object from one Amazon S3 bucket to another using S3 TransferManager.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[TransferManager copy] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] - - -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ -package aws.example.s3; +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0package aws.example.s3; // snippet-start:[s3.java1.s3_xfer_mgr_copy.import] import com.amazonaws.AmazonServiceException; @@ -42,7 +18,7 @@ */ public class XferMgrCopy { public static void copyObjectSimple(String from_bucket, String from_key, - String to_bucket, String to_key) { + String to_bucket, String to_key) { // snippet-start:[s3.java1.s3_xfer_mgr_copy.copy_object] System.out.println("Copying s3 object: " + from_key); System.out.println(" from bucket: " + from_bucket); diff --git a/java/example_code/s3/src/main/java/aws/example/s3/XferMgrDownload.java b/java/example_code/s3/src/main/java/aws/example/s3/XferMgrDownload.java index 649a534c75b..7e9efa1d3b8 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/XferMgrDownload.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/XferMgrDownload.java @@ -1,26 +1,5 @@ -//snippet-sourcedescription:[XferMgrDownload.java demonstrates how to download objects from an Amazon S3 bucket using S3 TransferManager.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[TransferManager downloadDirectory] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.s3; // snippet-start:[s3.java1.s3_xfer_mgr_download.import] @@ -43,7 +22,7 @@ */ public class XferMgrDownload { public static void downloadDir(String bucket_name, String key_prefix, - String dir_path, boolean pause) { + String dir_path, boolean pause) { System.out.println("downloading to directory: " + dir_path + (pause ? " (pause)" : "")); @@ -66,7 +45,7 @@ public static void downloadDir(String bucket_name, String key_prefix, } public static void downloadFile(String bucket_name, String key_name, - String file_path, boolean pause) { + String file_path, boolean pause) { System.out.println("Downloading to file: " + file_path + (pause ? " (pause)" : "")); @@ -149,7 +128,6 @@ public static void main(String[] args) { boolean s3_path_is_prefix = (key_name.lastIndexOf('/') == key_name.length() - 1); cur_arg += 1; - // The final argument is either a local directory or file to copy to. // If there is no final arg, use the key (object) name as the local file // name. diff --git a/java/example_code/s3/src/main/java/aws/example/s3/XferMgrProgress.java b/java/example_code/s3/src/main/java/aws/example/s3/XferMgrProgress.java index 03f823dd1a7..b255c2e9a95 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/XferMgrProgress.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/XferMgrProgress.java @@ -1,27 +1,5 @@ -//snippet-sourcedescription:[XferMgrProgress.java demonstrates how to use the S3 transfermanager to upload files to a bucket and show progress of the upload.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[TransferProgress] -//snippet-keyword:[TransferManager] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.s3; // snippet-start:[s3.java1.s3_xfer_mgr_progress.import] @@ -123,7 +101,7 @@ public static void showMultiUploadProgress(MultipleFileUpload multi_upload) { // snippet-end:[s3.java1.s3_xfer_mgr_progress.substranferes] } - // prints a simple text progressbar: [##### ] + // prints a simple text progressbar: [##### ] public static void printProgressBar(double pct) { // if bar_size changes, then change erase_bar (in eraseProgressBar) to // match. @@ -143,7 +121,7 @@ public static void eraseProgressBar() { } public static void uploadFileWithListener(String file_path, - String bucket_name, String key_prefix, boolean pause) { + String bucket_name, String key_prefix, boolean pause) { System.out.println("file: " + file_path + (pause ? " (pause)" : "")); @@ -182,10 +160,9 @@ public void progressChanged(ProgressEvent e) { } public static void uploadDirWithSubprogress(String dir_path, - String bucket_name, String key_prefix, boolean recursive, - boolean pause) { - System.out.println("directory: " + dir_path + (recursive ? - " (recursive)" : "") + (pause ? " (pause)" : "")); + String bucket_name, String key_prefix, boolean recursive, + boolean pause) { + System.out.println("directory: " + dir_path + (recursive ? " (recursive)" : "") + (pause ? " (pause)" : "")); TransferManager xfer_mgr = new TransferManager(); try { diff --git a/java/example_code/s3/src/main/java/aws/example/s3/XferMgrUpload.java b/java/example_code/s3/src/main/java/aws/example/s3/XferMgrUpload.java index afb4744089e..04110fbac72 100644 --- a/java/example_code/s3/src/main/java/aws/example/s3/XferMgrUpload.java +++ b/java/example_code/s3/src/main/java/aws/example/s3/XferMgrUpload.java @@ -1,27 +1,5 @@ -//snippet-sourcedescription:[XferMgrUpload.java demonstrates how to upload a file or files to an S3 bucket using the S3 transfer manager.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-keyword:[TransferManager upload] -//snippet-keyword:[TransferManager uploadDirectory] -//snippet-service:[s3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - - This file is 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/ - - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.s3; // snippet-start:[s3.java1.s3_xfer_mgr_upload.import] @@ -46,9 +24,8 @@ */ public class XferMgrUpload { public static void uploadDir(String dir_path, String bucket_name, - String key_prefix, boolean recursive, boolean pause) { - System.out.println("directory: " + dir_path + (recursive ? - " (recursive)" : "") + (pause ? " (pause)" : "")); + String key_prefix, boolean recursive, boolean pause) { + System.out.println("directory: " + dir_path + (recursive ? " (recursive)" : "") + (pause ? " (pause)" : "")); // snippet-start:[s3.java1.s3_xfer_mgr_upload.directory] TransferManager xfer_mgr = TransferManagerBuilder.standard().build(); @@ -68,7 +45,7 @@ public static void uploadDir(String dir_path, String bucket_name, } public static void uploadFileList(String[] file_paths, String bucket_name, - String key_prefix, boolean pause) { + String key_prefix, boolean pause) { System.out.println("file list: " + Arrays.toString(file_paths) + (pause ? " (pause)" : "")); // convert the file paths to a list of File objects (required by the @@ -96,7 +73,7 @@ public static void uploadFileList(String[] file_paths, String bucket_name, } public static void uploadFile(String file_path, String bucket_name, - String key_prefix, boolean pause) { + String key_prefix, boolean pause) { System.out.println("file: " + file_path + (pause ? " (pause)" : "")); @@ -114,7 +91,7 @@ public static void uploadFile(String file_path, String bucket_name, Upload xfer = xfer_mgr.upload(bucket_name, key_name, f); // loop with Transfer.isDone() XferMgrProgress.showTransferProgress(xfer); - // or block with Transfer.waitForCompletion() + // or block with Transfer.waitForCompletion() XferMgrProgress.waitForCompletion(xfer); } catch (AmazonServiceException e) { System.err.println(e.getErrorMessage()); diff --git a/java/example_code/s3/src/main/java/com/mycompany/app/App.java b/java/example_code/s3/src/main/java/com/mycompany/app/App.java index 63794989131..08c76a9d7b4 100644 --- a/java/example_code/s3/src/main/java/com/mycompany/app/App.java +++ b/java/example_code/s3/src/main/java/com/mycompany/app/App.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * @@ -12,18 +14,6 @@ * specific language governing permissions and limitations under the License. */ -// snippet-sourcedescription:[App.java demonstrates how to list, create, and delete a bucket in Amazon S3.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[listBuckets] -// snippet-keyword:[createBucket] -// snippet-keyword:[deleteBucket] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-05-29] -// snippet-sourceauthor:[AWS] // snippet-start:[s3.java.bucket_operations.list_create_delete] package com.mycompany.app; diff --git a/java/example_code/s3control/run_example.sh b/java/example_code/s3control/run_example.sh index bb6d2c99d14..dcf2644b639 100644 --- a/java/example_code/s3control/run_example.sh +++ b/java/example_code/s3control/run_example.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 if [[ -z $* ]] ; then echo 'Supply the name of one of the example classes as an argument.' echo 'If there are arguments to the class, put them in quotes after the class name.' diff --git a/java/example_code/s3control/src/main/java/aws/example/s3control/CancelJob.java b/java/example_code/s3control/src/main/java/aws/example/s3control/CancelJob.java index 4930917d574..8154532ee31 100644 --- a/java/example_code/s3control/src/main/java/aws/example/s3control/CancelJob.java +++ b/java/example_code/s3control/src/main/java/aws/example/s3control/CancelJob.java @@ -1,26 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - *

- * This file is 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/ - *

- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[CancelJob.java demonstrates how to cancel a job by setting the job status to Cancelled.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-04-30] -// snippet-sourceauthor:[jschwarzwalder (AWS)] // snippet-start:[s3.java.cancel_job.complete] package aws.example.s3control; @@ -68,7 +48,3 @@ public static void main(String[] args) { } } // snippet-end:[s3.java.cancel_job.complete] - - - - diff --git a/java/example_code/s3control/src/main/java/aws/example/s3control/CreateJob.java b/java/example_code/s3control/src/main/java/aws/example/s3control/CreateJob.java index 586d6502c6e..b5cfb8a6a5a 100644 --- a/java/example_code/s3control/src/main/java/aws/example/s3control/CreateJob.java +++ b/java/example_code/s3control/src/main/java/aws/example/s3control/CreateJob.java @@ -1,34 +1,12 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - *

- * This file is 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/ - *

- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 - -// snippet-sourcedescription:[CreateJob.java demonstrates how to execute an Amazon S3 Batch Operation.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-04-30] -// snippet-sourceauthor:[jschwarzwalder (AWS)] // snippet-start:[s3.java.create_batch_job.complete] package aws.example.s3control; // snippet-start:[s3.java.create_batch_job.import] - import com.amazonaws.AmazonServiceException; import com.amazonaws.SdkClientException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; @@ -43,66 +21,63 @@ // snippet-end:[s3.java.create_batch_job.import] public class CreateJob { - public static void main(String[] args) { - // snippet-start:[s3.java.create_batch_job.main] - String accountId = "Account ID"; - String iamRoleArn = "IAM Role ARN"; - String reportBucketName = "arn:aws:s3:::bucket-where-completion-report-goes"; - String uuid = UUID.randomUUID().toString(); - - ArrayList tagSet = new ArrayList(); - tagSet.add(new S3Tag().withKey("keyOne").withValue("ValueOne")); - - - try { - JobOperation jobOperation = new JobOperation() - .withS3PutObjectTagging(new S3SetObjectTaggingOperation() - .withTagSet(tagSet) - ); - - JobManifest manifest = new JobManifest() - .withSpec(new JobManifestSpec() - .withFormat("S3BatchOperations_CSV_20180820") - .withFields(new String[]{ - "Bucket", "Key" - })) - .withLocation(new JobManifestLocation() - .withObjectArn("arn:aws:s3:::my_manifests/manifest.csv") - .withETag("60e460c9d1046e73f7dde5043ac3ae85")); - JobReport jobReport = new JobReport() - .withBucket(reportBucketName) - .withPrefix("reports") - .withFormat("Report_CSV_20180820") - .withEnabled(true) - .withReportScope("AllTasks"); - - AWSS3Control s3ControlClient = AWSS3ControlClient.builder() - .withCredentials(new ProfileCredentialsProvider()) - .withRegion(US_WEST_2) - .build(); - - s3ControlClient.createJob(new CreateJobRequest() - .withAccountId(accountId) - .withOperation(jobOperation) - .withManifest(manifest) - .withReport(jobReport) - .withPriority(42) - .withRoleArn(iamRoleArn) - .withClientRequestToken(uuid) - .withDescription("job description") - .withConfirmationRequired(false) - ); - - // snippet-end:[s3.java.create_batch_job.main] - } catch (AmazonServiceException e) { - // The call was transmitted successfully, but Amazon S3 couldn't process - // it and returned an error response. - e.printStackTrace(); - } catch (SdkClientException e) { - // Amazon S3 couldn't be contacted for a response, or the client - // couldn't parse the response from Amazon S3. - e.printStackTrace(); + public static void main(String[] args) { + // snippet-start:[s3.java.create_batch_job.main] + String accountId = "Account ID"; + String iamRoleArn = "IAM Role ARN"; + String reportBucketName = "arn:aws:s3:::bucket-where-completion-report-goes"; + String uuid = UUID.randomUUID().toString(); + + ArrayList tagSet = new ArrayList(); + tagSet.add(new S3Tag().withKey("keyOne").withValue("ValueOne")); + + try { + JobOperation jobOperation = new JobOperation() + .withS3PutObjectTagging(new S3SetObjectTaggingOperation() + .withTagSet(tagSet)); + + JobManifest manifest = new JobManifest() + .withSpec(new JobManifestSpec() + .withFormat("S3BatchOperations_CSV_20180820") + .withFields(new String[] { + "Bucket", "Key" + })) + .withLocation(new JobManifestLocation() + .withObjectArn("arn:aws:s3:::my_manifests/manifest.csv") + .withETag("60e460c9d1046e73f7dde5043ac3ae85")); + JobReport jobReport = new JobReport() + .withBucket(reportBucketName) + .withPrefix("reports") + .withFormat("Report_CSV_20180820") + .withEnabled(true) + .withReportScope("AllTasks"); + + AWSS3Control s3ControlClient = AWSS3ControlClient.builder() + .withCredentials(new ProfileCredentialsProvider()) + .withRegion(US_WEST_2) + .build(); + + s3ControlClient.createJob(new CreateJobRequest() + .withAccountId(accountId) + .withOperation(jobOperation) + .withManifest(manifest) + .withReport(jobReport) + .withPriority(42) + .withRoleArn(iamRoleArn) + .withClientRequestToken(uuid) + .withDescription("job description") + .withConfirmationRequired(false)); + + // snippet-end:[s3.java.create_batch_job.main] + } catch (AmazonServiceException e) { + // The call was transmitted successfully, but Amazon S3 couldn't process + // it and returned an error response. + e.printStackTrace(); + } catch (SdkClientException e) { + // Amazon S3 couldn't be contacted for a response, or the client + // couldn't parse the response from Amazon S3. + e.printStackTrace(); + } } - } } // snippet-end:[s3.java.create_batch_job.complete] diff --git a/java/example_code/s3control/src/main/java/aws/example/s3control/DescribeJob.java b/java/example_code/s3control/src/main/java/aws/example/s3control/DescribeJob.java index 550fa5cd00d..39da9ccfddd 100644 --- a/java/example_code/s3control/src/main/java/aws/example/s3control/DescribeJob.java +++ b/java/example_code/s3control/src/main/java/aws/example/s3control/DescribeJob.java @@ -1,26 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - *

- * This file is 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/ - *

- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[DescribeJob.java demonstrates how to retrieve the ARN and status of a current job.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-04-30] -// snippet-sourceauthor:[jschwarzwalder (AWS)] // snippet-start:[s3.java.describe_job.complete] package aws.example.s3control; @@ -54,7 +34,7 @@ public static void main(String[] args) { DescribeJobResult result = s3ControlClient.describeJob(new DescribeJobRequest() .withAccountId(accountId) .withJobId(jobId)); - + JobDescriptor job = result.getJob(); System.out.printf("%s - %s (status: %s)\n", job.getJobId(), job.getJobArn(), job.getStatus()); @@ -71,7 +51,3 @@ public static void main(String[] args) { } } // snippet-end:[s3.java.describe_job.complete] - - - - diff --git a/java/example_code/s3control/src/main/java/aws/example/s3control/ListJobs.java b/java/example_code/s3control/src/main/java/aws/example/s3control/ListJobs.java index 49744bcf6f7..c1132eede06 100644 --- a/java/example_code/s3control/src/main/java/aws/example/s3control/ListJobs.java +++ b/java/example_code/s3control/src/main/java/aws/example/s3control/ListJobs.java @@ -1,33 +1,12 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - *

- * This file is 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/ - *

- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[ListJobs.java demonstrates how to list active and complete Amazon S3 Batch Operations.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-04-30] -// snippet-sourceauthor:[jschwarzwalder (AWS)] // snippet-start:[s3.java.list_batch_jobs.complete] package aws.example.s3control; // snippet-start:[s3.java.list_batch_jobs.import] - import com.amazonaws.AmazonServiceException; import com.amazonaws.SdkClientException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; @@ -51,21 +30,18 @@ public static void main(String[] args) { .withRegion(US_WEST_2) .build(); - ListJobsResult result = s3ControlClient.listJobs(new ListJobsRequest() .withAccountId(accountId) .withMaxResults(20) - .withJobStatuses("Active", "Complete") - ).withJobs(new JobListDescriptor() - .withStatus("Active") - .withStatus("Complete")); - - for (JobListDescriptor jobSummary : result.getJobs()) { - System.out.printf("%s - %s (status: %s)\n", jobSummary.getJobId(), jobSummary.getCreationTime(), jobSummary.getStatus()); - } - + .withJobStatuses("Active", "Complete")).withJobs(new JobListDescriptor() + .withStatus("Active") + .withStatus("Complete")); + for (JobListDescriptor jobSummary : result.getJobs()) { + System.out.printf("%s - %s (status: %s)\n", jobSummary.getJobId(), jobSummary.getCreationTime(), + jobSummary.getStatus()); + } // snippet-end:[s3.java.list_batch_jobs.main] } catch (AmazonServiceException e) { diff --git a/java/example_code/s3control/src/main/java/aws/example/s3control/UpdateJobPriority.java b/java/example_code/s3control/src/main/java/aws/example/s3control/UpdateJobPriority.java index d055c7d9a52..a94de2ef166 100644 --- a/java/example_code/s3control/src/main/java/aws/example/s3control/UpdateJobPriority.java +++ b/java/example_code/s3control/src/main/java/aws/example/s3control/UpdateJobPriority.java @@ -1,33 +1,12 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - *

- * This file is 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/ - *

- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[UpdateJobPriority.java demonstrates how to update the job priority (a higher number indicates a higher execution priority).] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-04-30] -// snippet-sourceauthor:[jschwarzwalder (AWS)] // snippet-start:[s3.java.update_job_priority.complete] package aws.example.s3control; // snippet-start:[s3.java.update_job_priority.import] - import com.amazonaws.AmazonServiceException; import com.amazonaws.SdkClientException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; @@ -68,4 +47,3 @@ public static void main(String[] args) { } } // snippet-end:[s3.java.update_job_priority.complete] - diff --git a/java/example_code/s3control/src/main/java/aws/example/s3control/UpdateJobStatus.java b/java/example_code/s3control/src/main/java/aws/example/s3control/UpdateJobStatus.java index 67ddfbe863d..19a9e92d5ca 100644 --- a/java/example_code/s3control/src/main/java/aws/example/s3control/UpdateJobStatus.java +++ b/java/example_code/s3control/src/main/java/aws/example/s3control/UpdateJobStatus.java @@ -1,26 +1,6 @@ -/** - * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - *

- * This file is 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/ - *

- * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[UpdateJobStatus.java demonstrates how to make job eligible for execution.] -// snippet-service:[s3] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-04-30] -// snippet-sourceauthor:[jschwarzwalder (AWS)] // snippet-start:[s3.java.update_job_status.complete] package aws.example.s3control; @@ -67,5 +47,3 @@ public static void main(String[] args) { } } // snippet-end:[s3.java.update_job_status.complete] - - diff --git a/java/example_code/secretsmanager/run_example.sh b/java/example_code/secretsmanager/run_example.sh index 053bdf1ae67..3c732aca381 100755 --- a/java/example_code/secretsmanager/run_example.sh +++ b/java/example_code/secretsmanager/run_example.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 if [[ -z $* ]] ; then echo 'Supply the name of one of the example classes as an argument.' echo 'If there are arguments to the class, put them in quotes after the class name.' diff --git a/java/example_code/secretsmanager/src/main/java/aws/example/secretsmanager/GetSecretValue.java b/java/example_code/secretsmanager/src/main/java/aws/example/secretsmanager/GetSecretValue.java index b208ab2fd08..fe16a8ce01e 100644 --- a/java/example_code/secretsmanager/src/main/java/aws/example/secretsmanager/GetSecretValue.java +++ b/java/example_code/secretsmanager/src/main/java/aws/example/secretsmanager/GetSecretValue.java @@ -1,26 +1,7 @@ -//snippet-sourcedescription:[GetSecretValue.java demonstrates how to get the value of a secret from AWS Secrets Manager.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[secretsmanager] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[Walker] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.secretsmanager; + import java.nio.ByteBuffer; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; @@ -31,51 +12,51 @@ import com.amazonaws.services.secretsmanager.model.*; public class GetSecretValue { - public static void main(String[] args) { - getSecret(); - } - - public static void getSecret() { - - String secretName = "testSecret"; - String endpoint = "secretsmanager.us-west-2.amazonaws.com"; - String region = "us-west-2"; - - AwsClientBuilder.EndpointConfiguration config = new AwsClientBuilder.EndpointConfiguration(endpoint, region); - AWSSecretsManagerClientBuilder clientBuilder = AWSSecretsManagerClientBuilder.standard(); - clientBuilder.setEndpointConfiguration(config); - AWSSecretsManager client = clientBuilder.build(); - - String secret; - ByteBuffer binarySecretData; - GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest() - .withSecretId(secretName).withVersionStage("AWSCURRENT"); - GetSecretValueResult getSecretValueResult = null; - try { - getSecretValueResult = client.getSecretValue(getSecretValueRequest); - - } catch(ResourceNotFoundException e) { - System.out.println("The requested secret " + secretName + " was not found"); - } catch (InvalidRequestException e) { - System.out.println("The request was invalid due to: " + e.getMessage()); - } catch (InvalidParameterException e) { - System.out.println("The request had invalid params: " + e.getMessage()); - } - - if(getSecretValueResult == null) { - return; - } - - // Depending on whether the secret was a string or binary, one of these fields will be populated - if(getSecretValueResult.getSecretString() != null) { - secret = getSecretValueResult.getSecretString(); - System.out.println(secret); - } - else { - binarySecretData = getSecretValueResult.getSecretBinary(); - System.out.println(binarySecretData.toString()); - } - - } + public static void main(String[] args) { + getSecret(); + } + + public static void getSecret() { + + String secretName = "testSecret"; + String endpoint = "secretsmanager.us-west-2.amazonaws.com"; + String region = "us-west-2"; + + AwsClientBuilder.EndpointConfiguration config = new AwsClientBuilder.EndpointConfiguration(endpoint, region); + AWSSecretsManagerClientBuilder clientBuilder = AWSSecretsManagerClientBuilder.standard(); + clientBuilder.setEndpointConfiguration(config); + AWSSecretsManager client = clientBuilder.build(); + + String secret; + ByteBuffer binarySecretData; + GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest() + .withSecretId(secretName).withVersionStage("AWSCURRENT"); + GetSecretValueResult getSecretValueResult = null; + try { + getSecretValueResult = client.getSecretValue(getSecretValueRequest); + + } catch (ResourceNotFoundException e) { + System.out.println("The requested secret " + secretName + " was not found"); + } catch (InvalidRequestException e) { + System.out.println("The request was invalid due to: " + e.getMessage()); + } catch (InvalidParameterException e) { + System.out.println("The request had invalid params: " + e.getMessage()); + } + + if (getSecretValueResult == null) { + return; + } + + // Depending on whether the secret was a string or binary, one of these fields + // will be populated + if (getSecretValueResult.getSecretString() != null) { + secret = getSecretValueResult.getSecretString(); + System.out.println(secret); + } else { + binarySecretData = getSecretValueResult.getSecretBinary(); + System.out.println(binarySecretData.toString()); + } + + } } diff --git a/java/example_code/sns/CreateMobileEndpoint.java b/java/example_code/sns/CreateMobileEndpoint.java index ce4072d00aa..be0c398edee 100644 --- a/java/example_code/sns/CreateMobileEndpoint.java +++ b/java/example_code/sns/CreateMobileEndpoint.java @@ -4,7 +4,7 @@ // snippet-start:[sns.java.create_mobile_endpoint] class RegistrationExample { - AmazonSNSClient client = new AmazonSNSClient(); //provide credentials here + AmazonSNSClient client = new AmazonSNSClient(); // provide credentials here String arnStorage = null; public void registerWithSNS() { @@ -22,22 +22,21 @@ public void registerWithSNS() { } System.out.println("Retrieving platform endpoint data..."); - // Look up the platform endpoint and make sure the data in it is current, even if + // Look up the platform endpoint and make sure the data in it is current, even + // if // it was just created. try { - GetEndpointAttributesRequest geaReq = - new GetEndpointAttributesRequest() - .withEndpointArn(endpointArn); - GetEndpointAttributesResult geaRes = - client.getEndpointAttributes(geaReq); + GetEndpointAttributesRequest geaReq = new GetEndpointAttributesRequest() + .withEndpointArn(endpointArn); + GetEndpointAttributesResult geaRes = client.getEndpointAttributes(geaReq); updateNeeded = !geaRes.getAttributes().get("Token").equals(token) - || !geaRes.getAttributes().get("Enabled").equalsIgnoreCase("true"); + || !geaRes.getAttributes().get("Enabled").equalsIgnoreCase("true"); } catch (NotFoundException nfe) { // We had a stored ARN, but the platform endpoint associated with it // disappeared. Recreate it. - createNeeded = true; + createNeeded = true; } if (createNeeded) { @@ -53,35 +52,33 @@ public void registerWithSNS() { Map attribs = new HashMap(); attribs.put("Token", token); attribs.put("Enabled", "true"); - SetEndpointAttributesRequest saeReq = - new SetEndpointAttributesRequest() - .withEndpointArn(endpointArn) - .withAttributes(attribs); + SetEndpointAttributesRequest saeReq = new SetEndpointAttributesRequest() + .withEndpointArn(endpointArn) + .withAttributes(attribs); client.setEndpointAttributes(saeReq); } } /** - * @return never null - * */ + * @return never null + */ private String createEndpoint(String token) { String endpointArn = null; try { System.out.println("Creating platform endpoint with token " + token); - CreatePlatformEndpointRequest cpeReq = - new CreatePlatformEndpointRequest() - .withPlatformApplicationArn(applicationArn) - .withToken(token); + CreatePlatformEndpointRequest cpeReq = new CreatePlatformEndpointRequest() + .withPlatformApplicationArn(applicationArn) + .withToken(token); CreatePlatformEndpointResult cpeRes = client - .createPlatformEndpoint(cpeReq); + .createPlatformEndpoint(cpeReq); endpointArn = cpeRes.getEndpointArn(); } catch (InvalidParameterException ipe) { String message = ipe.getErrorMessage(); System.out.println("Exception message: " + message); Pattern p = Pattern - .compile(".*Endpoint (arn:aws:sns[^ ]+) already exists " + - "with the same [Tt]oken.*"); + .compile(".*Endpoint (arn:aws:sns[^ ]+) already exists " + + "with the same [Tt]oken.*"); Matcher m = p.matcher(message); if (m.matches()) { // The platform endpoint already exists for this token, but with additional @@ -98,9 +95,9 @@ private String createEndpoint(String token) { } /** - * @return the ARN the app was registered under previously, or null if no - * platform endpoint ARN is stored. - */ + * @return the ARN the app was registered under previously, or null if no + * platform endpoint ARN is stored. + */ private String retrieveEndpointArn() { // Retrieve the platform endpoint ARN from permanent storage, // or return null if null is stored. @@ -108,8 +105,8 @@ private String retrieveEndpointArn() { } /** - * Stores the platform endpoint ARN in permanent storage for lookup next time. - * */ + * Stores the platform endpoint ARN in permanent storage for lookup next time. + */ private void storeEndpointArn(String endpointArn) { // Write the platform endpoint ARN to permanent storage. arnStorage = endpointArn; diff --git a/java/example_code/sns/FifoTopics.java b/java/example_code/sns/FifoTopics.java index d677ad6a128..c38247eef01 100644 --- a/java/example_code/sns/FifoTopics.java +++ b/java/example_code/sns/FifoTopics.java @@ -95,4 +95,3 @@ .withMessageDeduplicationId(dedupId) .withMessageAttributes(attributes); // snippet-end:[sns.java.fifo_topics.publish] - diff --git a/java/example_code/sns/PublishLargeFile.java b/java/example_code/sns/PublishLargeFile.java index 85b4c93e5d0..1fead1adc23 100644 --- a/java/example_code/sns/PublishLargeFile.java +++ b/java/example_code/sns/PublishLargeFile.java @@ -1,7 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 - // snippet-start:[sns.java.publish_large_file] import com.amazon.sqs.javamessaging.AmazonSQSExtendedClient; import com.amazon.sqs.javamessaging.ExtendedClientConfiguration; @@ -24,63 +23,66 @@ public class Example { - public static void main(String[] args) { - final String BUCKET_NAME = "extended-client-bucket"; - final String TOPIC_NAME = "extended-client-topic"; - final String QUEUE_NAME = "extended-client-queue"; - final Regions region = Regions.DEFAULT_REGION; + public static void main(String[] args) { + final String BUCKET_NAME = "extended-client-bucket"; + final String TOPIC_NAME = "extended-client-topic"; + final String QUEUE_NAME = "extended-client-queue"; + final Regions region = Regions.DEFAULT_REGION; - //Message threshold controls the maximum message size that will be allowed to be published - //through SNS using the extended client. Payload of messages exceeding this value will be stored in - //S3. The default value of this parameter is 256 KB which is the maximum message size in SNS (and SQS). - final int EXTENDED_STORAGE_MESSAGE_SIZE_THRESHOLD = 32; + // Message threshold controls the maximum message size that will be allowed to + // be published + // through SNS using the extended client. Payload of messages exceeding this + // value will be stored in + // S3. The default value of this parameter is 256 KB which is the maximum + // message size in SNS (and SQS). + final int EXTENDED_STORAGE_MESSAGE_SIZE_THRESHOLD = 32; - //Initialize SNS, SQS and S3 clients - final AmazonSNS snsClient = AmazonSNSClientBuilder.standard().withRegion(region).build(); - final AmazonSQS sqsClient = AmazonSQSClientBuilder.standard().withRegion(region).build(); - final AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(region).build(); + // Initialize SNS, SQS and S3 clients + final AmazonSNS snsClient = AmazonSNSClientBuilder.standard().withRegion(region).build(); + final AmazonSQS sqsClient = AmazonSQSClientBuilder.standard().withRegion(region).build(); + final AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(region).build(); - //Create bucket, topic, queue and subscription - s3Client.createBucket(BUCKET_NAME); - final String topicArn = snsClient.createTopic( - new CreateTopicRequest().withName(TOPIC_NAME) - ).getTopicArn(); - final String queueUrl = sqsClient.createQueue( - new CreateQueueRequest().withQueueName(QUEUE_NAME) - ).getQueueUrl(); - final String subscriptionArn = Topics.subscribeQueue( - snsClient, sqsClient, topicArn, queueUrl - ); + // Create bucket, topic, queue and subscription + s3Client.createBucket(BUCKET_NAME); + final String topicArn = snsClient.createTopic( + new CreateTopicRequest().withName(TOPIC_NAME)).getTopicArn(); + final String queueUrl = sqsClient.createQueue( + new CreateQueueRequest().withQueueName(QUEUE_NAME)).getQueueUrl(); + final String subscriptionArn = Topics.subscribeQueue( + snsClient, sqsClient, topicArn, queueUrl); - //To read message content stored in S3 transparently through SQS extended client, - //set the RawMessageDelivery subscription attribute to TRUE - final SetSubscriptionAttributesRequest subscriptionAttributesRequest = new SetSubscriptionAttributesRequest(); - subscriptionAttributesRequest.setSubscriptionArn(subscriptionArn); - subscriptionAttributesRequest.setAttributeName("RawMessageDelivery"); - subscriptionAttributesRequest.setAttributeValue("TRUE"); - snsClient.setSubscriptionAttributes(subscriptionAttributesRequest); + // To read message content stored in S3 transparently through SQS extended + // client, + // set the RawMessageDelivery subscription attribute to TRUE + final SetSubscriptionAttributesRequest subscriptionAttributesRequest = new SetSubscriptionAttributesRequest(); + subscriptionAttributesRequest.setSubscriptionArn(subscriptionArn); + subscriptionAttributesRequest.setAttributeName("RawMessageDelivery"); + subscriptionAttributesRequest.setAttributeValue("TRUE"); + snsClient.setSubscriptionAttributes(subscriptionAttributesRequest); - //Initialize SNS extended client - //PayloadSizeThreshold triggers message content storage in S3 when the threshold is exceeded - //To store all messages content in S3, use AlwaysThroughS3 flag - final SNSExtendedClientConfiguration snsExtendedClientConfiguration = new SNSExtendedClientConfiguration() - .withPayloadSupportEnabled(s3Client, BUCKET_NAME) - .withPayloadSizeThreshold(EXTENDED_STORAGE_MESSAGE_SIZE_THRESHOLD); - final AmazonSNSExtendedClient snsExtendedClient = new AmazonSNSExtendedClient(snsClient, snsExtendedClientConfiguration); + // Initialize SNS extended client + // PayloadSizeThreshold triggers message content storage in S3 when the + // threshold is exceeded + // To store all messages content in S3, use AlwaysThroughS3 flag + final SNSExtendedClientConfiguration snsExtendedClientConfiguration = new SNSExtendedClientConfiguration() + .withPayloadSupportEnabled(s3Client, BUCKET_NAME) + .withPayloadSizeThreshold(EXTENDED_STORAGE_MESSAGE_SIZE_THRESHOLD); + final AmazonSNSExtendedClient snsExtendedClient = new AmazonSNSExtendedClient(snsClient, + snsExtendedClientConfiguration); - //Publish message via SNS with storage in S3 - final String message = "This message is stored in S3 as it exceeds the threshold of 32 bytes set above."; - snsExtendedClient.publish(topicArn, message); + // Publish message via SNS with storage in S3 + final String message = "This message is stored in S3 as it exceeds the threshold of 32 bytes set above."; + snsExtendedClient.publish(topicArn, message); - //Initialize SQS extended client - final ExtendedClientConfiguration sqsExtendedClientConfiguration = new ExtendedClientConfiguration() - .withPayloadSupportEnabled(s3Client, BUCKET_NAME); - final AmazonSQSExtendedClient sqsExtendedClient = - new AmazonSQSExtendedClient(sqsClient, sqsExtendedClientConfiguration); + // Initialize SQS extended client + final ExtendedClientConfiguration sqsExtendedClientConfiguration = new ExtendedClientConfiguration() + .withPayloadSupportEnabled(s3Client, BUCKET_NAME); + final AmazonSQSExtendedClient sqsExtendedClient = new AmazonSQSExtendedClient(sqsClient, + sqsExtendedClientConfiguration); - //Read the message from the queue - final ReceiveMessageResult result = sqsExtendedClient.receiveMessage(queueUrl); - System.out.println("Received message is " + result.getMessages().get(0).getBody()); - } + // Read the message from the queue + final ReceiveMessageResult result = sqsExtendedClient.receiveMessage(queueUrl); + System.out.println("Received message is " + result.getMessages().get(0).getBody()); + } } // snippet-end:[sns.java.publish_large_file] diff --git a/java/example_code/sqs/run_example.sh b/java/example_code/sqs/run_example.sh index 856ecc7f2b0..22f9d5683ed 100755 --- a/java/example_code/sqs/run_example.sh +++ b/java/example_code/sqs/run_example.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 if [[ -z $* ]] ; then echo 'Supply the name of one of the example classes as an argument.' echo 'If there are arguments to the class, put them in quotes after the class name.' diff --git a/java/example_code/sqs/src/main/java/aws/example/sqs/DeadLetterQueues.java b/java/example_code/sqs/src/main/java/aws/example/sqs/DeadLetterQueues.java index 0a39f9267a0..06d63ba3991 100644 --- a/java/example_code/sqs/src/main/java/aws/example/sqs/DeadLetterQueues.java +++ b/java/example_code/sqs/src/main/java/aws/example/sqs/DeadLetterQueues.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[<> demonstrates how to create and use a dead letter queue.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Queue Service] -//snippet-service:[sqs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2011-2019 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. - * You may obtain a copy of the License at: - * - * http://aws.amazon.com/apache2.0 - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES - * OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and - * limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.sqs; + import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClientBuilder; import com.amazonaws.services.sqs.model.AmazonSQSException; @@ -29,13 +9,11 @@ import com.amazonaws.services.sqs.model.GetQueueAttributesResult; import com.amazonaws.services.sqs.model.SetQueueAttributesRequest; -public class DeadLetterQueues -{ - public static void main(String[] args) - { +public class DeadLetterQueues { + public static void main(String[] args) { if (args.length != 2) { System.out.println( - "Usage: DeadLetterQueues "); + "Usage: DeadLetterQueues "); System.exit(1); } @@ -64,23 +42,23 @@ public static void main(String[] args) // Get dead-letter queue ARN String dl_queue_url = sqs.getQueueUrl(dl_queue_name) - .getQueueUrl(); + .getQueueUrl(); GetQueueAttributesResult queue_attrs = sqs.getQueueAttributes( new GetQueueAttributesRequest(dl_queue_url) - .withAttributeNames("QueueArn")); + .withAttributeNames("QueueArn")); String dl_queue_arn = queue_attrs.getAttributes().get("QueueArn"); // Set dead letter queue with redrive policy on source queue. String src_queue_url = sqs.getQueueUrl(src_queue_name) - .getQueueUrl(); + .getQueueUrl(); SetQueueAttributesRequest request = new SetQueueAttributesRequest() .withQueueUrl(src_queue_url) .addAttributesEntry("RedrivePolicy", "{\"maxReceiveCount\":\"5\", \"deadLetterTargetArn\":\"" - + dl_queue_arn + "\"}"); + + dl_queue_arn + "\"}"); sqs.setQueueAttributes(request); } diff --git a/java/example_code/sqs/src/main/java/aws/example/sqs/LongPolling.java b/java/example_code/sqs/src/main/java/aws/example/sqs/LongPolling.java index 889fcd62b87..89e7a8f6a17 100644 --- a/java/example_code/sqs/src/main/java/aws/example/sqs/LongPolling.java +++ b/java/example_code/sqs/src/main/java/aws/example/sqs/LongPolling.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[<> demonstrates how to enable long polling when creating a queue.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Queue Service] -//snippet-service:[sqs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2011-2019 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. - * You may obtain a copy of the License at: - * - * http://aws.amazon.com/apache2.0 - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES - * OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and - * limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.sqs; + import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClientBuilder; import com.amazonaws.services.sqs.model.AmazonSQSException; @@ -29,14 +9,11 @@ import com.amazonaws.services.sqs.model.SetQueueAttributesRequest; import com.amazonaws.services.sqs.model.ReceiveMessageRequest; -public class LongPolling -{ - public static void main(String[] args) - { - final String USAGE = - "To run this example, supply the name of a queue to create and\n" + - "queue url of an existing queue.\n\n" + - "Ex: LongPolling \n"; +public class LongPolling { + public static void main(String[] args) { + final String USAGE = "To run this example, supply the name of a queue to create and\n" + + "queue url of an existing queue.\n\n" + + "Ex: LongPolling \n"; if (args.length != 2) { System.out.println(USAGE); diff --git a/java/example_code/sqs/src/main/java/aws/example/sqs/SendReceiveMessages.java b/java/example_code/sqs/src/main/java/aws/example/sqs/SendReceiveMessages.java index e771422905f..5b7ef426bbf 100644 --- a/java/example_code/sqs/src/main/java/aws/example/sqs/SendReceiveMessages.java +++ b/java/example_code/sqs/src/main/java/aws/example/sqs/SendReceiveMessages.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[<> demonstrates how to send, receive and delete messages from a queue.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Queue Service] -//snippet-service:[sqs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2011-2019 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. - * You may obtain a copy of the License at: - * - * http://aws.amazon.com/apache2.0 - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES - * OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and - * limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.sqs; + import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClientBuilder; import com.amazonaws.services.sqs.model.AmazonSQSException; @@ -33,12 +13,10 @@ import java.util.Date; import java.util.List; -public class SendReceiveMessages -{ +public class SendReceiveMessages { private static final String QUEUE_NAME = "testQueue" + new Date().getTime(); - public static void main(String[] args) - { + public static void main(String[] args) { final AmazonSQS sqs = AmazonSQSClientBuilder.defaultClient(); try { @@ -57,7 +35,6 @@ public static void main(String[] args) .withDelaySeconds(5); sqs.sendMessage(send_msg_request); - // Send multiple messages to the queue SendMessageBatchRequest send_batch_request = new SendMessageBatchRequest() .withQueueUrl(queueUrl) diff --git a/java/example_code/sqs/src/main/java/aws/example/sqs/UsingQueues.java b/java/example_code/sqs/src/main/java/aws/example/sqs/UsingQueues.java index 4759480c97d..26ebdd226ed 100644 --- a/java/example_code/sqs/src/main/java/aws/example/sqs/UsingQueues.java +++ b/java/example_code/sqs/src/main/java/aws/example/sqs/UsingQueues.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[<> demonstrates how to create, and delete a queue as well as list all queues in your account.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Queue Service] -//snippet-service:[sqs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2011-2019 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. - * You may obtain a copy of the License at: - * - * http://aws.amazon.com/apache2.0 - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES - * OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and - * limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.sqs; + import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClientBuilder; import com.amazonaws.services.sqs.model.AmazonSQSException; @@ -30,13 +10,11 @@ import com.amazonaws.services.sqs.model.ListQueuesResult; import java.util.Date; -public class UsingQueues -{ +public class UsingQueues { private static final String QUEUE_NAME = "testQueue" + - new Date().getTime(); + new Date().getTime(); - public static void main(String[] args) - { + public static void main(String[] args) { AmazonSQS sqs = AmazonSQSClientBuilder.defaultClient(); // Creating a Queue diff --git a/java/example_code/sqs/src/main/java/aws/example/sqs/VisibilityTimeout.java b/java/example_code/sqs/src/main/java/aws/example/sqs/VisibilityTimeout.java index d2b2f07a84f..d2bfe8a813d 100644 --- a/java/example_code/sqs/src/main/java/aws/example/sqs/VisibilityTimeout.java +++ b/java/example_code/sqs/src/main/java/aws/example/sqs/VisibilityTimeout.java @@ -1,27 +1,7 @@ -//snippet-sourcedescription:[<> demonstrates how to change the visibility timeout for a queue.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Queue Service] -//snippet-service:[sqs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2011-2019 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. - * You may obtain a copy of the License at: - * - * http://aws.amazon.com/apache2.0 - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES - * OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and - * limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.sqs; + import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClientBuilder; import com.amazonaws.services.sqs.model.ChangeMessageVisibilityBatchRequestEntry; @@ -31,53 +11,48 @@ import java.util.List; import java.util.Date; -public class VisibilityTimeout -{ +public class VisibilityTimeout { // Change the visibility timeout for a single message public static void changeMessageVisibilitySingle( - String queue_url, int timeout) - { + String queue_url, int timeout) { AmazonSQS sqs = AmazonSQSClientBuilder.defaultClient(); // Get the receipt handle for the first message in the queue. String receipt = sqs.receiveMessage(queue_url) - .getMessages() - .get(0) - .getReceiptHandle(); + .getMessages() + .get(0) + .getReceiptHandle(); sqs.changeMessageVisibility(queue_url, receipt, timeout); } // Change the visibility timeout for multiple messages. public static void changeMessageVisibilityMultiple( - String queue_url, int timeout) - { + String queue_url, int timeout) { AmazonSQS sqs = AmazonSQSClientBuilder.defaultClient(); - List entries = - new ArrayList(); + List entries = new ArrayList(); entries.add(new ChangeMessageVisibilityBatchRequestEntry( - "unique_id_msg1", - sqs.receiveMessage(queue_url) - .getMessages() - .get(0) - .getReceiptHandle()) + "unique_id_msg1", + sqs.receiveMessage(queue_url) + .getMessages() + .get(0) + .getReceiptHandle()) .withVisibilityTimeout(timeout)); entries.add(new ChangeMessageVisibilityBatchRequestEntry( - "unique_id_msg2", - sqs.receiveMessage(queue_url) - .getMessages() - .get(0) - .getReceiptHandle()) + "unique_id_msg2", + sqs.receiveMessage(queue_url) + .getMessages() + .get(0) + .getReceiptHandle()) .withVisibilityTimeout(timeout + 200)); sqs.changeMessageVisibilityBatch(queue_url, entries); } - public static void main(String[] args) - { + public static void main(String[] args) { final String queue_name = "testQueue" + new Date().getTime(); AmazonSQS sqs = AmazonSQSClientBuilder.defaultClient(); @@ -98,9 +73,9 @@ public static void main(String[] args) } // change visibility timeout (single) - changeMessageVisibilitySingle(queue_url, 60 * 60); //1 hour + changeMessageVisibilitySingle(queue_url, 60 * 60); // 1 hour // change visibility timeout (multiple) - changeMessageVisibilityMultiple(queue_url, 30 * 60 ); //30 minutes + changeMessageVisibilityMultiple(queue_url, 30 * 60); // 30 minutes } } diff --git a/java/example_code/ssm/src/main/java/aws/example/ssm/GetSimpleSystemsManagementOps.java b/java/example_code/ssm/src/main/java/aws/example/ssm/GetSimpleSystemsManagementOps.java index 79a7c982a31..e8c3b14e012 100644 --- a/java/example_code/ssm/src/main/java/aws/example/ssm/GetSimpleSystemsManagementOps.java +++ b/java/example_code/ssm/src/main/java/aws/example/ssm/GetSimpleSystemsManagementOps.java @@ -1,27 +1,5 @@ -/** - * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[GetSimpleSystemsManagementOps.java demonstrates how to get information about an OpsItem by using the ID value] -// snippet-service:[ssm] -// snippet-keyword:[Java] -// snippet-keyword:[Amazon Simple Systems Management] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-01-24] -// snippet-sourceauthor:[AWS - scmacdon] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[ssm.Java1.get_ops.complete] @@ -39,11 +17,11 @@ public class GetSimpleSystemsManagementOps { - public static void main(String[] args) { if (args.length < 1) { - System.out.println("Please specify a SSM OpsItem ID value. You can obtain this value using the AWS Console."); + System.out + .println("Please specify a SSM OpsItem ID value. You can obtain this value using the AWS Console."); System.exit(1); } @@ -53,7 +31,8 @@ public static void main(String[] args) { String opsID = args[0]; // Create the AWSSimpleSystemsManagement client object - AWSSimpleSystemsManagement ssm = AWSSimpleSystemsManagementClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); + AWSSimpleSystemsManagement ssm = AWSSimpleSystemsManagementClientBuilder.standard() + .withRegion(Regions.DEFAULT_REGION).build(); try { GetOpsItemRequest opsRequest = new GetOpsItemRequest(); diff --git a/java/example_code/ssm/src/main/java/aws/example/ssm/GetSimpleSystemsManagementParas.java b/java/example_code/ssm/src/main/java/aws/example/ssm/GetSimpleSystemsManagementParas.java index 38d46730a4b..6e3fb3bd722 100644 --- a/java/example_code/ssm/src/main/java/aws/example/ssm/GetSimpleSystemsManagementParas.java +++ b/java/example_code/ssm/src/main/java/aws/example/ssm/GetSimpleSystemsManagementParas.java @@ -1,27 +1,5 @@ -/** - * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[GetSimpleSystemsManagementParas.java demonstrates how to get information about SSM parameters by using an AWSSimpleSystemsManagement object] -// snippet-service:[ssm] -// snippet-keyword:[Java] -// snippet-keyword:[Amazon Simple Systems Management] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-01-24] -// snippet-sourceauthor:[AWS - scmacdon] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[ssm.Java1.get_params.complete] package aws.example.ssm; @@ -38,12 +16,12 @@ import com.amazonaws.AmazonServiceException; // snippet-end:[ssm.Java1.get_params.import] - public class GetSimpleSystemsManagementParas { public static void main(String[] args) { // snippet-start:[ssm.Java1.get_params.main] - AWSSimpleSystemsManagement ssm = AWSSimpleSystemsManagementClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); + AWSSimpleSystemsManagement ssm = AWSSimpleSystemsManagementClientBuilder.standard() + .withRegion(Regions.DEFAULT_REGION).build(); try { DescribeParametersRequest desRequest = new DescribeParametersRequest(); @@ -53,12 +31,12 @@ public static void main(String[] args) { List params = results.getParameters(); - //Iterate through the list + // Iterate through the list Iterator tagIterator = params.iterator(); - while(tagIterator.hasNext()) { + while (tagIterator.hasNext()) { - ParameterMetadata paraMeta = (ParameterMetadata)tagIterator.next(); + ParameterMetadata paraMeta = (ParameterMetadata) tagIterator.next(); System.out.println(paraMeta.getName()); System.out.println(paraMeta.getDescription()); diff --git a/java/example_code/stepfunctions/src/main/java/aws/example/hellosfn/StepFunctionsSample.java b/java/example_code/stepfunctions/src/main/java/aws/example/hellosfn/StepFunctionsSample.java index 7e15d2dc2f1..9ac77bf38be 100644 --- a/java/example_code/stepfunctions/src/main/java/aws/example/hellosfn/StepFunctionsSample.java +++ b/java/example_code/stepfunctions/src/main/java/aws/example/hellosfn/StepFunctionsSample.java @@ -1,25 +1,5 @@ -//snippet-sourcedescription:[StepFunctionsSample.java demonstrates how to make basic requests to Amazon Step Functions.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[states] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.hellosfn; @@ -60,20 +40,19 @@ public static void main(String[] args) throws Exception { * (~/.aws/credentials). * * It is possible to use another profile with: - * credentialsProvider = new ProfileCredentialsProvider("your-profile") + * credentialsProvider = new ProfileCredentialsProvider("your-profile") */ - ProfileCredentialsProvider credentialsProvider = - new ProfileCredentialsProvider(); + ProfileCredentialsProvider credentialsProvider = new ProfileCredentialsProvider(); try { credentialsProvider.getCredentials(); } catch (Exception e) { throw new AmazonClientException( - "Cannot load the credentials from the credential profiles " + - "file. Please make sure that your credentials file is " + - "at the correct location (~/.aws/credentials), and is " + - "in valid format.", - e); + "Cannot load the credentials from the credential profiles " + + "file. Please make sure that your credentials file is " + + "at the correct location (~/.aws/credentials), and is " + + "in valid format.", + e); } Regions region = Regions.US_EAST_1; @@ -88,8 +67,8 @@ public static void main(String[] args) throws Exception { try { System.out.println("Listing state machines"); - ListStateMachinesResult listStateMachinesResult = sfnClient. - listStateMachines(new ListStateMachinesRequest()); + ListStateMachinesResult listStateMachinesResult = sfnClient + .listStateMachines(new ListStateMachinesRequest()); List stateMachines = listStateMachinesResult .getStateMachines(); @@ -100,8 +79,7 @@ public static void main(String[] args) throws Exception { System.out.println("\t- Name: " + sm.getName()); System.out.println("\t- Arn: " + sm.getStateMachineArn()); - ListExecutionsRequest listRequest = new - ListExecutionsRequest().withStateMachineArn(sm + ListExecutionsRequest listRequest = new ListExecutionsRequest().withStateMachineArn(sm .getStateMachineArn()); ListExecutionsResult listExecutionsResult = sfnClient .listExecutions(listRequest); diff --git a/java/example_code/swf/run_workflow.sh b/java/example_code/swf/run_workflow.sh index 1da1d153d1c..99865186932 100755 --- a/java/example_code/swf/run_workflow.sh +++ b/java/example_code/swf/run_workflow.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 if [[ -z $* ]] ; then echo 'Supply the name of one of the example classes as an argument.' echo 'If there are arguments to the class, put them in quotes after the class name.' diff --git a/java/example_code/swf/src/main/java/aws/example/helloswf/ActivityWorker.java b/java/example_code/swf/src/main/java/aws/example/helloswf/ActivityWorker.java index d6f878d8fd2..0a94421e4ab 100644 --- a/java/example_code/swf/src/main/java/aws/example/helloswf/ActivityWorker.java +++ b/java/example_code/swf/src/main/java/aws/example/helloswf/ActivityWorker.java @@ -1,96 +1,77 @@ -//snippet-sourcedescription:[ActivityWorker.java demonstrates how to implement an activity worker that polls for tasks in a task list and executes its task.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[swf] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ -//snippet-start:[swf.java.activity_worker.complete] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[swf.java.activity_worker.complete] package aws.example.helloswf; -//snippet-start:[swf.java.activity_worker.import] +// snippet-start:[swf.java.activity_worker.import] import com.amazonaws.regions.Regions; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflowClientBuilder; import com.amazonaws.services.simpleworkflow.model.*; -//snippet-end:[swf.java.activity_worker.import] +// snippet-end:[swf.java.activity_worker.import] public class ActivityWorker { - //snippet-start:[swf.java.activity_worker.client] - private static final AmazonSimpleWorkflow swf = - AmazonSimpleWorkflowClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); - //snippet-end:[swf.java.activity_worker.client] + // snippet-start:[swf.java.activity_worker.client] + private static final AmazonSimpleWorkflow swf = AmazonSimpleWorkflowClientBuilder.standard() + .withRegion(Regions.DEFAULT_REGION).build(); + // snippet-end:[swf.java.activity_worker.client] - //snippet-start:[swf.java.activity_worker.sayHello] - private static String sayHello(String input) throws Throwable { - return "Hello, " + input + "!"; - } - //snippet-end:[swf.java.activity_worker.sayHello] + // snippet-start:[swf.java.activity_worker.sayHello] + private static String sayHello(String input) throws Throwable { + return "Hello, " + input + "!"; + } + // snippet-end:[swf.java.activity_worker.sayHello] - public static void main(String[] args) { - //snippet-start:[swf.java.activity_worker.main] - while (true) { - //snippet-start:[swf.java.activity_worker.poll_method] - System.out.println("Polling for an activity task from the tasklist '" - + HelloTypes.TASKLIST + "' in the domain '" + - HelloTypes.DOMAIN + "'."); + public static void main(String[] args) { + // snippet-start:[swf.java.activity_worker.main] + while (true) { + // snippet-start:[swf.java.activity_worker.poll_method] + System.out.println("Polling for an activity task from the tasklist '" + + HelloTypes.TASKLIST + "' in the domain '" + + HelloTypes.DOMAIN + "'."); - ActivityTask task = swf.pollForActivityTask( - new PollForActivityTaskRequest() - .withDomain(HelloTypes.DOMAIN) - .withTaskList( - new TaskList().withName(HelloTypes.TASKLIST))); + ActivityTask task = swf.pollForActivityTask( + new PollForActivityTaskRequest() + .withDomain(HelloTypes.DOMAIN) + .withTaskList( + new TaskList().withName(HelloTypes.TASKLIST))); - String task_token = task.getTaskToken(); - //snippet-end:[swf.java.activity_worker.poll_method] + String task_token = task.getTaskToken(); + // snippet-end:[swf.java.activity_worker.poll_method] - //snippet-start:[swf.java.activity_worker.process_tasks] - if (task_token != null) { - String result = null; - Throwable error = null; + // snippet-start:[swf.java.activity_worker.process_tasks] + if (task_token != null) { + String result = null; + Throwable error = null; - try { - System.out.println("Executing the activity task with input '" + - task.getInput() + "'."); - result = sayHello(task.getInput()); - } catch (Throwable th) { - error = th; - } + try { + System.out.println("Executing the activity task with input '" + + task.getInput() + "'."); + result = sayHello(task.getInput()); + } catch (Throwable th) { + error = th; + } - if (error == null) { - System.out.println("The activity task succeeded with result '" - + result + "'."); - swf.respondActivityTaskCompleted( - new RespondActivityTaskCompletedRequest() - .withTaskToken(task_token) - .withResult(result)); - } else { - System.out.println("The activity task failed with the error '" - + error.getClass().getSimpleName() + "'."); - swf.respondActivityTaskFailed( - new RespondActivityTaskFailedRequest() - .withTaskToken(task_token) - .withReason(error.getClass().getSimpleName()) - .withDetails(error.getMessage())); + if (error == null) { + System.out.println("The activity task succeeded with result '" + + result + "'."); + swf.respondActivityTaskCompleted( + new RespondActivityTaskCompletedRequest() + .withTaskToken(task_token) + .withResult(result)); + } else { + System.out.println("The activity task failed with the error '" + + error.getClass().getSimpleName() + "'."); + swf.respondActivityTaskFailed( + new RespondActivityTaskFailedRequest() + .withTaskToken(task_token) + .withReason(error.getClass().getSimpleName()) + .withDetails(error.getMessage())); + } + } + // snippet-end:[swf.java.activity_worker.process_tasks] } - } - //snippet-end:[swf.java.activity_worker.process_tasks] + // snippet-end:[swf.java.activity_worker.main] } - //snippet-end:[swf.java.activity_worker.main] - } } -//snippet-end:[swf.java.activity_worker.complete] \ No newline at end of file +// snippet-end:[swf.java.activity_worker.complete] \ No newline at end of file diff --git a/java/example_code/swf/src/main/java/aws/example/helloswf/ActivityWorkerWithGracefulShutdown.java b/java/example_code/swf/src/main/java/aws/example/helloswf/ActivityWorkerWithGracefulShutdown.java index 48a4749c2c7..08ed615f53c 100644 --- a/java/example_code/swf/src/main/java/aws/example/helloswf/ActivityWorkerWithGracefulShutdown.java +++ b/java/example_code/swf/src/main/java/aws/example/helloswf/ActivityWorkerWithGracefulShutdown.java @@ -1,27 +1,8 @@ -//snippet-sourcedescription:[ActivityWorkerWithGracefulShutdown.java demonstrates how to implement an activity worker with a graceful shutdown.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[swf] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.helloswf; -//snippet-start:[swf.java.activity_worker_with_graceful_shutdown.complete] +// snippet-start:[swf.java.activity_worker_with_graceful_shutdown.complete] import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -36,8 +17,8 @@ public class ActivityWorkerWithGracefulShutdown { - private static final AmazonSimpleWorkflow swf = - AmazonSimpleWorkflowClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); + private static final AmazonSimpleWorkflow swf = AmazonSimpleWorkflowClientBuilder.standard() + .withRegion(Regions.DEFAULT_REGION).build(); private static CountDownLatch waitForTermination = new CountDownLatch(1); private static volatile boolean terminate = false; @@ -54,16 +35,14 @@ public void run() { System.out.println("Waiting for the current poll request" + " to return before shutting down."); waitForTermination.await(60, TimeUnit.SECONDS); - } - catch (InterruptedException e) { + } catch (InterruptedException e) { // ignore } } }); try { pollAndExecute(); - } - finally { + } finally { waitForTermination.countDown(); } } @@ -75,8 +54,8 @@ public static void pollAndExecute() { HelloTypes.DOMAIN + "'."); ActivityTask task = swf.pollForActivityTask(new PollForActivityTaskRequest() - .withDomain(HelloTypes.DOMAIN) - .withTaskList(new TaskList().withName(HelloTypes.TASKLIST))); + .withDomain(HelloTypes.DOMAIN) + .withTaskList(new TaskList().withName(HelloTypes.TASKLIST))); String taskToken = task.getTaskToken(); @@ -88,8 +67,7 @@ public static void pollAndExecute() { System.out.println("Executing the activity task with input '" + task.getInput() + "'."); result = executeActivityTask(task.getInput()); - } - catch (Throwable th) { + } catch (Throwable th) { error = th; } @@ -97,21 +75,20 @@ public static void pollAndExecute() { System.out.println("The activity task succeeded with result '" + result + "'."); swf.respondActivityTaskCompleted( - new RespondActivityTaskCompletedRequest() - .withTaskToken(taskToken) - .withResult(result)); - } - else { + new RespondActivityTaskCompletedRequest() + .withTaskToken(taskToken) + .withResult(result)); + } else { System.out.println("The activity task failed with the error '" + error.getClass().getSimpleName() + "'."); swf.respondActivityTaskFailed( - new RespondActivityTaskFailedRequest() - .withTaskToken(taskToken) - .withReason(error.getClass().getSimpleName()) - .withDetails(error.getMessage())); + new RespondActivityTaskFailedRequest() + .withTaskToken(taskToken) + .withReason(error.getClass().getSimpleName()) + .withDetails(error.getMessage())); } } } } } -//snippet-end:[swf.java.activity_worker_with_graceful_shutdown.complete] +// snippet-end:[swf.java.activity_worker_with_graceful_shutdown.complete] diff --git a/java/example_code/swf/src/main/java/aws/example/helloswf/HelloTypes.java b/java/example_code/swf/src/main/java/aws/example/helloswf/HelloTypes.java index 201c6dc95d1..33b69f290fb 100644 --- a/java/example_code/swf/src/main/java/aws/example/helloswf/HelloTypes.java +++ b/java/example_code/swf/src/main/java/aws/example/helloswf/HelloTypes.java @@ -1,108 +1,89 @@ -//snippet-sourcedescription:[HelloTypes.java demonstrates how to register a domain, activity type and a workflow type.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[swf] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ -//snippet-start:[swf.java.hello_types.complete] -//snippet-start:[swf.java.hello_types.package] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[swf.java.hello_types.complete] +// snippet-start:[swf.java.hello_types.package] package aws.example.helloswf; -//snippet-end:[swf.java.hello_types.package] +// snippet-end:[swf.java.hello_types.package] -//snippet-start:[swf.java.hello_types.import] +// snippet-start:[swf.java.hello_types.import] import com.amazonaws.regions.Regions; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflowClientBuilder; import com.amazonaws.services.simpleworkflow.model.*; -//snippet-end:[swf.java.hello_types.import] +// snippet-end:[swf.java.hello_types.import] public class HelloTypes { - //snippet-start:[swf.java.hello_types.string_declare] + // snippet-start:[swf.java.hello_types.string_declare] public static final String DOMAIN = "HelloDomain"; public static final String TASKLIST = "HelloTasklist"; public static final String WORKFLOW = "HelloWorkflow"; public static final String WORKFLOW_VERSION = "1.0"; public static final String ACTIVITY = "HelloActivity"; public static final String ACTIVITY_VERSION = "1.0"; - //snippet-end:[swf.java.hello_types.string_declare] + // snippet-end:[swf.java.hello_types.string_declare] - //snippet-start:[swf.java.hello_types.client] - private static final AmazonSimpleWorkflow swf = - AmazonSimpleWorkflowClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); - //snippet-end:[swf.java.hello_types.client] + // snippet-start:[swf.java.hello_types.client] + private static final AmazonSimpleWorkflow swf = AmazonSimpleWorkflowClientBuilder.standard() + .withRegion(Regions.DEFAULT_REGION).build(); + // snippet-end:[swf.java.hello_types.client] public static void registerDomain() { - //snippet-start:[swf.java.hello_types.new_function] + // snippet-start:[swf.java.hello_types.new_function] try { System.out.println("** Registering the domain '" + DOMAIN + "'."); swf.registerDomain(new RegisterDomainRequest() - .withName(DOMAIN) - .withWorkflowExecutionRetentionPeriodInDays("1")); + .withName(DOMAIN) + .withWorkflowExecutionRetentionPeriodInDays("1")); } catch (DomainAlreadyExistsException e) { System.out.println("** Domain already exists!"); } - //snippet-end:[swf.java.hello_types.new_function] + // snippet-end:[swf.java.hello_types.new_function] } public static void registerActivityType() { - //snippet-start:[swf.java.hello_types.new_activity_type] + // snippet-start:[swf.java.hello_types.new_activity_type] try { System.out.println("** Registering the activity type '" + ACTIVITY + - "-" + ACTIVITY_VERSION + "'."); + "-" + ACTIVITY_VERSION + "'."); swf.registerActivityType(new RegisterActivityTypeRequest() - .withDomain(DOMAIN) - .withName(ACTIVITY) - .withVersion(ACTIVITY_VERSION) - .withDefaultTaskList(new TaskList().withName(TASKLIST)) - .withDefaultTaskScheduleToStartTimeout("30") - .withDefaultTaskStartToCloseTimeout("600") - .withDefaultTaskScheduleToCloseTimeout("630") - .withDefaultTaskHeartbeatTimeout("10")); + .withDomain(DOMAIN) + .withName(ACTIVITY) + .withVersion(ACTIVITY_VERSION) + .withDefaultTaskList(new TaskList().withName(TASKLIST)) + .withDefaultTaskScheduleToStartTimeout("30") + .withDefaultTaskStartToCloseTimeout("600") + .withDefaultTaskScheduleToCloseTimeout("630") + .withDefaultTaskHeartbeatTimeout("10")); } catch (TypeAlreadyExistsException e) { System.out.println("** Activity type already exists!"); } - //snippet-end:[swf.java.hello_types.new_activity_type] + // snippet-end:[swf.java.hello_types.new_activity_type] } public static void registerWorkflowType() { - //snippet-start:[swf.java.hello_types.new_workflow_type] + // snippet-start:[swf.java.hello_types.new_workflow_type] try { System.out.println("** Registering the workflow type '" + WORKFLOW + - "-" + WORKFLOW_VERSION + "'."); + "-" + WORKFLOW_VERSION + "'."); swf.registerWorkflowType(new RegisterWorkflowTypeRequest() - .withDomain(DOMAIN) - .withName(WORKFLOW) - .withVersion(WORKFLOW_VERSION) - .withDefaultChildPolicy(ChildPolicy.TERMINATE) - .withDefaultTaskList(new TaskList().withName(TASKLIST)) - .withDefaultTaskStartToCloseTimeout("30")); + .withDomain(DOMAIN) + .withName(WORKFLOW) + .withVersion(WORKFLOW_VERSION) + .withDefaultChildPolicy(ChildPolicy.TERMINATE) + .withDefaultTaskList(new TaskList().withName(TASKLIST)) + .withDefaultTaskStartToCloseTimeout("30")); } catch (TypeAlreadyExistsException e) { System.out.println("** Workflow type already exists!"); } - //snippet-end:[swf.java.hello_types.new_workflow_type] + // snippet-end:[swf.java.hello_types.new_workflow_type] } public static void main(String[] args) { - //snippet-start:[swf.java.hello_types.main] + // snippet-start:[swf.java.hello_types.main] registerDomain(); registerWorkflowType(); registerActivityType(); - //snippet-end:[swf.java.hello_types.main] + // snippet-end:[swf.java.hello_types.main] } } -//snippet-end:[swf.java.hello_types.complete] \ No newline at end of file +// snippet-end:[swf.java.hello_types.complete] \ No newline at end of file diff --git a/java/example_code/swf/src/main/java/aws/example/helloswf/WorkflowStarter.java b/java/example_code/swf/src/main/java/aws/example/helloswf/WorkflowStarter.java index dcf5110c997..fda58f453d6 100644 --- a/java/example_code/swf/src/main/java/aws/example/helloswf/WorkflowStarter.java +++ b/java/example_code/swf/src/main/java/aws/example/helloswf/WorkflowStarter.java @@ -1,64 +1,44 @@ -//snippet-sourcedescription:[WorkflowStarter.java demonstrates how to start a workflow.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[swf] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ -//snippet-start:[swf.java.workflow_starter.complete] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[swf.java.workflow_starter.complete] package aws.example.helloswf; - -//snippet-start:[swf.java.workflow_starter.import] +// snippet-start:[swf.java.workflow_starter.import] import com.amazonaws.regions.Regions; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflowClientBuilder; import com.amazonaws.services.simpleworkflow.model.*; -//snippet-end:[swf.java.workflow_starter.import] +// snippet-end:[swf.java.workflow_starter.import] -//snippet-start:[swf.java.workflow_starter.main] +// snippet-start:[swf.java.workflow_starter.main] public class WorkflowStarter { - private static final AmazonSimpleWorkflow swf = - AmazonSimpleWorkflowClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); - public static final String WORKFLOW_EXECUTION = "HelloWorldWorkflowExecution"; - - public static void main(String[] args) { - String workflow_input = "Amazon SWF"; - if (args.length > 0) { - workflow_input = args[0]; + private static final AmazonSimpleWorkflow swf = AmazonSimpleWorkflowClientBuilder.standard() + .withRegion(Regions.DEFAULT_REGION).build(); + public static final String WORKFLOW_EXECUTION = "HelloWorldWorkflowExecution"; + + public static void main(String[] args) { + String workflow_input = "Amazon SWF"; + if (args.length > 0) { + workflow_input = args[0]; + } + + System.out.println("Starting the workflow execution '" + WORKFLOW_EXECUTION + + "' with input '" + workflow_input + "'."); + + WorkflowType wf_type = new WorkflowType() + .withName(HelloTypes.WORKFLOW) + .withVersion(HelloTypes.WORKFLOW_VERSION); + + Run run = swf.startWorkflowExecution(new StartWorkflowExecutionRequest() + .withDomain(HelloTypes.DOMAIN) + .withWorkflowType(wf_type) + .withWorkflowId(WORKFLOW_EXECUTION) + .withInput(workflow_input) + .withExecutionStartToCloseTimeout("90")); + + System.out.println("Workflow execution started with the run id '" + + run.getRunId() + "'."); } - - System.out.println("Starting the workflow execution '" + WORKFLOW_EXECUTION + - "' with input '" + workflow_input + "'."); - - WorkflowType wf_type = new WorkflowType() - .withName(HelloTypes.WORKFLOW) - .withVersion(HelloTypes.WORKFLOW_VERSION); - - Run run = swf.startWorkflowExecution(new StartWorkflowExecutionRequest() - .withDomain(HelloTypes.DOMAIN) - .withWorkflowType(wf_type) - .withWorkflowId(WORKFLOW_EXECUTION) - .withInput(workflow_input) - .withExecutionStartToCloseTimeout("90")); - - System.out.println("Workflow execution started with the run id '" + - run.getRunId() + "'."); - } } -//snippet-end:[swf.java.workflow_starter.main] -//snippet-end:[swf.java.workflow_starter.complete] +// snippet-end:[swf.java.workflow_starter.main] +// snippet-end:[swf.java.workflow_starter.complete] diff --git a/java/example_code/swf/src/main/java/aws/example/helloswf/WorkflowWorker.java b/java/example_code/swf/src/main/java/aws/example/helloswf/WorkflowWorker.java index d00b2162c27..3206615672a 100644 --- a/java/example_code/swf/src/main/java/aws/example/helloswf/WorkflowWorker.java +++ b/java/example_code/swf/src/main/java/aws/example/helloswf/WorkflowWorker.java @@ -1,28 +1,9 @@ -//snippet-sourcedescription:[WorkflowWorker.java demonstrates how to poll for a decision task in a task list.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[swf] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 2010-2019 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. - */ -//snippet-start:[swf.java.workflow_worker.complete] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[swf.java.workflow_worker.complete] package aws.example.helloswf; -//snippet-start:[swf.java.workflow_worker.import] +// snippet-start:[swf.java.workflow_worker.import] import com.amazonaws.regions.Regions; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflowClientBuilder; @@ -30,26 +11,25 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; -//snippet-end:[swf.java.workflow_worker.import] +// snippet-end:[swf.java.workflow_worker.import] public class WorkflowWorker { - //snippet-start:[swf.java.workflow_worker.client] - private static final AmazonSimpleWorkflow swf = - AmazonSimpleWorkflowClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build(); - //snippet-end:[swf.java.workflow_worker.client] + // snippet-start:[swf.java.workflow_worker.client] + private static final AmazonSimpleWorkflow swf = AmazonSimpleWorkflowClientBuilder.standard() + .withRegion(Regions.DEFAULT_REGION).build(); + // snippet-end:[swf.java.workflow_worker.client] public static void main(String[] args) { - //snippet-start:[swf.java.workflow_worker.main] - PollForDecisionTaskRequest task_request = - new PollForDecisionTaskRequest() + // snippet-start:[swf.java.workflow_worker.main] + PollForDecisionTaskRequest task_request = new PollForDecisionTaskRequest() .withDomain(HelloTypes.DOMAIN) .withTaskList(new TaskList().withName(HelloTypes.TASKLIST)); while (true) { System.out.println( "Polling for a decision task from the tasklist '" + - HelloTypes.TASKLIST + "' in the domain '" + - HelloTypes.DOMAIN + "'."); + HelloTypes.TASKLIST + "' in the domain '" + + HelloTypes.DOMAIN + "'."); DecisionTask task = swf.pollForDecisionTask(task_request); @@ -62,35 +42,36 @@ public static void main(String[] args) { } } } - //snippet-end:[swf.java.workflow_worker.main] + // snippet-end:[swf.java.workflow_worker.main] } /** - * The goal of this workflow is to execute at least one HelloActivity successfully. + * The goal of this workflow is to execute at least one HelloActivity + * successfully. * - * We pass the workflow execution's input to the activity, and we use the activity's result + * We pass the workflow execution's input to the activity, and we use the + * activity's result * as the output of the workflow. */ private static void executeDecisionTask(String taskToken, List events) throws Throwable { - //snippet-start:[swf.java.workflow_worker.execute_decision_task_token] + // snippet-start:[swf.java.workflow_worker.execute_decision_task_token] List decisions = new ArrayList(); String workflow_input = null; int scheduled_activities = 0; int open_activities = 0; boolean activity_completed = false; String result = null; - //snippet-end:[swf.java.workflow_worker.execute_decision_task_token] + // snippet-end:[swf.java.workflow_worker.execute_decision_task_token] - //snippet-start:[swf.java.workflow_worker.execute_decision_task_history_events] + // snippet-start:[swf.java.workflow_worker.execute_decision_task_history_events] System.out.println("Executing the decision task for the history events: ["); for (HistoryEvent event : events) { System.out.println(" " + event); - switch(event.getEventType()) { + switch (event.getEventType()) { case "WorkflowExecutionStarted": - workflow_input = - event.getWorkflowExecutionStartedEventAttributes() - .getInput(); + workflow_input = event.getWorkflowExecutionStartedEventAttributes() + .getInput(); break; case "ActivityTaskScheduled": scheduled_activities++; @@ -106,7 +87,7 @@ private static void executeDecisionTask(String taskToken, List eve open_activities--; activity_completed = true; result = event.getActivityTaskCompletedEventAttributes() - .getResult(); + .getResult(); break; case "ActivityTaskFailed": open_activities--; @@ -117,46 +98,46 @@ private static void executeDecisionTask(String taskToken, List eve } } System.out.println("]"); - //snippet-end:[swf.java.workflow_worker.execute_decision_task_history_events] + // snippet-end:[swf.java.workflow_worker.execute_decision_task_history_events] - //snippet-start:[swf.java.workflow_worker.task_decision] + // snippet-start:[swf.java.workflow_worker.task_decision] if (activity_completed) { decisions.add( - new Decision() - .withDecisionType(DecisionType.CompleteWorkflowExecution) - .withCompleteWorkflowExecutionDecisionAttributes( - new CompleteWorkflowExecutionDecisionAttributes() - .withResult(result))); + new Decision() + .withDecisionType(DecisionType.CompleteWorkflowExecution) + .withCompleteWorkflowExecutionDecisionAttributes( + new CompleteWorkflowExecutionDecisionAttributes() + .withResult(result))); } else { if (open_activities == 0 && scheduled_activities == 0) { - ScheduleActivityTaskDecisionAttributes attrs = - new ScheduleActivityTaskDecisionAttributes() + ScheduleActivityTaskDecisionAttributes attrs = new ScheduleActivityTaskDecisionAttributes() .withActivityType(new ActivityType() - .withName(HelloTypes.ACTIVITY) - .withVersion(HelloTypes.ACTIVITY_VERSION)) + .withName(HelloTypes.ACTIVITY) + .withVersion(HelloTypes.ACTIVITY_VERSION)) .withActivityId(UUID.randomUUID().toString()) .withInput(workflow_input); decisions.add( new Decision() - .withDecisionType(DecisionType.ScheduleActivityTask) - .withScheduleActivityTaskDecisionAttributes(attrs)); + .withDecisionType(DecisionType.ScheduleActivityTask) + .withScheduleActivityTaskDecisionAttributes(attrs)); } else { - // an instance of HelloActivity is already scheduled or running. Do nothing, another + // an instance of HelloActivity is already scheduled or running. Do nothing, + // another // task will be scheduled once the activity completes, fails or times out } } System.out.println("Exiting the decision task with the decisions " + decisions); - //snippet-end:[swf.java.workflow_worker.task_decision] + // snippet-end:[swf.java.workflow_worker.task_decision] - //snippet-start:[swf.java.workflow_worker.return_decision_objects] + // snippet-start:[swf.java.workflow_worker.return_decision_objects] swf.respondDecisionTaskCompleted( - new RespondDecisionTaskCompletedRequest() - .withTaskToken(taskToken) - .withDecisions(decisions)); - //snippet-end:[swf.java.workflow_worker.return_decision_objects] + new RespondDecisionTaskCompletedRequest() + .withTaskToken(taskToken) + .withDecisions(decisions)); + // snippet-end:[swf.java.workflow_worker.return_decision_objects] } } -//snippet-end:[swf.java.workflow_worker.complete] \ No newline at end of file +// snippet-end:[swf.java.workflow_worker.complete] \ No newline at end of file diff --git a/java/example_code/textract/run_example.sh b/java/example_code/textract/run_example.sh index 9af61cd102d..dfd04901f6a 100644 --- a/java/example_code/textract/run_example.sh +++ b/java/example_code/textract/run_example.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 if [[ -z $* ]] ; then echo 'Supply the name of one of the example classes as an argument.' echo 'If there are arguments to the class, put them in quotes after the class name.' diff --git a/java/example_code/textract/src/main/java/com/amazonaws/samples/AnalyzeDocument.java b/java/example_code/textract/src/main/java/com/amazonaws/samples/AnalyzeDocument.java index b7423813eaf..cd83d6115e2 100644 --- a/java/example_code/textract/src/main/java/com/amazonaws/samples/AnalyzeDocument.java +++ b/java/example_code/textract/src/main/java/com/amazonaws/samples/AnalyzeDocument.java @@ -1,15 +1,5 @@ -// snippet-sourcedescription:[AnalyzeDocument.java demonstrates how to display bounding boxes around analyzed text.] -// snippet-service:[textract] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Textract] -// snippet-keyword:[Code Sample] -// snippet-keyword:[AnalyzeDocument] -// snippet-keyword:[Bounding Box] -// snippet-keyword:[Synchronous] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-04-11] -// snippet-sourceauthor:[reesch(AWS)] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[textract.java.textract-java-analyze-text-sync.complete] //Loads document from S3 bucket. Displays the document and polygon around detected lines of text. package com.amazonaws.samples; @@ -45,7 +35,6 @@ public class AnalyzeDocument extends JPanel { public AnalyzeDocument(AnalyzeDocumentResult documentResult, BufferedImage bufImage) throws Exception { super(); - result = documentResult; // Results of text detection. image = bufImage; // The image containing the document. @@ -67,32 +56,31 @@ public void paintComponent(Graphics g) { List blocks = result.getBlocks(); for (Block block : blocks) { DisplayBlockInfo(block); - switch(block.getBlockType()) { - - case "KEY_VALUE_SET": - if (block.getEntityTypes().contains("KEY")){ - ShowBoundingBox(height, width, block.getGeometry().getBoundingBox(), g2d, new Color(255,0,0)); - } - else { //VALUE - ShowBoundingBox(height, width, block.getGeometry().getBoundingBox(), g2d, new Color(0,255,0)); - } - break; - case "TABLE": - ShowBoundingBox(height, width, block.getGeometry().getBoundingBox(), g2d, new Color(0,0,255)); - break; - case "CELL": - ShowBoundingBox(height, width, block.getGeometry().getBoundingBox(), g2d, new Color(255,255,0)); - break; - default: - //PAGE, LINE & WORD - //ShowBoundingBox(height, width, block.getGeometry().getBoundingBox(), g2d, new Color(200,200,0)); + switch (block.getBlockType()) { + + case "KEY_VALUE_SET": + if (block.getEntityTypes().contains("KEY")) { + ShowBoundingBox(height, width, block.getGeometry().getBoundingBox(), g2d, new Color(255, 0, 0)); + } else { // VALUE + ShowBoundingBox(height, width, block.getGeometry().getBoundingBox(), g2d, new Color(0, 255, 0)); + } + break; + case "TABLE": + ShowBoundingBox(height, width, block.getGeometry().getBoundingBox(), g2d, new Color(0, 0, 255)); + break; + case "CELL": + ShowBoundingBox(height, width, block.getGeometry().getBoundingBox(), g2d, new Color(255, 255, 0)); + break; + default: + // PAGE, LINE & WORD + // ShowBoundingBox(height, width, block.getGeometry().getBoundingBox(), g2d, new + // Color(200,200,0)); } } - // uncomment to show polygon around all blocks - //ShowPolygon(height,width,block.getGeometry().getPolygon(),g2d); - - + // uncomment to show polygon around all blocks + // ShowPolygon(height,width,block.getGeometry().getPolygon(),g2d); + } // Show bounding box at supplied location. @@ -121,18 +109,19 @@ private void ShowPolygon(int imageHeight, int imageWidth, List points, Gr } g2d.drawPolygon(polygon); } - //Displays information from a block returned by text detection and text analysis + + // Displays information from a block returned by text detection and text + // analysis private void DisplayBlockInfo(Block block) { System.out.println("Block Id : " + block.getId()); - if (block.getText()!=null) + if (block.getText() != null) System.out.println(" Detected text: " + block.getText()); System.out.println(" Type: " + block.getBlockType()); - - if (block.getBlockType().equals("PAGE") !=true) { + + if (block.getBlockType().equals("PAGE") != true) { System.out.println(" Confidence: " + block.getConfidence().toString()); } - if(block.getBlockType().equals("CELL")) - { + if (block.getBlockType().equals("CELL")) { System.out.println(" Cell information:"); System.out.println(" Column: " + block.getColumnIndex()); System.out.println(" Row: " + block.getRowIndex()); @@ -140,10 +129,10 @@ private void DisplayBlockInfo(Block block) { System.out.println(" Row span: " + block.getRowSpan()); } - + System.out.println(" Relationships"); - List relationships=block.getRelationships(); - if(relationships!=null) { + List relationships = block.getRelationships(); + if (relationships != null) { for (Relationship relationship : relationships) { System.out.println(" Type: " + relationship.getType()); System.out.println(" IDs: " + relationship.getIds().toString()); @@ -155,19 +144,19 @@ private void DisplayBlockInfo(Block block) { System.out.println(" Geometry"); System.out.println(" Bounding Box: " + block.getGeometry().getBoundingBox().toString()); System.out.println(" Polygon: " + block.getGeometry().getPolygon().toString()); - + List entityTypes = block.getEntityTypes(); - + System.out.println(" Entity Types"); - if(entityTypes!=null) { + if (entityTypes != null) { for (String entityType : entityTypes) { System.out.println(" Entity Type: " + entityType); } } else { System.out.println(" No entity type"); } - if(block.getPage()!=null) - System.out.println(" Page: " + block.getPage()); + if (block.getPage() != null) + System.out.println(" Page: " + block.getPage()); System.out.println(); } @@ -178,28 +167,24 @@ public static void main(String arg[]) throws Exception { String bucket = ""; AmazonS3 s3client = AmazonS3ClientBuilder.standard() - .withEndpointConfiguration( - new EndpointConfiguration("https://s3.amazonaws.com","us-east-1")) + .withEndpointConfiguration( + new EndpointConfiguration("https://s3.amazonaws.com", "us-east-1")) .build(); - - + // Get the document from S3 com.amazonaws.services.s3.model.S3Object s3object = s3client.getObject(bucket, document); S3ObjectInputStream inputStream = s3object.getObjectContent(); BufferedImage image = ImageIO.read(inputStream); - // Call AnalyzeDocument + // Call AnalyzeDocument EndpointConfiguration endpoint = new EndpointConfiguration( "https://textract.us-east-1.amazonaws.com", "us-east-1"); AmazonTextract client = AmazonTextractClientBuilder.standard() .withEndpointConfiguration(endpoint).build(); - AnalyzeDocumentRequest request = new AnalyzeDocumentRequest() - .withFeatureTypes("TABLES","FORMS") - .withDocument(new Document(). - withS3Object(new S3Object().withName(document).withBucket(bucket))); - + .withFeatureTypes("TABLES", "FORMS") + .withDocument(new Document().withS3Object(new S3Object().withName(document).withBucket(bucket))); AnalyzeDocumentResult result = client.analyzeDocument(request); @@ -210,7 +195,7 @@ public static void main(String arg[]) throws Exception { panel.setPreferredSize(new Dimension(image.getWidth(), image.getHeight())); frame.setContentPane(panel); frame.pack(); - frame.setVisible(true); + frame.setVisible(true); } } diff --git a/java/example_code/textract/src/main/java/com/amazonaws/samples/DocumentText.java b/java/example_code/textract/src/main/java/com/amazonaws/samples/DocumentText.java index e061182ee5f..98504221ed4 100644 --- a/java/example_code/textract/src/main/java/com/amazonaws/samples/DocumentText.java +++ b/java/example_code/textract/src/main/java/com/amazonaws/samples/DocumentText.java @@ -1,32 +1,9 @@ -// snippet-sourcedescription:[DocumentText.java demonstrates how to display bounding boxes around detected text.] -// snippet-service:[textract] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Textract] -// snippet-keyword:[Code Sample] -// snippet-keyword:[DetectDocumentText] -// snippet-keyword:[Bounding Box] -// snippet-keyword:[Synchronous] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-04-11] -// snippet-sourceauthor:[reesch(AWS)] -// snippet-start:[textract.java.textract-java-detect-text-sync.complete] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ -//Calls DetectDocumentText. -//Loads document from S3 bucket. Displays the document and bounding boxes around detected lines/words of text. +// snippet-start:[textract.java.textract-java-detect-text-sync.complete] +// Calls DetectDocumentText. +// Loads document from S3 bucket. Displays the document and bounding boxes around detected lines/words of text. package com.amazonaws.samples; import java.awt.*; @@ -58,7 +35,7 @@ public class DocumentText extends JPanel { public DocumentText(DetectDocumentTextResult documentResult, BufferedImage bufImage) throws Exception { super(); - + result = documentResult; // Results of text detection. image = bufImage; // The image containing the document. @@ -73,7 +50,7 @@ public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; // Create a Java2D version of g. // Draw the image. - g2d.drawImage(image, 0, 0, image.getWidth(this) , image.getHeight(this), this); + g2d.drawImage(image, 0, 0, image.getWidth(this), image.getHeight(this), this); // Iterate through blocks and display polygons around lines of detected text. List blocks = result.getBlocks(); @@ -82,7 +59,7 @@ public void paintComponent(Graphics g) { if ((block.getBlockType()).equals("LINE")) { ShowPolygon(height, width, block.getGeometry().getPolygon(), g2d); /* - ShowBoundingBox(height, width, block.getGeometry().getBoundingBox(), g2d); + * ShowBoundingBox(height, width, block.getGeometry().getBoundingBox(), g2d); */ } else { // its a word, so just show vertical lines. ShowPolygonVerticals(height, width, block.getGeometry().getPolygon(), g2d); @@ -134,18 +111,19 @@ private void ShowPolygonVerticals(int imageHeight, int imageWidth, List p Math.round(((Point) parry[2]).getY() * imageHeight)); } - //Displays information from a block returned by text detection and text analysis + + // Displays information from a block returned by text detection and text + // analysis private void DisplayBlockInfo(Block block) { System.out.println("Block Id : " + block.getId()); - if (block.getText()!=null) + if (block.getText() != null) System.out.println(" Detected text: " + block.getText()); System.out.println(" Type: " + block.getBlockType()); - - if (block.getBlockType().equals("PAGE") !=true) { + + if (block.getBlockType().equals("PAGE") != true) { System.out.println(" Confidence: " + block.getConfidence().toString()); } - if(block.getBlockType().equals("CELL")) - { + if (block.getBlockType().equals("CELL")) { System.out.println(" Cell information:"); System.out.println(" Column: " + block.getColumnIndex()); System.out.println(" Row: " + block.getRowIndex()); @@ -153,10 +131,10 @@ private void DisplayBlockInfo(Block block) { System.out.println(" Row span: " + block.getRowSpan()); } - + System.out.println(" Relationships"); - List relationships=block.getRelationships(); - if(relationships!=null) { + List relationships = block.getRelationships(); + if (relationships != null) { for (Relationship relationship : relationships) { System.out.println(" Type: " + relationship.getType()); System.out.println(" IDs: " + relationship.getIds().toString()); @@ -168,35 +146,33 @@ private void DisplayBlockInfo(Block block) { System.out.println(" Geometry"); System.out.println(" Bounding Box: " + block.getGeometry().getBoundingBox().toString()); System.out.println(" Polygon: " + block.getGeometry().getPolygon().toString()); - + List entityTypes = block.getEntityTypes(); - + System.out.println(" Entity Types"); - if(entityTypes!=null) { + if (entityTypes != null) { for (String entityType : entityTypes) { System.out.println(" Entity Type: " + entityType); } } else { System.out.println(" No entity type"); } - if(block.getPage()!=null) - System.out.println(" Page: " + block.getPage()); + if (block.getPage() != null) + System.out.println(" Page: " + block.getPage()); System.out.println(); } public static void main(String arg[]) throws Exception { - + // The S3 bucket and document String document = ""; String bucket = ""; - AmazonS3 s3client = AmazonS3ClientBuilder.standard() - .withEndpointConfiguration( - new EndpointConfiguration("https://s3.amazonaws.com","us-east-1")) + .withEndpointConfiguration( + new EndpointConfiguration("https://s3.amazonaws.com", "us-east-1")) .build(); - - + // Get the document from S3 com.amazonaws.services.s3.model.S3Object s3object = s3client.getObject(bucket, document); S3ObjectInputStream inputStream = s3object.getObjectContent(); @@ -208,17 +184,16 @@ public static void main(String arg[]) throws Exception { AmazonTextract client = AmazonTextractClientBuilder.standard() .withEndpointConfiguration(endpoint).build(); - DetectDocumentTextRequest request = new DetectDocumentTextRequest() - .withDocument(new Document().withS3Object(new S3Object().withName(document).withBucket(bucket))); + .withDocument(new Document().withS3Object(new S3Object().withName(document).withBucket(bucket))); DetectDocumentTextResult result = client.detectDocumentText(request); - + // Create frame and panel. JFrame frame = new JFrame("RotateImage"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); DocumentText panel = new DocumentText(result, image); - panel.setPreferredSize(new Dimension(image.getWidth() , image.getHeight() )); + panel.setPreferredSize(new Dimension(image.getWidth(), image.getHeight())); frame.setContentPane(panel); frame.pack(); frame.setVisible(true); diff --git a/java/example_code/translate/TranslateText.java b/java/example_code/translate/TranslateText.java index 1e104d30f98..965e40274f6 100644 --- a/java/example_code/translate/TranslateText.java +++ b/java/example_code/translate/TranslateText.java @@ -1,29 +1,7 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[TranslateText demonstrates how to use the translatetext operation.] -// snippet-service:[translate] -// snippet-keyword:[Java] -// snippet-sourcesyntax:[java] -// snippet-keyword:[Amazon Translate] -// snippet-keyword:[Code Sample] -// snippet-keyword:[TranslateText] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-31] -// snippet-sourceauthor:[AWS] -// snippet-start:[translate.java.translatetext.complete] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// snippet-start:[translate.java.translatetext.complete] import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; @@ -36,12 +14,12 @@ public class App { private static final String REGION = "region"; - public static void main( String[] args ) { + public static void main(String[] args) { // Create credentials using a provider chain. For more information, see // https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html AWSCredentialsProvider awsCreds = DefaultAWSCredentialsProviderChain.getInstance(); - + AWSTranslate translate = AmazonTranslateClient.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCreds)) .withRegion(REGION) @@ -51,10 +29,9 @@ public static void main( String[] args ) { .withText("Hello, world") .withSourceLanguageCode("en") .withTargetLanguageCode("es"); - TranslateTextResult result = translate.translateText(request); + TranslateTextResult result = translate.translateText(request); System.out.println(result.getTranslatedText()); } } - // snippet-end:[translate.java.translatetext.complete] \ No newline at end of file diff --git a/java/example_code/workdocs/download-user-doc/src/main/java/aws/example/workdocs/DownloadUserDoc.java b/java/example_code/workdocs/download-user-doc/src/main/java/aws/example/workdocs/DownloadUserDoc.java index 95ead30c079..1f9a33ad13b 100644 --- a/java/example_code/workdocs/download-user-doc/src/main/java/aws/example/workdocs/DownloadUserDoc.java +++ b/java/example_code/workdocs/download-user-doc/src/main/java/aws/example/workdocs/DownloadUserDoc.java @@ -1,170 +1,167 @@ -//snippet-sourcedescription:[download_user_doc.java demonstrates how to download a document from AWS Workdocs.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[workdocs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-10-28] -//snippet-sourceauthor:[m-czernek] -package aws.example.workdocs; - -import java.io.InputStream; -import java.net.URL; -import java.net.URLConnection; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.amazonaws.services.workdocs.AmazonWorkDocs; -import com.amazonaws.services.workdocs.AmazonWorkDocsClientBuilder; -import com.amazonaws.services.workdocs.model.DescribeFolderContentsRequest; -import com.amazonaws.services.workdocs.model.DescribeFolderContentsResult; -import com.amazonaws.services.workdocs.model.DescribeUsersRequest; -import com.amazonaws.services.workdocs.model.DescribeUsersResult; -import com.amazonaws.services.workdocs.model.DocumentMetadata; -import com.amazonaws.services.workdocs.model.DocumentSourceType; -import com.amazonaws.services.workdocs.model.DocumentVersionMetadata; -import com.amazonaws.services.workdocs.model.GetDocumentVersionRequest; -import com.amazonaws.services.workdocs.model.GetDocumentVersionResult; -import com.amazonaws.services.workdocs.model.InitiateDocumentVersionUploadRequest; -import com.amazonaws.services.workdocs.model.InitiateDocumentVersionUploadResult; -import com.amazonaws.services.workdocs.model.UploadMetadata; -import com.amazonaws.services.workdocs.model.User; - -public class DownloadUserDoc { - - private static String getUserFolder(AmazonWorkDocs workDocs, String orgId, String user) throws Exception { - String user_folder = ""; - List wdUsers = new ArrayList<>(); - DescribeUsersRequest request = new DescribeUsersRequest(); - - request.setOrganizationId(orgId); - - String marker = null; - - do { - request.setMarker(marker); - request.setQuery(user); - - DescribeUsersResult result = workDocs.describeUsers(request); - - wdUsers.addAll(result.getUsers()); - marker = result.getMarker(); - } while (marker != null); - - // We should only have one user in this list - int num_users = wdUsers.size(); - - if (num_users != 1) { - System.out.println("WARNING!!!"); - System.out.println("Found " + num_users + " but expected to find only one"); - } - - for (User wdUser : wdUsers) { - //DescribeFolderContentsRequest dfc_request = new DescribeFolderContentsRequest(); - user_folder = wdUser.getRootFolderId(); - } - - return user_folder; - } - - private static Map getDocInfo(AmazonWorkDocs workDocs, String orgId, String user, String docName) throws Exception { - // Java code: http://docs.aws.amazon.com/workdocs/latest/developerguide/download-documents.html - Map map = new HashMap(); - String folderId = getUserFolder(workDocs, orgId, user); - - if ("".equals(folderId)) { - System.out.println("Could not get user folder"); - } else { - - DescribeFolderContentsRequest dfc_request = new DescribeFolderContentsRequest(); - dfc_request.setFolderId(folderId); - - DescribeFolderContentsResult result = workDocs.describeFolderContents(dfc_request); - - List userDocs = new ArrayList<>(); - - userDocs.addAll(result.getDocuments()); - - for (DocumentMetadata doc: userDocs) { - DocumentVersionMetadata md = doc.getLatestVersionMetadata(); - - if (docName.equals(md.getName())) { - map.put("doc_id", doc.getId()); - map.put("version_id", md.getId()); - } - } - } - - return map; - } - - private static String getDownloadDocUrl(AmazonWorkDocs workDocs, String docId, String versionId, String doc) { - GetDocumentVersionRequest request = new GetDocumentVersionRequest(); - request.setDocumentId(docId); - request.setVersionId(versionId); - request.setFields("SOURCE"); - GetDocumentVersionResult result = workDocs.getDocumentVersion(request); - - return result.getMetadata().getSource().get(DocumentSourceType.ORIGINAL.name()); - } - - public static void main(String[] args) throws Exception { - // Create default client - AmazonWorkDocs workDocs = AmazonWorkDocsClientBuilder.defaultClient(); - - // Set to the OrganizationId of your WorkDocs site. - String orgId = "d-123456789c"; - - // Set to the email address of a real user - String userEmail = "nobody@amazon.com"; - - // Set to the name of the doc - String workdocsName = "test.txt"; - - // Set to the full path to the doc - String saveDocFullName; - if(System.getProperty("os.name").contains("win")) { - saveDocFullName = "C:\\test.txt"; - } else { - saveDocFullName = "/tmp/test.txt"; - } - - Map map = getDocInfo(workDocs, orgId, userEmail, workdocsName); - - if (map.isEmpty()) { - System.out.println("Could not get info about workdoc " + workdocsName); - return; - } - - String doc_id = map.get("doc_id"); - String version_id = map.get("version_id"); - - if ("".equals(doc_id) || "".equals(version_id)) { - System.out.println("Could not get info about workdoc " + workdocsName); - return; - } - - String downloadUrl = getDownloadDocUrl(workDocs, doc_id, version_id, workdocsName); - - GetDocumentVersionRequest request = new GetDocumentVersionRequest(); - request.setDocumentId(doc_id); - request.setVersionId(version_id); - request.setFields("SOURCE"); - - // Get doc from provided URL - URL doc_url = new URL(downloadUrl); - URLConnection url_conn = doc_url.openConnection(); - - final Path destination = Paths.get(saveDocFullName); - - try (final InputStream in = url_conn.getInputStream();) { - Files.copy(in, destination); - System.out.println("Downloaded " + workdocsName + " to: "+ saveDocFullName); - } - } +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package aws.example.workdocs; + +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.amazonaws.services.workdocs.AmazonWorkDocs; +import com.amazonaws.services.workdocs.AmazonWorkDocsClientBuilder; +import com.amazonaws.services.workdocs.model.DescribeFolderContentsRequest; +import com.amazonaws.services.workdocs.model.DescribeFolderContentsResult; +import com.amazonaws.services.workdocs.model.DescribeUsersRequest; +import com.amazonaws.services.workdocs.model.DescribeUsersResult; +import com.amazonaws.services.workdocs.model.DocumentMetadata; +import com.amazonaws.services.workdocs.model.DocumentSourceType; +import com.amazonaws.services.workdocs.model.DocumentVersionMetadata; +import com.amazonaws.services.workdocs.model.GetDocumentVersionRequest; +import com.amazonaws.services.workdocs.model.GetDocumentVersionResult; +import com.amazonaws.services.workdocs.model.InitiateDocumentVersionUploadRequest; +import com.amazonaws.services.workdocs.model.InitiateDocumentVersionUploadResult; +import com.amazonaws.services.workdocs.model.UploadMetadata; +import com.amazonaws.services.workdocs.model.User; + +public class DownloadUserDoc { + + private static String getUserFolder(AmazonWorkDocs workDocs, String orgId, String user) throws Exception { + String user_folder = ""; + List wdUsers = new ArrayList<>(); + DescribeUsersRequest request = new DescribeUsersRequest(); + + request.setOrganizationId(orgId); + + String marker = null; + + do { + request.setMarker(marker); + request.setQuery(user); + + DescribeUsersResult result = workDocs.describeUsers(request); + + wdUsers.addAll(result.getUsers()); + marker = result.getMarker(); + } while (marker != null); + + // We should only have one user in this list + int num_users = wdUsers.size(); + + if (num_users != 1) { + System.out.println("WARNING!!!"); + System.out.println("Found " + num_users + " but expected to find only one"); + } + + for (User wdUser : wdUsers) { + // DescribeFolderContentsRequest dfc_request = new + // DescribeFolderContentsRequest(); + user_folder = wdUser.getRootFolderId(); + } + + return user_folder; + } + + private static Map getDocInfo(AmazonWorkDocs workDocs, String orgId, String user, String docName) + throws Exception { + // Java code: + // http://docs.aws.amazon.com/workdocs/latest/developerguide/download-documents.html + Map map = new HashMap(); + String folderId = getUserFolder(workDocs, orgId, user); + + if ("".equals(folderId)) { + System.out.println("Could not get user folder"); + } else { + + DescribeFolderContentsRequest dfc_request = new DescribeFolderContentsRequest(); + dfc_request.setFolderId(folderId); + + DescribeFolderContentsResult result = workDocs.describeFolderContents(dfc_request); + + List userDocs = new ArrayList<>(); + + userDocs.addAll(result.getDocuments()); + + for (DocumentMetadata doc : userDocs) { + DocumentVersionMetadata md = doc.getLatestVersionMetadata(); + + if (docName.equals(md.getName())) { + map.put("doc_id", doc.getId()); + map.put("version_id", md.getId()); + } + } + } + + return map; + } + + private static String getDownloadDocUrl(AmazonWorkDocs workDocs, String docId, String versionId, String doc) { + GetDocumentVersionRequest request = new GetDocumentVersionRequest(); + request.setDocumentId(docId); + request.setVersionId(versionId); + request.setFields("SOURCE"); + GetDocumentVersionResult result = workDocs.getDocumentVersion(request); + + return result.getMetadata().getSource().get(DocumentSourceType.ORIGINAL.name()); + } + + public static void main(String[] args) throws Exception { + // Create default client + AmazonWorkDocs workDocs = AmazonWorkDocsClientBuilder.defaultClient(); + + // Set to the OrganizationId of your WorkDocs site. + String orgId = "d-123456789c"; + + // Set to the email address of a real user + String userEmail = "nobody@amazon.com"; + + // Set to the name of the doc + String workdocsName = "test.txt"; + + // Set to the full path to the doc + String saveDocFullName; + if (System.getProperty("os.name").contains("win")) { + saveDocFullName = "C:\\test.txt"; + } else { + saveDocFullName = "/tmp/test.txt"; + } + + Map map = getDocInfo(workDocs, orgId, userEmail, workdocsName); + + if (map.isEmpty()) { + System.out.println("Could not get info about workdoc " + workdocsName); + return; + } + + String doc_id = map.get("doc_id"); + String version_id = map.get("version_id"); + + if ("".equals(doc_id) || "".equals(version_id)) { + System.out.println("Could not get info about workdoc " + workdocsName); + return; + } + + String downloadUrl = getDownloadDocUrl(workDocs, doc_id, version_id, workdocsName); + + GetDocumentVersionRequest request = new GetDocumentVersionRequest(); + request.setDocumentId(doc_id); + request.setVersionId(version_id); + request.setFields("SOURCE"); + + // Get doc from provided URL + URL doc_url = new URL(downloadUrl); + URLConnection url_conn = doc_url.openConnection(); + + final Path destination = Paths.get(saveDocFullName); + + try (final InputStream in = url_conn.getInputStream();) { + Files.copy(in, destination); + System.out.println("Downloaded " + workdocsName + " to: " + saveDocFullName); + } + } } \ No newline at end of file diff --git a/java/example_code/workdocs/list_user_docs.java b/java/example_code/workdocs/list_user_docs.java index 4230f237b57..a5ffaba8721 100644 --- a/java/example_code/workdocs/list_user_docs.java +++ b/java/example_code/workdocs/list_user_docs.java @@ -1,85 +1,82 @@ -//snippet-sourcedescription:[list_user_docs.java demonstrates how to list user docs for the current user.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[workdocs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[Doug-AWS] -import java.util.ArrayList; -import java.util.List; - -import com.amazonaws.services.workdocs.AmazonWorkDocs; -import com.amazonaws.services.workdocs.AmazonWorkDocsClientBuilder; -import com.amazonaws.services.workdocs.model.DescribeFolderContentsRequest; -import com.amazonaws.services.workdocs.model.DescribeFolderContentsResult; -import com.amazonaws.services.workdocs.model.DescribeUsersRequest; -import com.amazonaws.services.workdocs.model.DescribeUsersResult; -import com.amazonaws.services.workdocs.model.DocumentMetadata; -import com.amazonaws.services.workdocs.model.DocumentVersionMetadata; -import com.amazonaws.services.workdocs.model.User; - -public class list_user_docs { - - private static String get_user_folder(AmazonWorkDocs workDocs, String orgId, String user) throws Exception { - List wdUsers = new ArrayList<>(); - DescribeUsersRequest request = new DescribeUsersRequest(); - - request.setOrganizationId(orgId); - - String marker = null; - - do { - request.setMarker(marker); - request.setQuery(user); - - DescribeUsersResult result = workDocs.describeUsers(request); - - wdUsers.addAll(result.getUsers()); - marker = result.getMarker(); - } while (marker != null); - - for (User wdUser : wdUsers) { - DescribeFolderContentsRequest dfc_request = new DescribeFolderContentsRequest(); - return wdUser.getRootFolderId(); - } - - return ""; - } - - public static void main(String[] args) throws Exception { - // Based on WorkDocs dev guide code at http://docs.aws.amazon.com/workdocs/latest/developerguide/connect-workdocs-role.html - - // Use the default client. Look at Window, Preferences, AWS Toolkit to see the values - AmazonWorkDocs workDocs = AmazonWorkDocsClientBuilder.defaultClient(); - - // Set to the OrganizationId of your WorkDocs site. - String orgId = "d-123456789c"; - - // Set to the email address of a real user - String userEmail = "nobody@amazon.com"; - - String folderId = get_user_folder(workDocs, orgId, userEmail); - - DescribeFolderContentsRequest dfc_request = new DescribeFolderContentsRequest(); - dfc_request.setFolderId(folderId); - - DescribeFolderContentsResult result = workDocs.describeFolderContents(dfc_request); - - List userDocs = new ArrayList<>(); - - userDocs.addAll(result.getDocuments()); - - System.out.println("Docs for user " + userEmail + ":"); - System.out.println(""); - - for (DocumentMetadata doc: userDocs) { - DocumentVersionMetadata md = doc.getLatestVersionMetadata(); - System.out.println("Name: " + md.getName()); - System.out.println("Size (bytes): " + md.getSize()); - System.out.println("Last modified: " + md.getModifiedTimestamp()); - System.out.println("Doc ID: " + doc.getId()); - System.out.println(""); - } - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import java.util.ArrayList; +import java.util.List; + +import com.amazonaws.services.workdocs.AmazonWorkDocs; +import com.amazonaws.services.workdocs.AmazonWorkDocsClientBuilder; +import com.amazonaws.services.workdocs.model.DescribeFolderContentsRequest; +import com.amazonaws.services.workdocs.model.DescribeFolderContentsResult; +import com.amazonaws.services.workdocs.model.DescribeUsersRequest; +import com.amazonaws.services.workdocs.model.DescribeUsersResult; +import com.amazonaws.services.workdocs.model.DocumentMetadata; +import com.amazonaws.services.workdocs.model.DocumentVersionMetadata; +import com.amazonaws.services.workdocs.model.User; + +public class list_user_docs { + + private static String get_user_folder(AmazonWorkDocs workDocs, String orgId, String user) throws Exception { + List wdUsers = new ArrayList<>(); + DescribeUsersRequest request = new DescribeUsersRequest(); + + request.setOrganizationId(orgId); + + String marker = null; + + do { + request.setMarker(marker); + request.setQuery(user); + + DescribeUsersResult result = workDocs.describeUsers(request); + + wdUsers.addAll(result.getUsers()); + marker = result.getMarker(); + } while (marker != null); + + for (User wdUser : wdUsers) { + DescribeFolderContentsRequest dfc_request = new DescribeFolderContentsRequest(); + return wdUser.getRootFolderId(); + } + + return ""; + } + + public static void main(String[] args) throws Exception { + // Based on WorkDocs dev guide code at + // http://docs.aws.amazon.com/workdocs/latest/developerguide/connect-workdocs-role.html + + // Use the default client. Look at Window, Preferences, AWS Toolkit to see the + // values + AmazonWorkDocs workDocs = AmazonWorkDocsClientBuilder.defaultClient(); + + // Set to the OrganizationId of your WorkDocs site. + String orgId = "d-123456789c"; + + // Set to the email address of a real user + String userEmail = "nobody@amazon.com"; + + String folderId = get_user_folder(workDocs, orgId, userEmail); + + DescribeFolderContentsRequest dfc_request = new DescribeFolderContentsRequest(); + dfc_request.setFolderId(folderId); + + DescribeFolderContentsResult result = workDocs.describeFolderContents(dfc_request); + + List userDocs = new ArrayList<>(); + + userDocs.addAll(result.getDocuments()); + + System.out.println("Docs for user " + userEmail + ":"); + System.out.println(""); + + for (DocumentMetadata doc : userDocs) { + DocumentVersionMetadata md = doc.getLatestVersionMetadata(); + System.out.println("Name: " + md.getName()); + System.out.println("Size (bytes): " + md.getSize()); + System.out.println("Last modified: " + md.getModifiedTimestamp()); + System.out.println("Doc ID: " + doc.getId()); + System.out.println(""); + } + } +} diff --git a/java/example_code/workdocs/list_users.java b/java/example_code/workdocs/list_users.java index 9988c4c555d..d38f4299d3a 100644 --- a/java/example_code/workdocs/list_users.java +++ b/java/example_code/workdocs/list_users.java @@ -1,51 +1,48 @@ -//snippet-sourcedescription:[list_users.java demonstrates how to list the users for an organization.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[workdocs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[Doug-AWS] -import java.util.ArrayList; -import java.util.List; - -import com.amazonaws.services.workdocs.AmazonWorkDocs; -import com.amazonaws.services.workdocs.AmazonWorkDocsClientBuilder; -import com.amazonaws.services.workdocs.model.DescribeUsersRequest; -import com.amazonaws.services.workdocs.model.DescribeUsersResult; -import com.amazonaws.services.workdocs.model.User; - -public class list_users { - - public static void main(String[] args) { - // Based on WorkDocs dev guide code at http://docs.aws.amazon.com/workdocs/latest/developerguide/connect-workdocs-iam.html - - // Use the default client. Look at Window, Preferences, AWS Toolkit to see the values - AmazonWorkDocs workDocs = AmazonWorkDocsClientBuilder.defaultClient(); - - List wdUsers = new ArrayList<>(); - DescribeUsersRequest request = new DescribeUsersRequest(); - - // Set to the OrganizationId of your WorkDocs site. - request.setOrganizationId("d-123456789c"); - - String marker = null; - - do { - request.setMarker(marker); - - System.out.println("List of users:"); - - DescribeUsersResult result = workDocs.describeUsers(request); - - wdUsers.addAll(result.getUsers()); - marker = result.getMarker(); - } while (marker != null); - - for (User wdUser : wdUsers) { - System.out.printf("Firstname:%s | Lastname:%s | Email:%s | root-folder-id:%s\n", - wdUser.getGivenName(), wdUser.getSurname(), wdUser.getEmailAddress(), - wdUser.getRootFolderId()); - } - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import java.util.ArrayList; +import java.util.List; + +import com.amazonaws.services.workdocs.AmazonWorkDocs; +import com.amazonaws.services.workdocs.AmazonWorkDocsClientBuilder; +import com.amazonaws.services.workdocs.model.DescribeUsersRequest; +import com.amazonaws.services.workdocs.model.DescribeUsersResult; +import com.amazonaws.services.workdocs.model.User; + +public class list_users { + + public static void main(String[] args) { + // Based on WorkDocs dev guide code at + // http://docs.aws.amazon.com/workdocs/latest/developerguide/connect-workdocs-iam.html + + // Use the default client. Look at Window, Preferences, AWS Toolkit to see the + // values + AmazonWorkDocs workDocs = AmazonWorkDocsClientBuilder.defaultClient(); + + List wdUsers = new ArrayList<>(); + DescribeUsersRequest request = new DescribeUsersRequest(); + + // Set to the OrganizationId of your WorkDocs site. + request.setOrganizationId("d-123456789c"); + + String marker = null; + + do { + request.setMarker(marker); + + System.out.println("List of users:"); + + DescribeUsersResult result = workDocs.describeUsers(request); + + wdUsers.addAll(result.getUsers()); + marker = result.getMarker(); + } while (marker != null); + + for (User wdUser : wdUsers) { + System.out.printf("Firstname:%s | Lastname:%s | Email:%s | root-folder-id:%s\n", + wdUser.getGivenName(), wdUser.getSurname(), wdUser.getEmailAddress(), + wdUser.getRootFolderId()); + } + } +} diff --git a/java/example_code/workdocs/upload_user_doc.java b/java/example_code/workdocs/upload_user_doc.java index b9901088221..c8c43f159c8 100644 --- a/java/example_code/workdocs/upload_user_doc.java +++ b/java/example_code/workdocs/upload_user_doc.java @@ -1,166 +1,165 @@ -//snippet-sourcedescription:[upload_user_doc.java demonstrates how to upload a document to AWS Workdocs.] -//snippet-keyword:[Java] -//snippet-sourcesyntax:[java] -//snippet-keyword:[Code Sample] -//snippet-service:[workdocs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[Doug-AWS] -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Unmarshaller; - -import com.amazonaws.services.workdocs.AmazonWorkDocs; -import com.amazonaws.services.workdocs.AmazonWorkDocsClientBuilder; -import com.amazonaws.services.workdocs.model.DescribeFolderContentsRequest; -import com.amazonaws.services.workdocs.model.DescribeUsersRequest; -import com.amazonaws.services.workdocs.model.DescribeUsersResult; -import com.amazonaws.services.workdocs.model.DocumentVersionStatus; -import com.amazonaws.services.workdocs.model.InitiateDocumentVersionUploadRequest; -import com.amazonaws.services.workdocs.model.InitiateDocumentVersionUploadResult; -import com.amazonaws.services.workdocs.model.UpdateDocumentVersionRequest; -import com.amazonaws.services.workdocs.model.UploadMetadata; -import com.amazonaws.services.workdocs.model.User; - -public class upload_user_doc { - - private static String get_user_folder(AmazonWorkDocs workDocs, String orgId, String user) throws Exception { - List wdUsers = new ArrayList<>(); - DescribeUsersRequest request = new DescribeUsersRequest(); - - request.setOrganizationId(orgId); - - String marker = null; - - do { - request.setMarker(marker); - request.setQuery(user); - - DescribeUsersResult result = workDocs.describeUsers(request); - - wdUsers.addAll(result.getUsers()); - marker = result.getMarker(); - } while (marker != null); - - for (User wdUser : wdUsers) { - DescribeFolderContentsRequest dfc_request = new DescribeFolderContentsRequest(); - return wdUser.getRootFolderId(); - } - - return ""; - } - - private static Map get_doc_info(AmazonWorkDocs workDocs, String orgId, String user, String doc) throws Exception { - String folderId = get_user_folder(workDocs, orgId, user); - - InitiateDocumentVersionUploadRequest request = new InitiateDocumentVersionUploadRequest(); - request.setParentFolderId(folderId); - request.setName(doc); - request.setContentType("application/octet-stream"); // MISSING SEMI-COLON!!! - - InitiateDocumentVersionUploadResult result = workDocs.initiateDocumentVersionUpload(request); - - UploadMetadata uploadMetadata = result.getUploadMetadata(); - - Map map = new HashMap(); - - map.put("doc_id", result.getMetadata().getId()); - map.put("version_id", result.getMetadata().getLatestVersionMetadata().getId()); - map.put("upload_url", uploadMetadata.getUploadUrl()); - - return map; - } - - private static int start_doc_upload(String uploadUrl, String doc) throws Exception { - URL url = new URL(uploadUrl); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setDoOutput(true); - connection.setRequestMethod("PUT"); - // Content-Type supplied here should match with the Content-Type set - // in the InitiateDocumentVersionUpload request. - connection.setRequestProperty("Content-Type","application/octet-stream"); - connection.setRequestProperty("x-amz-server-side-encryption", "AES256"); - File file = new File(doc); - FileInputStream fileInputStream = new FileInputStream(file); - OutputStream outputStream = connection.getOutputStream(); - com.amazonaws.util.IOUtils.copy(fileInputStream, outputStream); - - // Very misleading. Getting a 200 only means the call succeeded, not that the copy worked. - return connection.getResponseCode(); // int where 200 == success - } - - private static void complete_upload(AmazonWorkDocs workDocs, String doc_id, String version_id) throws Exception { - UpdateDocumentVersionRequest request = new UpdateDocumentVersionRequest(); - request.setDocumentId(doc_id); - request.setVersionId(version_id); - request.setVersionStatus(DocumentVersionStatus.ACTIVE); - workDocs.updateDocumentVersion(request); - } - - public static void main(String[] args) throws Exception { - // Based on WorkDocs dev guide code at http://docs.aws.amazon.com/workdocs/latest/developerguide/upload-documents.html - - // Use the default client. Look at Window, Preferences, AWS Toolkit to see the values - AmazonWorkDocs workDocs = AmazonWorkDocsClientBuilder.defaultClient(); - - // Set to the OrganizationId of your WorkDocs site. - String orgId = "d-123456789c"; - - // Set to the email address of a real user - String userEmail = "nobody@amazon.com"; - - // Set to the name of the doc - String docName = "test.txt"; - - // Set to the full path to the doc - String doc = "C:\\test.txt"; - - String doc_id, version_id, uploadUrl = ""; - int rc = 0; - - try { - Map map = get_doc_info(workDocs, orgId, userEmail, docName); - - doc_id = map.get("doc_id"); - version_id = map.get("version_id"); - uploadUrl = map.get("upload_url"); - } catch (Exception ex) { - System.out.println("Caught exception " + ex.getMessage() + " calling start_doc_upload"); - return; - } - - try { - rc = start_doc_upload(uploadUrl, doc); - - if (rc != 200) { - System.out.println("Error code uploading: " + rc); - } else { - System.out.println("Success uploading doc " + docName); - } - } catch (Exception ex) { - System.out.println("Caught exception " + ex.getMessage() + " calling finish_doc_upload"); - return; - } - - System.out.println(""); - - try { - complete_upload(workDocs, doc_id, version_id); - } catch (Exception ex) { - System.out.println("Caught exception " + ex.getMessage() + " calling complete_upload"); - return; - } - - System.out.println(""); - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; + +import com.amazonaws.services.workdocs.AmazonWorkDocs; +import com.amazonaws.services.workdocs.AmazonWorkDocsClientBuilder; +import com.amazonaws.services.workdocs.model.DescribeFolderContentsRequest; +import com.amazonaws.services.workdocs.model.DescribeUsersRequest; +import com.amazonaws.services.workdocs.model.DescribeUsersResult; +import com.amazonaws.services.workdocs.model.DocumentVersionStatus; +import com.amazonaws.services.workdocs.model.InitiateDocumentVersionUploadRequest; +import com.amazonaws.services.workdocs.model.InitiateDocumentVersionUploadResult; +import com.amazonaws.services.workdocs.model.UpdateDocumentVersionRequest; +import com.amazonaws.services.workdocs.model.UploadMetadata; +import com.amazonaws.services.workdocs.model.User; + +public class upload_user_doc { + + private static String get_user_folder(AmazonWorkDocs workDocs, String orgId, String user) throws Exception { + List wdUsers = new ArrayList<>(); + DescribeUsersRequest request = new DescribeUsersRequest(); + + request.setOrganizationId(orgId); + + String marker = null; + + do { + request.setMarker(marker); + request.setQuery(user); + + DescribeUsersResult result = workDocs.describeUsers(request); + + wdUsers.addAll(result.getUsers()); + marker = result.getMarker(); + } while (marker != null); + + for (User wdUser : wdUsers) { + DescribeFolderContentsRequest dfc_request = new DescribeFolderContentsRequest(); + return wdUser.getRootFolderId(); + } + + return ""; + } + + private static Map get_doc_info(AmazonWorkDocs workDocs, String orgId, String user, String doc) + throws Exception { + String folderId = get_user_folder(workDocs, orgId, user); + + InitiateDocumentVersionUploadRequest request = new InitiateDocumentVersionUploadRequest(); + request.setParentFolderId(folderId); + request.setName(doc); + request.setContentType("application/octet-stream"); // MISSING SEMI-COLON!!! + + InitiateDocumentVersionUploadResult result = workDocs.initiateDocumentVersionUpload(request); + + UploadMetadata uploadMetadata = result.getUploadMetadata(); + + Map map = new HashMap(); + + map.put("doc_id", result.getMetadata().getId()); + map.put("version_id", result.getMetadata().getLatestVersionMetadata().getId()); + map.put("upload_url", uploadMetadata.getUploadUrl()); + + return map; + } + + private static int start_doc_upload(String uploadUrl, String doc) throws Exception { + URL url = new URL(uploadUrl); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setDoOutput(true); + connection.setRequestMethod("PUT"); + // Content-Type supplied here should match with the Content-Type set + // in the InitiateDocumentVersionUpload request. + connection.setRequestProperty("Content-Type", "application/octet-stream"); + connection.setRequestProperty("x-amz-server-side-encryption", "AES256"); + File file = new File(doc); + FileInputStream fileInputStream = new FileInputStream(file); + OutputStream outputStream = connection.getOutputStream(); + com.amazonaws.util.IOUtils.copy(fileInputStream, outputStream); + + // Very misleading. Getting a 200 only means the call succeeded, not that the + // copy worked. + return connection.getResponseCode(); // int where 200 == success + } + + private static void complete_upload(AmazonWorkDocs workDocs, String doc_id, String version_id) throws Exception { + UpdateDocumentVersionRequest request = new UpdateDocumentVersionRequest(); + request.setDocumentId(doc_id); + request.setVersionId(version_id); + request.setVersionStatus(DocumentVersionStatus.ACTIVE); + workDocs.updateDocumentVersion(request); + } + + public static void main(String[] args) throws Exception { + // Based on WorkDocs dev guide code at + // http://docs.aws.amazon.com/workdocs/latest/developerguide/upload-documents.html + + // Use the default client. Look at Window, Preferences, AWS Toolkit to see the + // values + AmazonWorkDocs workDocs = AmazonWorkDocsClientBuilder.defaultClient(); + + // Set to the OrganizationId of your WorkDocs site. + String orgId = "d-123456789c"; + + // Set to the email address of a real user + String userEmail = "nobody@amazon.com"; + + // Set to the name of the doc + String docName = "test.txt"; + + // Set to the full path to the doc + String doc = "C:\\test.txt"; + + String doc_id, version_id, uploadUrl = ""; + int rc = 0; + + try { + Map map = get_doc_info(workDocs, orgId, userEmail, docName); + + doc_id = map.get("doc_id"); + version_id = map.get("version_id"); + uploadUrl = map.get("upload_url"); + } catch (Exception ex) { + System.out.println("Caught exception " + ex.getMessage() + " calling start_doc_upload"); + return; + } + + try { + rc = start_doc_upload(uploadUrl, doc); + + if (rc != 200) { + System.out.println("Error code uploading: " + rc); + } else { + System.out.println("Success uploading doc " + docName); + } + } catch (Exception ex) { + System.out.println("Caught exception " + ex.getMessage() + " calling finish_doc_upload"); + return; + } + + System.out.println(""); + + try { + complete_upload(workDocs, doc_id, version_id); + } catch (Exception ex) { + System.out.println("Caught exception " + ex.getMessage() + " calling complete_upload"); + return; + } + + System.out.println(""); + } +} diff --git a/javascript/example_code/athena/index.js b/javascript/example_code/athena/index.js index 82f9f2443de..fc6bad6459c 100644 --- a/javascript/example_code/athena/index.js +++ b/javascript/example_code/athena/index.js @@ -1,147 +1,161 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[index.ts demonstrates how to query for information from Amazon Athena.] -// snippet-service:[athena] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Athena] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // For more information about Amazon Athena, see the user guide and API reference at: // https://docs.aws.amazon.com/athena // snippet-start:[athena.JavaScript.index.complete] -const AWS = require('aws-sdk') -const Queue = require('async.queue') -const _ = require('lodash') - -const ATHENA_DB = 'default' -const ATHENA_OUTPUT_LOCATION = 's3://my-bucket/athena-temp/' -const RESULT_SIZE = 1000 -const POLL_INTERVAL = 1000 - -let creds = new AWS.SharedIniFileCredentials({filename:'/Users/username/.aws/credentials', profile: 'username'}); +const AWS = require("aws-sdk"); +const Queue = require("async.queue"); +const _ = require("lodash"); + +const ATHENA_DB = "default"; +const ATHENA_OUTPUT_LOCATION = "s3://my-bucket/athena-temp/"; +const RESULT_SIZE = 1000; +const POLL_INTERVAL = 1000; + +let creds = new AWS.SharedIniFileCredentials({ + filename: "/Users/username/.aws/credentials", + profile: "username", +}); AWS.config.credentials = creds; -let client = new AWS.Athena({region: 'us-east-1'}) +let client = new AWS.Athena({ region: "us-east-1" }); /* Create an async queue to handle polling for query results */ let q = Queue((id, cb) => { - startPolling(id) - .then((data) => { return cb(null, data) }) - .catch((err) => { console.log('Failed to poll query: ', err); return cb(err) }) + startPolling(id) + .then((data) => { + return cb(null, data); + }) + .catch((err) => { + console.log("Failed to poll query: ", err); + return cb(err); + }); }, 5); /* Make a SQL query and display results */ makeQuery("SELECT * FROM cloudtrail_logs limit 10;") -.then((data) => { - console.log('Row Count: ', data.length) - console.log('DATA: ', data) -}) -.catch((e) => { console.log('ERROR: ', e) }) - + .then((data) => { + console.log("Row Count: ", data.length); + console.log("DATA: ", data); + }) + .catch((e) => { + console.log("ERROR: ", e); + }); function makeQuery(sql) { - return new Promise((resolve, reject) => { - let params = { - QueryString: sql, - ResultConfiguration: { OutputLocation: ATHENA_OUTPUT_LOCATION }, - QueryExecutionContext: { Database: ATHENA_DB } - } - - /* Make API call to start the query execution */ - client.startQueryExecution(params, (err, results) => { - if (err) return reject(err) - /* If successful, get the query ID and queue it for polling */ - q.push(results.QueryExecutionId, (err, qid) => { - if (err) return reject(err) - /* Once query completed executing, get and process results */ - return buildResults(qid) - .then((data) => { return resolve(data) }) - .catch((err) => { return reject(err) }) - }) - }) - }) + return new Promise((resolve, reject) => { + let params = { + QueryString: sql, + ResultConfiguration: { OutputLocation: ATHENA_OUTPUT_LOCATION }, + QueryExecutionContext: { Database: ATHENA_DB }, + }; + + /* Make API call to start the query execution */ + client.startQueryExecution(params, (err, results) => { + if (err) return reject(err); + /* If successful, get the query ID and queue it for polling */ + q.push(results.QueryExecutionId, (err, qid) => { + if (err) return reject(err); + /* Once query completed executing, get and process results */ + return buildResults(qid) + .then((data) => { + return resolve(data); + }) + .catch((err) => { + return reject(err); + }); + }); + }); + }); } function buildResults(query_id, max, page) { - let max_num_results = max ? max : RESULT_SIZE - let page_token = page ? page : undefined - return new Promise((resolve, reject) => { - let params = { - QueryExecutionId: query_id, - MaxResults: max_num_results, - NextToken: page_token - } - - let dataBlob = [] - go(params) - - /* Get results and iterate through all pages */ - function go(param) { - getResults(param) - .then((res) => { - dataBlob = _.concat(dataBlob, res.list) - if (res.next) { - param.NextToken = res.next - return go(param) - } else return resolve(dataBlob) - }).catch((err) => { return reject(err) }) - } - - /* Process results merging column names and values into a JS object */ - function getResults() { - return new Promise((resolve, reject) => { - client.getQueryResults(params, (err, data) => { - if (err) return reject(err) - var list = [] - let header = buildHeader(data.ResultSet.ResultSetMetadata.ColumnInfo) - let top_row = _.map(_.head(data.ResultSet.Rows).Data, (n) => { return n.VarCharValue }) - let resultSet = (_.difference(header, top_row).length > 0) ? - data.ResultSet.Rows : - _.drop(data.ResultSet.Rows) - resultSet.forEach((item) => { - list.push(_.zipObject(header, _.map(item.Data, (n) => {return n.VarCharValue }))) - }) - return resolve({next: ('NextToken' in data) ? data.NextToken : undefined, list: list}) + let max_num_results = max ? max : RESULT_SIZE; + let page_token = page ? page : undefined; + return new Promise((resolve, reject) => { + let params = { + QueryExecutionId: query_id, + MaxResults: max_num_results, + NextToken: page_token, + }; + + let dataBlob = []; + go(params); + + /* Get results and iterate through all pages */ + function go(param) { + getResults(param) + .then((res) => { + dataBlob = _.concat(dataBlob, res.list); + if (res.next) { + param.NextToken = res.next; + return go(param); + } else return resolve(dataBlob); + }) + .catch((err) => { + return reject(err); + }); + } + + /* Process results merging column names and values into a JS object */ + function getResults() { + return new Promise((resolve, reject) => { + client.getQueryResults(params, (err, data) => { + if (err) return reject(err); + var list = []; + let header = buildHeader(data.ResultSet.ResultSetMetadata.ColumnInfo); + let top_row = _.map(_.head(data.ResultSet.Rows).Data, (n) => { + return n.VarCharValue; + }); + let resultSet = + _.difference(header, top_row).length > 0 + ? data.ResultSet.Rows + : _.drop(data.ResultSet.Rows); + resultSet.forEach((item) => { + list.push( + _.zipObject( + header, + _.map(item.Data, (n) => { + return n.VarCharValue; }) - }) - } - }) + ) + ); + }); + return resolve({ + next: "NextToken" in data ? data.NextToken : undefined, + list: list, + }); + }); + }); + } + }); } function startPolling(id) { - return new Promise((resolve, reject) => { - function poll(id) { - client.getQueryExecution({QueryExecutionId: id}, (err, data) => { - if (err) return reject(err) - if (data.QueryExecution.Status.State === 'SUCCEEDED') return resolve(id) - else if (['FAILED', 'CANCELLED'].includes(data.QueryExecution.Status.State)) return reject(new Error(`Query ${data.QueryExecution.Status.State}`)) - else { setTimeout(poll, POLL_INTERVAL, id) } - }) + return new Promise((resolve, reject) => { + function poll(id) { + client.getQueryExecution({ QueryExecutionId: id }, (err, data) => { + if (err) return reject(err); + if (data.QueryExecution.Status.State === "SUCCEEDED") + return resolve(id); + else if ( + ["FAILED", "CANCELLED"].includes(data.QueryExecution.Status.State) + ) + return reject(new Error(`Query ${data.QueryExecution.Status.State}`)); + else { + setTimeout(poll, POLL_INTERVAL, id); } - poll(id) - }) + }); + } + poll(id); + }); } function buildHeader(columns) { - return _.map(columns, (i) => { return i.Name }) + return _.map(columns, (i) => { + return i.Name; + }); } // snippet-end:[athena.JavaScript.index.complete] diff --git a/javascript/example_code/cdk/widgets.js b/javascript/example_code/cdk/widgets.js index 34012f2ac20..18170c513ea 100644 --- a/javascript/example_code/cdk/widgets.js +++ b/javascript/example_code/cdk/widgets.js @@ -1,20 +1,6 @@ -//snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -//snippet-comment:[This should be in the resources/ directory] -//snippet-comment:[and only works with my_widget_service.ts in the bin/ directory] -//snippet-comment:[and widget_service.ts in the lib/ directory.] -//snippet-sourceauthor:[Doug-AWS] -//snippet-sourcedescription:[Lambda function to handle GET, POST, and DELETE.] -//snippet-keyword:[CDK V0.24.1] -//snippet-keyword:[S3.deleteObject function] -//snippet-keyword:[S3.getObject function] -//snippet-keyword:[S3.listObjectsV2 function] -//snippet-keyword:[S3.putObject function] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-service:[cdk] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-2-8] -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // // This file is 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 @@ -25,15 +11,15 @@ // This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. -//snippet-start:[cdk.typescript.widgets] -//snippet-start:[cdk.typescript.widgets.imports] -const AWS = require('aws-sdk'); +// snippet-start:[cdk.typescript.widgets] +// snippet-start:[cdk.typescript.widgets.imports] +const AWS = require("aws-sdk"); const S3 = new AWS.S3(); -//snippet-end:[cdk.typescript.widgets.imports] +// snippet-end:[cdk.typescript.widgets.imports] const bucketName = process.env.BUCKET; -//snippet-start:[cdk.typescript.widgets.exports_main] +// snippet-start:[cdk.typescript.widgets.exports_main] /* This code uses callbacks to handle asynchronous function responses. It currently demonstrates using an async-await pattern. @@ -44,35 +30,42 @@ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/calling-services-asynchronously.html https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html */ -exports.main = async function(event, context) { +exports.main = async function (event, context) { try { var method = event.httpMethod; // Get name, if present - var widgetName = event.path.startsWith('/') ? event.path.substring(1) : event.path; + var widgetName = event.path.startsWith("/") + ? event.path.substring(1) + : event.path; if (method === "GET") { // GET / to get the names of all widgets if (event.path === "/") { const data = await S3.listObjectsV2({ Bucket: bucketName }).promise(); var body = { - widgets: data.Contents.map(function(e) { return e.Key }) + widgets: data.Contents.map(function (e) { + return e.Key; + }), }; return { statusCode: 200, headers: {}, - body: JSON.stringify(body) + body: JSON.stringify(body), }; } if (widgetName) { // GET /name to get info on widget name - const data = await S3.getObject({ Bucket: bucketName, Key: widgetName}).promise(); - var body = data.Body.toString('utf-8'); + const data = await S3.getObject({ + Bucket: bucketName, + Key: widgetName, + }).promise(); + var body = data.Body.toString("utf-8"); return { statusCode: 200, headers: {}, - body: JSON.stringify(body) + body: JSON.stringify(body), }; } } @@ -84,7 +77,7 @@ exports.main = async function(event, context) { return { statusCode: 400, headers: {}, - body: "Widget name missing" + body: "Widget name missing", }; } @@ -92,19 +85,19 @@ exports.main = async function(event, context) { const now = new Date(); var data = widgetName + " created: " + now; - var base64data = new Buffer(data, 'binary'); + var base64data = new Buffer(data, "binary"); await S3.putObject({ Bucket: bucketName, Key: widgetName, Body: base64data, - ContentType: 'application/json' + ContentType: "application/json", }).promise(); return { statusCode: 200, headers: {}, - body: JSON.stringify(event.widgets) + body: JSON.stringify(event.widgets), }; } @@ -115,18 +108,19 @@ exports.main = async function(event, context) { return { statusCode: 400, headers: {}, - body: "Widget name missing" + body: "Widget name missing", }; } await S3.deleteObject({ - Bucket: bucketName, Key: widgetName + Bucket: bucketName, + Key: widgetName, }).promise(); return { statusCode: 200, headers: {}, - body: "Successfully deleted widget " + widgetName + body: "Successfully deleted widget " + widgetName, }; } @@ -134,16 +128,16 @@ exports.main = async function(event, context) { return { statusCode: 400, headers: {}, - body: "We only accept GET, POST, and DELETE, not " + method + body: "We only accept GET, POST, and DELETE, not " + method, }; - } catch(error) { + } catch (error) { var body = error.stack || JSON.stringify(error, null, 2); return { statusCode: 400, headers: {}, - body: body - } + body: body, + }; } -} -//snippet-end:[cdk.typescript.widgets.exports_main] -//snippet-end:[cdk.typescript.widgets] +}; +// snippet-end:[cdk.typescript.widgets.exports_main] +// snippet-end:[cdk.typescript.widgets] diff --git a/javascript/example_code/cdk/widgetsv1.js b/javascript/example_code/cdk/widgetsv1.js index 33206c1d6ca..b75aa1e7b2e 100644 --- a/javascript/example_code/cdk/widgetsv1.js +++ b/javascript/example_code/cdk/widgetsv1.js @@ -1,13 +1,6 @@ -//snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -//snippet-comment:[Contains code for initial version of widgets.js.] -//snippet-sourceauthor:[Doug-AWS] -//snippet-keyword:[CDK V0.24.1] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-service:[cdk] -//snippet-sourcetype:[snippet] -//snippet-sourcedate:[2019-2-8] -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // // This file is 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 @@ -18,7 +11,7 @@ // This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. -//snippet-start:[cdk.typescript.widgets.exports_main_v1] +// snippet-start:[cdk.typescript.widgets.exports_main_v1] /* This code uses callbacks to handle asynchronous function responses. It currently demonstrates using an async-await pattern. @@ -29,12 +22,12 @@ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/calling-services-asynchronously.html https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html */ -const AWS = require('aws-sdk'); +const AWS = require("aws-sdk"); const S3 = new AWS.S3(); const bucketName = process.env.BUCKET; -exports.main = async function(event, context) { +exports.main = async function (event, context) { try { var method = event.httpMethod; @@ -42,12 +35,14 @@ exports.main = async function(event, context) { if (event.path === "/") { const data = await S3.listObjectsV2({ Bucket: bucketName }).promise(); var body = { - widgets: data.Contents.map(function(e) { return e.Key }) + widgets: data.Contents.map(function (e) { + return e.Key; + }), }; return { statusCode: 200, headers: {}, - body: JSON.stringify(body) + body: JSON.stringify(body), }; } } @@ -56,15 +51,15 @@ exports.main = async function(event, context) { return { statusCode: 400, headers: {}, - body: "We only accept GET /" + body: "We only accept GET /", }; - } catch(error) { + } catch (error) { var body = error.stack || JSON.stringify(error, null, 2); return { statusCode: 400, - headers: {}, - body: JSON.stringify(body) - } + headers: {}, + body: JSON.stringify(body), + }; } -} -//snippet-end:[cdk.typescript.widgets.exports_main_v1] +}; +// snippet-end:[cdk.typescript.widgets.exports_main_v1] diff --git a/javascript/example_code/cloudwatch-events/cwe_putevents.js b/javascript/example_code/cloudwatch-events/cwe_putevents.js index 6a310aa9718..572facfd430 100644 --- a/javascript/example_code/cloudwatch-events/cwe_putevents.js +++ b/javascript/example_code/cloudwatch-events/cwe_putevents.js @@ -1,53 +1,30 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[cwe_putevents.js demonstrates how to send custom events to Amazon CloudWatch Events so they can be matched with rules.] -//snippet-service:[cw_events] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon CloudWatch Events] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-sending-events.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-sending-events.html // snippet-start:[cwEvents.JavaScript.cwe.putEvents] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create CloudWatchEvents service object -var cwevents = new AWS.CloudWatchEvents({apiVersion: '2015-10-07'}); +var cwevents = new AWS.CloudWatchEvents({ apiVersion: "2015-10-07" }); var params = { Entries: [ { - Detail: '{ \"key1\": \"value1\", \"key2\": \"value2\" }', - DetailType: 'appRequestSubmitted', - Resources: [ - 'RESOURCE_ARN', - ], - Source: 'com.company.app' - } - ] + Detail: '{ "key1": "value1", "key2": "value2" }', + DetailType: "appRequestSubmitted", + Resources: ["RESOURCE_ARN"], + Source: "com.company.app", + }, + ], }; -cwevents.putEvents(params, function(err, data) { +cwevents.putEvents(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/cloudwatch-events/cwe_putrule.js b/javascript/example_code/cloudwatch-events/cwe_putrule.js index 2e1c000981c..41ec8147045 100644 --- a/javascript/example_code/cloudwatch-events/cwe_putrule.js +++ b/javascript/example_code/cloudwatch-events/cwe_putrule.js @@ -1,47 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[cwe_putrule.js demonstrates how to create or update an Amazon CloudWatch Events rule.] -//snippet-service:[cw_events] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon CloudWatch Events] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-sending-events.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-sending-events.html // snippet-start:[cwEvents.JavaScript.cwe.putRule] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create CloudWatchEvents service object -var cwevents = new AWS.CloudWatchEvents({apiVersion: '2015-10-07'}); +var cwevents = new AWS.CloudWatchEvents({ apiVersion: "2015-10-07" }); var params = { - Name: 'DEMO_EVENT', - RoleArn: 'IAM_ROLE_ARN', - ScheduleExpression: 'rate(5 minutes)', - State: 'ENABLED' + Name: "DEMO_EVENT", + RoleArn: "IAM_ROLE_ARN", + ScheduleExpression: "rate(5 minutes)", + State: "ENABLED", }; -cwevents.putRule(params, function(err, data) { +cwevents.putRule(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/cloudwatch-events/cwe_puttargets.js b/javascript/example_code/cloudwatch-events/cwe_puttargets.js index 525442b0786..726b5325177 100644 --- a/javascript/example_code/cloudwatch-events/cwe_puttargets.js +++ b/javascript/example_code/cloudwatch-events/cwe_puttargets.js @@ -1,50 +1,29 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[cwe_puttargets.js demonstrates how to add or update a target to an Amazon CloudWatch Events rule.] -//snippet-service:[cw_events] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon CloudWatch Events] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-sending-events.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-sending-events.html // snippet-start:[cwEvents.JavaScript.cwe.putTargets] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create CloudWatchEvents service object -var cwevents = new AWS.CloudWatchEvents({apiVersion: '2015-10-07'}); +var cwevents = new AWS.CloudWatchEvents({ apiVersion: "2015-10-07" }); var params = { - Rule: 'DEMO_EVENT', + Rule: "DEMO_EVENT", Targets: [ { - Arn: 'LAMBDA_FUNCTION_ARN', - Id: 'myCloudWatchEventsTarget', - } - ] + Arn: "LAMBDA_FUNCTION_ARN", + Id: "myCloudWatchEventsTarget", + }, + ], }; -cwevents.putTargets(params, function(err, data) { +cwevents.putTargets(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/cloudwatch-logs/cwl_deletesubscriptionfilter.js b/javascript/example_code/cloudwatch-logs/cwl_deletesubscriptionfilter.js index 3d73f05adae..8425ad5fa19 100644 --- a/javascript/example_code/cloudwatch-logs/cwl_deletesubscriptionfilter.js +++ b/javascript/example_code/cloudwatch-logs/cwl_deletesubscriptionfilter.js @@ -1,45 +1,24 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[cwl_deletesubscriptionfilter.js demonstrates how to delete an Amazon CloudWatch Logs filter.] -//snippet-service:[cw_logs] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon CloudWatch Logs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-subscriptions.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-subscriptions.html // snippet-start:[cwLogs.JavaScript.cwl.deleteSubscriptionFilter] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the CloudWatchLogs service object -var cwl = new AWS.CloudWatchLogs({apiVersion: '2014-03-28'}); +var cwl = new AWS.CloudWatchLogs({ apiVersion: "2014-03-28" }); var params = { - filterName: 'FILTER', - logGroupName: 'LOG_GROUP' + filterName: "FILTER", + logGroupName: "LOG_GROUP", }; -cwl.deleteSubscriptionFilter(params, function(err, data) { +cwl.deleteSubscriptionFilter(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/cloudwatch-logs/cwl_describesubscriptionfilters.js b/javascript/example_code/cloudwatch-logs/cwl_describesubscriptionfilters.js index c9613654a4f..8136a81d4e3 100644 --- a/javascript/example_code/cloudwatch-logs/cwl_describesubscriptionfilters.js +++ b/javascript/example_code/cloudwatch-logs/cwl_describesubscriptionfilters.js @@ -1,45 +1,24 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[cwl_describesubscriptionfilters.js demonstrates how to list the subscription filters for an Amazon CloudWatch Logs group.] -//snippet-service:[cs_logs] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon CloudWatch Logs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-subscriptions.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-subscriptions.html // snippet-start:[cwLogs.JavaScript.cwl.describeSubscriptionFilters] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the CloudWatchLogs service object -var cwl = new AWS.CloudWatchLogs({apiVersion: '2014-03-28'}); +var cwl = new AWS.CloudWatchLogs({ apiVersion: "2014-03-28" }); var params = { - logGroupName: 'GROUP_NAME', - limit: 5 + logGroupName: "GROUP_NAME", + limit: 5, }; -cwl.describeSubscriptionFilters(params, function(err, data) { +cwl.describeSubscriptionFilters(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/cloudwatch-logs/cwl_putsubscriptionfilter.js b/javascript/example_code/cloudwatch-logs/cwl_putsubscriptionfilter.js index 043a4b7da6b..6fde6359f93 100644 --- a/javascript/example_code/cloudwatch-logs/cwl_putsubscriptionfilter.js +++ b/javascript/example_code/cloudwatch-logs/cwl_putsubscriptionfilter.js @@ -1,47 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[cwl_putsubscriptionfilter.js demonstrates how to create or update a subscription filter for an Amazon CloudWatch Logs group.] -//snippet-service:[cw_logs] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon CloudWatch Logs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-subscriptions.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-subscriptions.html // snippet-start:[cwLogs.JavaScript.cwl.putSubscriptionFilter] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the CloudWatchLogs service object -var cwl = new AWS.CloudWatchLogs({apiVersion: '2014-03-28'}); +var cwl = new AWS.CloudWatchLogs({ apiVersion: "2014-03-28" }); var params = { - destinationArn: 'LAMBDA_FUNCTION_ARN', - filterName: 'FILTER_NAME', - filterPattern: 'ERROR', - logGroupName: 'LOG_GROUP', + destinationArn: "LAMBDA_FUNCTION_ARN", + filterName: "FILTER_NAME", + filterPattern: "ERROR", + logGroupName: "LOG_GROUP", }; -cwl.putSubscriptionFilter(params, function(err, data) { +cwl.putSubscriptionFilter(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/cloudwatch/cw_deletealarms.js b/javascript/example_code/cloudwatch/cw_deletealarms.js index 2e94cd5009b..1f73f919d03 100644 --- a/javascript/example_code/cloudwatch/cw_deletealarms.js +++ b/javascript/example_code/cloudwatch/cw_deletealarms.js @@ -1,44 +1,23 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[cw_deletealarm.js demonstrates how to delete Amazon CloudWatch alarms.] -//snippet-service:[cloudwatch] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon CloudWatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-creating-alarms.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-creating-alarms.html // snippet-start:[cw.JavaScript.alarms.deleteAlarms] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create CloudWatch service object -var cw = new AWS.CloudWatch({apiVersion: '2010-08-01'}); +var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" }); var params = { - AlarmNames: ['Web_Server_CPU_Utilization'] + AlarmNames: ["Web_Server_CPU_Utilization"], }; -cw.deleteAlarms(params, function(err, data) { +cw.deleteAlarms(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/cloudwatch/cw_describealarms.js b/javascript/example_code/cloudwatch/cw_describealarms.js index 510ad953303..0795f229a96 100644 --- a/javascript/example_code/cloudwatch/cw_describealarms.js +++ b/javascript/example_code/cloudwatch/cw_describealarms.js @@ -1,46 +1,25 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[cw_describealarms.js demonstrates how to retrieve information about Amazon CloudWatch alarms.] -//snippet-service:[cloudwatch] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon CloudWatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-creating-alarms.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-creating-alarms.html // snippet-start:[cw.JavaScript.alarms.describeAlarms] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create CloudWatch service object -var cw = new AWS.CloudWatch({apiVersion: '2010-08-01'}); +var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" }); -cw.describeAlarms({StateValue: 'INSUFFICIENT_DATA'}, function(err, data) { +cw.describeAlarms({ StateValue: "INSUFFICIENT_DATA" }, function (err, data) { if (err) { console.log("Error", err); } else { // List the names of all current alarms in the console data.MetricAlarms.forEach(function (item, index, array) { - console.log(item.AlarmName); + console.log(item.AlarmName); }); } }); diff --git a/javascript/example_code/cloudwatch/cw_disablealarmactions.js b/javascript/example_code/cloudwatch/cw_disablealarmactions.js index 6f2ef2a9ab2..c7480ba5f32 100644 --- a/javascript/example_code/cloudwatch/cw_disablealarmactions.js +++ b/javascript/example_code/cloudwatch/cw_disablealarmactions.js @@ -1,44 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[cw_disablealarmactions.js demonstrates how to disable actions for an Amazon CloudWatch alarm.] -//snippet-service:[cloudwatch] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon CloudWatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-using-alarm-actions.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-using-alarm-actions.html // snippet-start:[cw.JavaScript.alarms.disableAlarmActions] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create CloudWatch service object -var cw = new AWS.CloudWatch({apiVersion: '2010-08-01'}); +var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" }); -cw.disableAlarmActions({AlarmNames: ['Web_Server_CPU_Utilization']}, function(err, data) { - if (err) { - console.log("Error", err); - } else { - console.log("Success", data); +cw.disableAlarmActions( + { AlarmNames: ["Web_Server_CPU_Utilization"] }, + function (err, data) { + if (err) { + console.log("Error", err); + } else { + console.log("Success", data); + } } -}); +); // snippet-end:[cw.JavaScript.alarms.disableAlarmActions] diff --git a/javascript/example_code/cloudwatch/cw_enablealarmactions.js b/javascript/example_code/cloudwatch/cw_enablealarmactions.js index 6f324cbbb8c..eab836a35a9 100644 --- a/javascript/example_code/cloudwatch/cw_enablealarmactions.js +++ b/javascript/example_code/cloudwatch/cw_enablealarmactions.js @@ -1,69 +1,48 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[cw_enablealarmactions.js demonstrates how to enable actions for Amazon CloudWatch alarms.] -//snippet-service:[cloudwatch] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon CloudWatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-using-alarm-actions.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-using-alarm-actions.html // snippet-start:[cw.JavaScript.alarms.enableAlarmActions] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create CloudWatch service object -var cw = new AWS.CloudWatch({apiVersion: '2010-08-01'}); +var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" }); var params = { - AlarmName: 'Web_Server_CPU_Utilization', - ComparisonOperator: 'GreaterThanThreshold', + AlarmName: "Web_Server_CPU_Utilization", + ComparisonOperator: "GreaterThanThreshold", EvaluationPeriods: 1, - MetricName: 'CPUUtilization', - Namespace: 'AWS/EC2', + MetricName: "CPUUtilization", + Namespace: "AWS/EC2", Period: 60, - Statistic: 'Average', + Statistic: "Average", Threshold: 70.0, ActionsEnabled: true, - AlarmActions: ['ACTION_ARN'], - AlarmDescription: 'Alarm when server CPU exceeds 70%', + AlarmActions: ["ACTION_ARN"], + AlarmDescription: "Alarm when server CPU exceeds 70%", Dimensions: [ { - Name: 'InstanceId', - Value: 'INSTANCE_ID' + Name: "InstanceId", + Value: "INSTANCE_ID", }, ], - Unit: 'Percent' + Unit: "Percent", }; -cw.putMetricAlarm(params, function(err, data) { +cw.putMetricAlarm(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Alarm action added", data); var paramsEnableAlarmAction = { - AlarmNames: [params.AlarmName] + AlarmNames: [params.AlarmName], }; - cw.enableAlarmActions(paramsEnableAlarmAction, function(err, data) { + cw.enableAlarmActions(paramsEnableAlarmAction, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/cloudwatch/cw_listmetrics.js b/javascript/example_code/cloudwatch/cw_listmetrics.js index 5a0bc542860..a3719ab526d 100644 --- a/javascript/example_code/cloudwatch/cw_listmetrics.js +++ b/javascript/example_code/cloudwatch/cw_listmetrics.js @@ -1,50 +1,29 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[cw_listmetrics.js demonstrates how to list metrics for Amazon CloudWatch.] -//snippet-service:[cloudwatch] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon CloudWatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide//cloudwatch-examples-getting-metrics.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide//cloudwatch-examples-getting-metrics.html // snippet-start:[cw.JavaScript.metrics.listMetrics] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create CloudWatch service object -var cw = new AWS.CloudWatch({apiVersion: '2010-08-01'}); +var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" }); var params = { Dimensions: [ { - Name: 'LogGroupName', /* required */ + Name: "LogGroupName" /* required */, }, ], - MetricName: 'IncomingLogEvents', - Namespace: 'AWS/Logs' + MetricName: "IncomingLogEvents", + Namespace: "AWS/Logs", }; -cw.listMetrics(params, function(err, data) { +cw.listMetrics(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/cloudwatch/cw_putmetricalarm.js b/javascript/example_code/cloudwatch/cw_putmetricalarm.js index ed6f94a74dc..0dead828cb7 100644 --- a/javascript/example_code/cloudwatch/cw_putmetricalarm.js +++ b/javascript/example_code/cloudwatch/cw_putmetricalarm.js @@ -1,60 +1,39 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[cw_putmetricalarm.js demonstrates how to create or update an Amazon CloudWatch alarm and associate it with particular metrics.] -//snippet-service:[cloudwatch] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon CloudWatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-creating-alarms.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-creating-alarms.html // snippet-start:[cw.JavaScript.alarms.putMetricAlarm] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create CloudWatch service object -var cw = new AWS.CloudWatch({apiVersion: '2010-08-01'}); +var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" }); var params = { - AlarmName: 'Web_Server_CPU_Utilization', - ComparisonOperator: 'GreaterThanThreshold', + AlarmName: "Web_Server_CPU_Utilization", + ComparisonOperator: "GreaterThanThreshold", EvaluationPeriods: 1, - MetricName: 'CPUUtilization', - Namespace: 'AWS/EC2', + MetricName: "CPUUtilization", + Namespace: "AWS/EC2", Period: 60, - Statistic: 'Average', + Statistic: "Average", Threshold: 70.0, ActionsEnabled: false, - AlarmDescription: 'Alarm when server CPU exceeds 70%', + AlarmDescription: "Alarm when server CPU exceeds 70%", Dimensions: [ { - Name: 'InstanceId', - Value: 'INSTANCE_ID' + Name: "InstanceId", + Value: "INSTANCE_ID", }, ], - Unit: 'Percent' + Unit: "Percent", }; -cw.putMetricAlarm(params, function(err, data) { +cw.putMetricAlarm(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/cloudwatch/cw_putmetricdata.js b/javascript/example_code/cloudwatch/cw_putmetricdata.js index 3151471da58..1e555e35171 100644 --- a/javascript/example_code/cloudwatch/cw_putmetricdata.js +++ b/javascript/example_code/cloudwatch/cw_putmetricdata.js @@ -1,58 +1,37 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[cw_putmetricdata.js demonstrates how to publish metric data to Amazon CloudWatch.] -//snippet-service:[cloudwatch] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon CloudWatch] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide//cloudwatch-examples-getting-metrics.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide//cloudwatch-examples-getting-metrics.html // snippet-start:[cw.JavaScript.metrics.putMetricData] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create CloudWatch service object -var cw = new AWS.CloudWatch({apiVersion: '2010-08-01'}); +var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" }); // Create parameters JSON for putMetricData var params = { MetricData: [ { - MetricName: 'PAGES_VISITED', + MetricName: "PAGES_VISITED", Dimensions: [ { - Name: 'UNIQUE_PAGES', - Value: 'URLS' + Name: "UNIQUE_PAGES", + Value: "URLS", }, ], - Unit: 'None', - Value: 1.0 + Unit: "None", + Value: 1.0, }, ], - Namespace: 'SITE/TRAFFIC' + Namespace: "SITE/TRAFFIC", }; -cw.putMetricData(params, function(err, data) { +cw.putMetricData(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/cognito/admin-create-user.js b/javascript/example_code/cognito/admin-create-user.js index 001d84e44aa..81ee9e53135 100644 --- a/javascript/example_code/cognito/admin-create-user.js +++ b/javascript/example_code/cognito/admin-create-user.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 2 (v2). Purpose: @@ -13,33 +14,34 @@ Inputs: */ // snippet-start:[cognito.JavaScript.admin-create-user-v2] -const aws = require('aws-sdk'); +const aws = require("aws-sdk"); // Initialize CognitoIdentityServiceProvider. const cognito = new AWS.CognitoIdentityServiceProvider({ - apiVersion: "2016-04-18", + apiVersion: "2016-04-18", }); const USERPOOLID = "your Cognito User Pool ID"; exports.handler = async (event, context) => { - const EMAIL = event.email; - const cognitoParams = { - UserPoolId: USERPOOLID, - Username: EMAIL, - UserAttributes: [{ - Name: "email", - Value: EMAIL, - }, - { - Name: "email_verified", - Value: "true", - }, - ], - TemporaryPassword: Math.random().toString(36).substr(2, 10), - }; - - let response = await cognito.adminCreateUser(cognitoParams).promise(); - console.log(JSON.stringify(response, null, 2)); -} -// snippet-end:[cognito.JavaScript.admin-create-user-v2] \ No newline at end of file + const EMAIL = event.email; + const cognitoParams = { + UserPoolId: USERPOOLID, + Username: EMAIL, + UserAttributes: [ + { + Name: "email", + Value: EMAIL, + }, + { + Name: "email_verified", + Value: "true", + }, + ], + TemporaryPassword: Math.random().toString(36).substr(2, 10), + }; + + let response = await cognito.adminCreateUser(cognitoParams).promise(); + console.log(JSON.stringify(response, null, 2)); +}; +// snippet-end:[cognito.JavaScript.admin-create-user-v2] diff --git a/javascript/example_code/cognito/admin-delete-user.js b/javascript/example_code/cognito/admin-delete-user.js index 412a78252f9..d19f5c861b2 100644 --- a/javascript/example_code/cognito/admin-delete-user.js +++ b/javascript/example_code/cognito/admin-delete-user.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 2 (v2). Purpose: @@ -14,22 +15,22 @@ Inputs: // snippet-start:[cognito.JavaScript.admin-delete-user-v2] -const aws = require('aws-sdk'); +const aws = require("aws-sdk"); /*Initializing CognitoIdentityServiceProvider from AWS SDK JS*/ const cognito = new AWS.CognitoIdentityServiceProvider({ - apiVersion: "2016-04-18", + apiVersion: "2016-04-18", }); const USERPOOLID = "your Cognito User Pool ID"; exports.handler = async (event, context) => { - const EMAIL = event.email; - const cognitoParams = { - UserPoolId: USERPOOLID, - Username: EMAIL - }; - - let response = await cognito.adminDeleteUser(cognitoParams).promise(); - console.log(JSON.stringify(response, null, 2)); -} + const EMAIL = event.email; + const cognitoParams = { + UserPoolId: USERPOOLID, + Username: EMAIL, + }; + + let response = await cognito.adminDeleteUser(cognitoParams).promise(); + console.log(JSON.stringify(response, null, 2)); +}; // snippet-end:[cognito.JavaScript.admin-delete-user-v2] diff --git a/javascript/example_code/cognito/admin-disable-user.js b/javascript/example_code/cognito/admin-disable-user.js index ff04a646f94..91d21805806 100644 --- a/javascript/example_code/cognito/admin-disable-user.js +++ b/javascript/example_code/cognito/admin-disable-user.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 2 (v2). Purpose: @@ -13,22 +14,22 @@ Inputs: */ // snippet-start:[cognito.JavaScript.admin-disable-user-v2] -const aws = require('aws-sdk'); +const aws = require("aws-sdk"); /*Initializing CognitoIdentityServiceProvider from AWS SDK JS*/ const cognito = new AWS.CognitoIdentityServiceProvider({ - apiVersion: "2016-04-18", + apiVersion: "2016-04-18", }); const USERPOOLID = "your Cognito User Pool ID"; exports.handler = async (event, context) => { - const EMAIL = event.email; - const cognitoParams = { - UserPoolId: USERPOOLID, - Username: EMAIL - }; - - let response = await cognito.adminDisableUser(cognitoParams).promise(); - console.log(JSON.stringify(response, null, 2)); -} -// snippet-end:[cognito.JavaScript.admin-disable-user-v2] \ No newline at end of file + const EMAIL = event.email; + const cognitoParams = { + UserPoolId: USERPOOLID, + Username: EMAIL, + }; + + let response = await cognito.adminDisableUser(cognitoParams).promise(); + console.log(JSON.stringify(response, null, 2)); +}; +// snippet-end:[cognito.JavaScript.admin-disable-user-v2] diff --git a/javascript/example_code/cognito/admin-enable-user.js b/javascript/example_code/cognito/admin-enable-user.js index c93b5f85322..e8eb9574ede 100644 --- a/javascript/example_code/cognito/admin-enable-user.js +++ b/javascript/example_code/cognito/admin-enable-user.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 2 (v2). Purpose: @@ -13,22 +14,22 @@ Inputs: */ // snippet-start:[cognito.JavaScript.admin-enable-user-v2] -const aws = require('aws-sdk'); +const aws = require("aws-sdk"); /*Initializing CognitoIdentityServiceProvider from AWS SDK JS*/ const cognito = new AWS.CognitoIdentityServiceProvider({ - apiVersion: "2016-04-18", + apiVersion: "2016-04-18", }); const USERPOOLID = "your Cognito User Pool ID"; exports.handler = async (event, context) => { - const EMAIL = event.email; - const cognitoParams = { - UserPoolId: USERPOOLID, - Username: EMAIL - }; - - let response = await cognito.adminEnableUser(cognitoParams).promise(); - console.log(JSON.stringify(response, null, 2)); -} -// snippet-end:[cognito.JavaScript.admin-enable-user-v2] \ No newline at end of file + const EMAIL = event.email; + const cognitoParams = { + UserPoolId: USERPOOLID, + Username: EMAIL, + }; + + let response = await cognito.adminEnableUser(cognitoParams).promise(); + console.log(JSON.stringify(response, null, 2)); +}; +// snippet-end:[cognito.JavaScript.admin-enable-user-v2] diff --git a/javascript/example_code/cognito/admin-get-user.js b/javascript/example_code/cognito/admin-get-user.js index 9c436ad8b9d..353e581c2a3 100644 --- a/javascript/example_code/cognito/admin-get-user.js +++ b/javascript/example_code/cognito/admin-get-user.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 2 (v2). Purpose: @@ -12,22 +13,22 @@ Inputs: */ // snippet-start:[cognito.JavaScript.admin-get-user-v2] -const aws = require('aws-sdk'); +const aws = require("aws-sdk"); /*Initializing CognitoIdentityServiceProvider from AWS SDK JS*/ const cognito = new AWS.CognitoIdentityServiceProvider({ - apiVersion: "2016-04-18", + apiVersion: "2016-04-18", }); const USERPOOLID = "your Cognito User Pool ID"; exports.handler = async (event, context) => { - const EMAIL = event.email; - const cognitoParams = { - UserPoolId: USERPOOLID, - Username: EMAIL - }; + const EMAIL = event.email; + const cognitoParams = { + UserPoolId: USERPOOLID, + Username: EMAIL, + }; - let response = await cognito.adminGetUser(cognitoParams).promise(); - console.log(JSON.stringify(response, null, 2)); -} -// snippet-end:[cognito.JavaScript.admin-get-user-v2] \ No newline at end of file + let response = await cognito.adminGetUser(cognitoParams).promise(); + console.log(JSON.stringify(response, null, 2)); +}; +// snippet-end:[cognito.JavaScript.admin-get-user-v2] diff --git a/javascript/example_code/cognito/lambda-trigger-auth-challenge-create.js b/javascript/example_code/cognito/lambda-trigger-auth-challenge-create.js index 307ca08167c..ee6ae93ff2d 100644 --- a/javascript/example_code/cognito/lambda-trigger-auth-challenge-create.js +++ b/javascript/example_code/cognito/lambda-trigger-auth-challenge-create.js @@ -1,37 +1,17 @@ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -// snippet-sourcedescription:[A CAPTCHA is created as a challenge to the user. The URL for the CAPTCHA image is added to the public challenge parameters as "captchaUrl", and the expected answer is added to the private challenge parameters.] -// snippet-service:[cognito-idp] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Cognito] -// snippet-keyword:[Code Sample] -// snippet-keyword:[lambda_trigger] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cognito.javascript.lambda-trigger.create-auth-challenge] exports.handler = (event, context, callback) => { - if (event.request.challengeName == 'CUSTOM_CHALLENGE') { - event.response.publicChallengeParameters = {}; - event.response.publicChallengeParameters.captchaUrl = 'url/123.jpg' - event.response.privateChallengeParameters = {}; - event.response.privateChallengeParameters.answer = '5'; - event.response.challengeMetadata = 'CAPTCHA_CHALLENGE'; - } + if (event.request.challengeName == "CUSTOM_CHALLENGE") { + event.response.publicChallengeParameters = {}; + event.response.publicChallengeParameters.captchaUrl = "url/123.jpg"; + event.response.privateChallengeParameters = {}; + event.response.privateChallengeParameters.answer = "5"; + event.response.challengeMetadata = "CAPTCHA_CHALLENGE"; + } - //Return to Amazon Cognito. - callback(null, event); -} -// snippet-end:[cognito.javascript.lambda-trigger.create-auth-challenge] \ No newline at end of file + //Return to Amazon Cognito. + callback(null, event); +}; +// snippet-end:[cognito.javascript.lambda-trigger.create-auth-challenge] diff --git a/javascript/example_code/cognito/lambda-trigger-auth-challenge-define.js b/javascript/example_code/cognito/lambda-trigger-auth-challenge-define.js index 23e114c6467..614ef5e7f8e 100644 --- a/javascript/example_code/cognito/lambda-trigger-auth-challenge-define.js +++ b/javascript/example_code/cognito/lambda-trigger-auth-challenge-define.js @@ -1,45 +1,36 @@ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -// snippet-sourcedescription:[This example defines a series of challenges for authentication and issues tokens only if all of the challenges are successfully completed.] -// snippet-service:[cognito-idp] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Cognito] -// snippet-keyword:[Code Sample] -// snippet-keyword:[lambda_trigger] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cognito.javascript.lambda-trigger.define-auth-challenge] exports.handler = (event, context, callback) => { - if (event.request.session.length == 1 && event.request.session[0].challengeName == 'SRP_A') { - event.response.issueTokens = false; - event.response.failAuthentication = false; - event.response.challengeName = 'PASSWORD_VERIFIER'; - } else if (event.request.session.length == 2 && event.request.session[1].challengeName == 'PASSWORD_VERIFIER' && event.request.session[1].challengeResult == true) { - event.response.issueTokens = false; - event.response.failAuthentication = false; - event.response.challengeName = 'CUSTOM_CHALLENGE'; - } else if (event.request.session.length == 3 && event.request.session[2].challengeName == 'CUSTOM_CHALLENGE' && event.request.session[2].challengeResult == true) { - event.response.issueTokens = true; - event.response.failAuthentication = false; - } else { - event.response.issueTokens = false; - event.response.failAuthentication = true; - } + if ( + event.request.session.length == 1 && + event.request.session[0].challengeName == "SRP_A" + ) { + event.response.issueTokens = false; + event.response.failAuthentication = false; + event.response.challengeName = "PASSWORD_VERIFIER"; + } else if ( + event.request.session.length == 2 && + event.request.session[1].challengeName == "PASSWORD_VERIFIER" && + event.request.session[1].challengeResult == true + ) { + event.response.issueTokens = false; + event.response.failAuthentication = false; + event.response.challengeName = "CUSTOM_CHALLENGE"; + } else if ( + event.request.session.length == 3 && + event.request.session[2].challengeName == "CUSTOM_CHALLENGE" && + event.request.session[2].challengeResult == true + ) { + event.response.issueTokens = true; + event.response.failAuthentication = false; + } else { + event.response.issueTokens = false; + event.response.failAuthentication = true; + } - // Return to Amazon Cognito - callback(null, event); -} -// snippet-end:[cognito.javascript.lambda-trigger.define-auth-challenge] \ No newline at end of file + // Return to Amazon Cognito + callback(null, event); +}; +// snippet-end:[cognito.javascript.lambda-trigger.define-auth-challenge] diff --git a/javascript/example_code/cognito/lambda-trigger-auth-challenge-verify.js b/javascript/example_code/cognito/lambda-trigger-auth-challenge-verify.js index 5958744110f..6d21ae647ee 100644 --- a/javascript/example_code/cognito/lambda-trigger-auth-challenge-verify.js +++ b/javascript/example_code/cognito/lambda-trigger-auth-challenge-verify.js @@ -1,35 +1,18 @@ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -// snippet-sourcedescription:[In this example, the Lambda function checks whether the user's response to a challenge matches the expected response. The answerCorrect parameter is set to true if the user's response matches the expected response.] -// snippet-service:[cognito-idp] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Cognito] -// snippet-keyword:[Code Sample] -// snippet-keyword:[lambda_trigger] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cognito.javascript.lambda-trigger.auth-challenge-verify] exports.handler = (event, context, callback) => { - if (event.request.privateChallengeParameters.answer == event.request.challengeAnswer) { - event.response.answerCorrect = true; - } else { - event.response.answerCorrect = false; - } + if ( + event.request.privateChallengeParameters.answer == + event.request.challengeAnswer + ) { + event.response.answerCorrect = true; + } else { + event.response.answerCorrect = false; + } - // Return to Amazon Cognito - callback(null, event); -} -// snippet-end:[cognito.javascript.lambda-trigger.auth-challenge-verify] \ No newline at end of file + // Return to Amazon Cognito + callback(null, event); +}; +// snippet-end:[cognito.javascript.lambda-trigger.auth-challenge-verify] diff --git a/javascript/example_code/cognito/lambda-trigger-custom-message-admin-create-user.js b/javascript/example_code/cognito/lambda-trigger-custom-message-admin-create-user.js index 8d39f55aff7..7481b23af50 100644 --- a/javascript/example_code/cognito/lambda-trigger-custom-message-admin-create-user.js +++ b/javascript/example_code/cognito/lambda-trigger-custom-message-admin-create-user.js @@ -1,42 +1,30 @@ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -// snippet-sourcedescription:[A custom message Lambda function with the CustomMessage_AdminCreateUser trigger returns a user name and verification code and so include both request.usernameParameter and request.codeParameter in the message body.] -// snippet-service:[cognito-idp] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Cognito] -// snippet-keyword:[Code Sample] -// snippet-keyword:[lambda_trigger] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cognito.javascript.lambda-trigger.custom-message-admin-create-user] exports.handler = (event, context, callback) => { - // - if(event.userPoolId === "theSpecialUserPool") { - // Identify why was this function invoked - if(event.triggerSource === "CustomMessage_AdminCreateUser") { - // Ensure that your message contains event.request.codeParameter event.request.usernameParameter. This is the placeholder for the code and username that will be sent to your user. - event.response.smsMessage = "Welcome to the service. Your user name is " + event.request.usernameParameter + " Your temporary password is " + event.request.codeParameter; - event.response.emailSubject = "Welcome to the service"; - event.response.emailMessage = "Welcome to the service. Your user name is " + event.request.usernameParameter + " Your temporary password is " + event.request.codeParameter; - } - // Create custom message for other events + // + if (event.userPoolId === "theSpecialUserPool") { + // Identify why was this function invoked + if (event.triggerSource === "CustomMessage_AdminCreateUser") { + // Ensure that your message contains event.request.codeParameter event.request.usernameParameter. This is the placeholder for the code and username that will be sent to your user. + event.response.smsMessage = + "Welcome to the service. Your user name is " + + event.request.usernameParameter + + " Your temporary password is " + + event.request.codeParameter; + event.response.emailSubject = "Welcome to the service"; + event.response.emailMessage = + "Welcome to the service. Your user name is " + + event.request.usernameParameter + + " Your temporary password is " + + event.request.codeParameter; } - // Customize messages for other user pools + // Create custom message for other events + } + // Customize messages for other user pools - // Return to Amazon Cognito - callback(null, event); + // Return to Amazon Cognito + callback(null, event); }; -// snippet-end:[cognito.javascript.lambda-trigger.custom-message-admin-create-user] \ No newline at end of file +// snippet-end:[cognito.javascript.lambda-trigger.custom-message-admin-create-user] diff --git a/javascript/example_code/cognito/lambda-trigger-custom-message-sign-up.js b/javascript/example_code/cognito/lambda-trigger-custom-message-sign-up.js index 830267a800a..112fba0d8b2 100644 --- a/javascript/example_code/cognito/lambda-trigger-custom-message-sign-up.js +++ b/javascript/example_code/cognito/lambda-trigger-custom-message-sign-up.js @@ -1,42 +1,27 @@ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -// snippet-sourcedescription:[This Lambda function is invoked to customize an email or SMS message when the service requires an app to send a verification code to the user.] -// snippet-service:[cognito-idp] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Cognito] -// snippet-keyword:[Code Sample] -// snippet-keyword:[lambda_trigger] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cognito.javascript.lambda-trigger.custom-message-sign-up] exports.handler = (event, context, callback) => { - // - if(event.userPoolId === "theSpecialUserPool") { - // Identify why was this function invoked - if(event.triggerSource === "CustomMessage_SignUp") { - // Ensure that your message contains event.request.codeParameter. This is the placeholder for code that will be sent - event.response.smsMessage = "Welcome to the service. Your confirmation code is " + event.request.codeParameter; - event.response.emailSubject = "Welcome to the service"; - event.response.emailMessage = "Thank you for signing up. " + event.request.codeParameter + " is your verification code"; - } - // Create custom message for other events + // + if (event.userPoolId === "theSpecialUserPool") { + // Identify why was this function invoked + if (event.triggerSource === "CustomMessage_SignUp") { + // Ensure that your message contains event.request.codeParameter. This is the placeholder for code that will be sent + event.response.smsMessage = + "Welcome to the service. Your confirmation code is " + + event.request.codeParameter; + event.response.emailSubject = "Welcome to the service"; + event.response.emailMessage = + "Thank you for signing up. " + + event.request.codeParameter + + " is your verification code"; } - // Customize messages for other user pools + // Create custom message for other events + } + // Customize messages for other user pools - // Return to Amazon Cognito - callback(null, event); + // Return to Amazon Cognito + callback(null, event); }; -// snippet-end:[cognito.javascript.lambda-trigger.custom-message-sign-up] \ No newline at end of file +// snippet-end:[cognito.javascript.lambda-trigger.custom-message-sign-up] diff --git a/javascript/example_code/cognito/lambda-trigger-migrate-user.js b/javascript/example_code/cognito/lambda-trigger-migrate-user.js index 3a77bdcfd87..abb562c8d7a 100644 --- a/javascript/example_code/cognito/lambda-trigger-migrate-user.js +++ b/javascript/example_code/cognito/lambda-trigger-migrate-user.js @@ -1,70 +1,43 @@ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -// snippet-sourcedescription:[This example Lambda function migrates the user with an existing password and suppresses the welcome message from Amazon Cognito.] -// snippet-service:[cognito-idp] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Cognito] -// snippet-keyword:[Code Sample] -// snippet-keyword:[lambda_trigger] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cognito.javascript.lambda-trigger.migrate-user] exports.handler = (event, context, callback) => { + var user; - var user; - - if ( event.triggerSource == "UserMigration_Authentication" ) { - - // authenticate the user with your existing user directory service - user = authenticateUser(event.userName, event.request.password); - if ( user ) { - event.response.userAttributes = { - "email": user.emailAddress, - "email_verified": "true" - }; - event.response.finalUserStatus = "CONFIRMED"; - event.response.messageAction = "SUPPRESS"; - context.succeed(event); - } - else { - // Return error to Amazon Cognito - callback("Bad password"); - } - } - else if ( event.triggerSource == "UserMigration_ForgotPassword" ) { - - // Lookup the user in your existing user directory service - user = lookupUser(event.userName); - if ( user ) { - event.response.userAttributes = { - "email": user.emailAddress, - // required to enable password-reset code to be sent to user - "email_verified": "true" - }; - event.response.messageAction = "SUPPRESS"; - context.succeed(event); - } - else { - // Return error to Amazon Cognito - callback("Bad password"); - } + if (event.triggerSource == "UserMigration_Authentication") { + // authenticate the user with your existing user directory service + user = authenticateUser(event.userName, event.request.password); + if (user) { + event.response.userAttributes = { + email: user.emailAddress, + email_verified: "true", + }; + event.response.finalUserStatus = "CONFIRMED"; + event.response.messageAction = "SUPPRESS"; + context.succeed(event); + } else { + // Return error to Amazon Cognito + callback("Bad password"); } - else { - // Return error to Amazon Cognito - callback("Bad triggerSource " + event.triggerSource); + } else if (event.triggerSource == "UserMigration_ForgotPassword") { + // Lookup the user in your existing user directory service + user = lookupUser(event.userName); + if (user) { + event.response.userAttributes = { + email: user.emailAddress, + // required to enable password-reset code to be sent to user + email_verified: "true", + }; + event.response.messageAction = "SUPPRESS"; + context.succeed(event); + } else { + // Return error to Amazon Cognito + callback("Bad password"); } + } else { + // Return error to Amazon Cognito + callback("Bad triggerSource " + event.triggerSource); + } }; -// snippet-end:[cognito.javascript.lambda-trigger.migrate-user] \ No newline at end of file +// snippet-end:[cognito.javascript.lambda-trigger.migrate-user] diff --git a/javascript/example_code/cognito/lambda-trigger-post-authentication.js b/javascript/example_code/cognito/lambda-trigger-post-authentication.js index 2a2cb75101d..ec87bb75894 100644 --- a/javascript/example_code/cognito/lambda-trigger-post-authentication.js +++ b/javascript/example_code/cognito/lambda-trigger-post-authentication.js @@ -1,37 +1,16 @@ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -// snippet-sourcedescription:[This post authentication sample Lambda function sends data from a successful sign-in to CloudWatch Logs.] -// snippet-service:[cognito-idp] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Cognito] -// snippet-keyword:[Code Sample] -// snippet-keyword:[lambda_trigger] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cognito.javascript.lambda-trigger.post-authentication] exports.handler = (event, context, callback) => { + // Send post authentication data to Cloudwatch logs + console.log("Authentication successful"); + console.log("Trigger function =", event.triggerSource); + console.log("User pool = ", event.userPoolId); + console.log("App client ID = ", event.callerContext.clientId); + console.log("User ID = ", event.userName); - // Send post authentication data to Cloudwatch logs - console.log ("Authentication successful"); - console.log ("Trigger function =", event.triggerSource); - console.log ("User pool = ", event.userPoolId); - console.log ("App client ID = ", event.callerContext.clientId); - console.log ("User ID = ", event.userName); - - // Return to Amazon Cognito - callback(null, event); + // Return to Amazon Cognito + callback(null, event); }; -// snippet-end:[cognito.javascript.lambda-trigger.post-authentication] \ No newline at end of file +// snippet-end:[cognito.javascript.lambda-trigger.post-authentication] diff --git a/javascript/example_code/cognito/lambda-trigger-post-confirmation.js b/javascript/example_code/cognito/lambda-trigger-post-confirmation.js index 241ec0a8ad5..0b4ce69e618 100644 --- a/javascript/example_code/cognito/lambda-trigger-post-confirmation.js +++ b/javascript/example_code/cognito/lambda-trigger-post-confirmation.js @@ -1,74 +1,57 @@ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -// snippet-sourcedescription:[This example Lambda function sends a confirmation email message to your user using Amazon SES.] -// snippet-service:[cognito-idp] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Cognito] -// snippet-keyword:[Code Sample] -// snippet-keyword:[lambda_trigger, send_email] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cognito.javascript.lambda-trigger.post-confirmation] -var aws = require('aws-sdk'); +var aws = require("aws-sdk"); var ses = new aws.SES(); exports.handler = (event, context, callback) => { - console.log(event); - - if (event.request.userAttributes.email) { - sendEmail(event.request.userAttributes.email, "Congratulations " + event.userName + ", you have been confirmed: ", function(status) { - - // Return to Amazon Cognito - callback(null, event); - }); - } else { - // Nothing to do, the user's email ID is unknown + console.log(event); + + if (event.request.userAttributes.email) { + sendEmail( + event.request.userAttributes.email, + "Congratulations " + event.userName + ", you have been confirmed: ", + function (status) { + // Return to Amazon Cognito callback(null, event); - } + } + ); + } else { + // Nothing to do, the user's email ID is unknown + callback(null, event); + } }; function sendEmail(to, body, completedCallback) { - var eParams = { - Destination: { - ToAddresses: [to] - }, - Message: { - Body: { - Text: { - Data: body - } - }, - Subject: { - Data: "Cognito Identity Provider registration completed" - } + var eParams = { + Destination: { + ToAddresses: [to], + }, + Message: { + Body: { + Text: { + Data: body, }, - - // Replace source_email with your SES validated email address - Source: "" - }; - - var email = ses.sendEmail(eParams, function(err, data){ - if (err) { - console.log(err); - } else { - console.log("===EMAIL SENT==="); - } - completedCallback('Email sent'); - }); - console.log("EMAIL CODE END"); -}; -// snippet-end:[cognito.javascript.lambda-trigger.post-confirmation] \ No newline at end of file + }, + Subject: { + Data: "Cognito Identity Provider registration completed", + }, + }, + + // Replace source_email with your SES validated email address + Source: "", + }; + + var email = ses.sendEmail(eParams, function (err, data) { + if (err) { + console.log(err); + } else { + console.log("===EMAIL SENT==="); + } + completedCallback("Email sent"); + }); + console.log("EMAIL CODE END"); +} +// snippet-end:[cognito.javascript.lambda-trigger.post-confirmation] diff --git a/javascript/example_code/cognito/lambda-trigger-pre-authentication.js b/javascript/example_code/cognito/lambda-trigger-pre-authentication.js index 8f0f850f88a..bd6863e99b0 100644 --- a/javascript/example_code/cognito/lambda-trigger-pre-authentication.js +++ b/javascript/example_code/cognito/lambda-trigger-pre-authentication.js @@ -1,36 +1,20 @@ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -// snippet-sourcedescription:[This sample function prevents users from a specific user pool app client to sign-in to the user pool.] -// snippet-service:[cognito-idp] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Cognito] -// snippet-keyword:[Code Sample] -// snippet-keyword:[lambda_trigger] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cognito.javascript.lambda-trigger.pre-authentication] exports.handler = (event, context, callback) => { - if (event.callerContext.clientId === "user-pool-app-client-id-to-be-blocked") { - var error = new Error("Cannot authenticate users from this user pool app client"); + if ( + event.callerContext.clientId === "user-pool-app-client-id-to-be-blocked" + ) { + var error = new Error( + "Cannot authenticate users from this user pool app client" + ); - // Return error to Amazon Cognito - callback(error, event); - } + // Return error to Amazon Cognito + callback(error, event); + } - // Return to Amazon Cognito - callback(null, event); + // Return to Amazon Cognito + callback(null, event); }; -// snippet-end:[cognito.javascript.lambda-trigger.pre-authentication] \ No newline at end of file +// snippet-end:[cognito.javascript.lambda-trigger.pre-authentication] diff --git a/javascript/example_code/cognito/lambda-trigger-pre-sign-up-auto-confirm-and-verify.js b/javascript/example_code/cognito/lambda-trigger-pre-sign-up-auto-confirm-and-verify.js index 93e7a2bafb3..12747dd6077 100644 --- a/javascript/example_code/cognito/lambda-trigger-pre-sign-up-auto-confirm-and-verify.js +++ b/javascript/example_code/cognito/lambda-trigger-pre-sign-up-auto-confirm-and-verify.js @@ -1,43 +1,22 @@ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -// snippet-sourcedescription:[This example confirms all users and sets the user's email and phone_number attributes to verified if the attribute is present. Also, if aliasing is enabled, aliases will be created for phone_number and email when auto-verify is set.] -// snippet-service:[cognito-idp] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Cognito] -// snippet-keyword:[Code Sample] -// snippet-keyword:[lambda_trigger] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cognito.javascript.lambda-trigger.pre-sign-up-auto-confirm-and-verify] exports.handler = (event, context, callback) => { + // Confirm the user + event.response.autoConfirmUser = true; - // Confirm the user - event.response.autoConfirmUser = true; - - // Set the email as verified if it is in the request - if (event.request.userAttributes.hasOwnProperty("email")) { - event.response.autoVerifyEmail = true; - } + // Set the email as verified if it is in the request + if (event.request.userAttributes.hasOwnProperty("email")) { + event.response.autoVerifyEmail = true; + } - // Set the phone number as verified if it is in the request - if (event.request.userAttributes.hasOwnProperty("phone_number")) { - event.response.autoVerifyPhone = true; - } + // Set the phone number as verified if it is in the request + if (event.request.userAttributes.hasOwnProperty("phone_number")) { + event.response.autoVerifyPhone = true; + } - // Return to Amazon Cognito - callback(null, event); + // Return to Amazon Cognito + callback(null, event); }; -// snippet-end:[cognito.javascript.lambda-trigger.pre-sign-up-auto-confirm-and-verify] \ No newline at end of file +// snippet-end:[cognito.javascript.lambda-trigger.pre-sign-up-auto-confirm-and-verify] diff --git a/javascript/example_code/cognito/lambda-trigger-pre-sign-up-auto-confirm-front-end.js b/javascript/example_code/cognito/lambda-trigger-pre-sign-up-auto-confirm-front-end.js index dd5b359045b..066052ec635 100644 --- a/javascript/example_code/cognito/lambda-trigger-pre-sign-up-auto-confirm-front-end.js +++ b/javascript/example_code/cognito/lambda-trigger-pre-sign-up-auto-confirm-front-end.js @@ -1,59 +1,46 @@ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -// snippet-sourcedescription:[This is a sample JavaScript program that demonstrates how to sign up a new user. It will invoke a pre sign-up Lambda trigger as part of the authentication.] -// snippet-service:[cognito-idp] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Cognito] -// snippet-keyword:[Code Sample] -// snippet-keyword:[sign_up, update_user_attributes] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cognito.javascript.lambda-trigger.pre-sign-up-auto-confirm-front-end] var attributeList = []; var dataEmail = { - Name : 'email', - Value : '...' // your email here + Name: "email", + Value: "...", // your email here }; var dataPhoneNumber = { - Name : 'phone_number', - Value : '...' // your phone number here with +country code and no delimiters in front + Name: "phone_number", + Value: "...", // your phone number here with +country code and no delimiters in front }; var dataEmailDomain = { - Name: "custom:domain", - Value: "example.com" -} -var attributeEmail = -new AmazonCognitoIdentity.CognitoUserAttribute(dataEmail); -var attributePhoneNumber = -new AmazonCognitoIdentity.CognitoUserAttribute(dataPhoneNumber); -var attributeEmailDomain = -new AmazonCognitoIdentity.CognitoUserAttribute(dataEmailDomain); - + Name: "custom:domain", + Value: "example.com", +}; +var attributeEmail = new AmazonCognitoIdentity.CognitoUserAttribute(dataEmail); +var attributePhoneNumber = new AmazonCognitoIdentity.CognitoUserAttribute( + dataPhoneNumber +); +var attributeEmailDomain = new AmazonCognitoIdentity.CognitoUserAttribute( + dataEmailDomain +); + attributeList.push(attributeEmail); attributeList.push(attributePhoneNumber); attributeList.push(attributeEmailDomain); - + var cognitoUser; -userPool.signUp('username', 'password', attributeList, null, function(err, result){ +userPool.signUp( + "username", + "password", + attributeList, + null, + function (err, result) { if (err) { - alert(err); - return; + alert(err); + return; } cognitoUser = result.user; - console.log('user name is ' + cognitoUser.getUsername()); -}); -// snippet-end:[cognito.javascript.lambda-trigger.pre-sign-up-auto-confirm-front-end] \ No newline at end of file + console.log("user name is " + cognitoUser.getUsername()); + } +); +// snippet-end:[cognito.javascript.lambda-trigger.pre-sign-up-auto-confirm-front-end] diff --git a/javascript/example_code/cognito/lambda-trigger-pre-sign-up-auto-confirm.js b/javascript/example_code/cognito/lambda-trigger-pre-sign-up-auto-confirm.js index a605f93489f..0e6881e3856 100644 --- a/javascript/example_code/cognito/lambda-trigger-pre-sign-up-auto-confirm.js +++ b/javascript/example_code/cognito/lambda-trigger-pre-sign-up-auto-confirm.js @@ -1,42 +1,22 @@ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -// snippet-sourcedescription:[This is a sample Lambda trigger called just before sign-up with the user pool pre sign-up Lambda trigger. It uses a custom attribute custom:domain to automatically confirm new users from a particular email domain. Any new users not in the custom domain will be added to the user pool, but not automatically confirmed.] -// snippet-service:[cognito-idp] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Cognito] -// snippet-keyword:[Code Sample] -// snippet-keyword:[lambda_trigger] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cognito.javascript.lambda-trigger.pre-sign-up-auto-confirm] exports.handler = (event, context, callback) => { - // Set the user pool autoConfirmUser flag after validating the email domain - event.response.autoConfirmUser = false; + // Set the user pool autoConfirmUser flag after validating the email domain + event.response.autoConfirmUser = false; + + // Split the email address so we can compare domains + var address = event.request.userAttributes.email.split("@"); - // Split the email address so we can compare domains - var address = event.request.userAttributes.email.split("@") - - // This example uses a custom attribute "custom:domain" - if (event.request.userAttributes.hasOwnProperty("custom:domain")) { - if ( event.request.userAttributes['custom:domain'] === address[1]) { - event.response.autoConfirmUser = true; - } + // This example uses a custom attribute "custom:domain" + if (event.request.userAttributes.hasOwnProperty("custom:domain")) { + if (event.request.userAttributes["custom:domain"] === address[1]) { + event.response.autoConfirmUser = true; } + } - // Return to Amazon Cognito - callback(null, event); + // Return to Amazon Cognito + callback(null, event); }; -// snippet-end:[cognito.javascript.lambda-trigger.pre-sign-up-auto-confirm] \ No newline at end of file +// snippet-end:[cognito.javascript.lambda-trigger.pre-sign-up-auto-confirm] diff --git a/javascript/example_code/cognito/lambda-trigger-pre-token-generation-add-suppress-claims.js b/javascript/example_code/cognito/lambda-trigger-pre-token-generation-add-suppress-claims.js index 9b23140381e..d2b09c08898 100644 --- a/javascript/example_code/cognito/lambda-trigger-pre-token-generation-add-suppress-claims.js +++ b/javascript/example_code/cognito/lambda-trigger-pre-token-generation-add-suppress-claims.js @@ -1,39 +1,19 @@ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -// snippet-sourcedescription:[This example uses the Pre Token Generation Lambda to add a new claim and suppresses an existing one.] -// snippet-service:[cognito-idp] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Cognito] -// snippet-keyword:[Code Sample] -// snippet-keyword:[lambda_trigger] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cognito.javascript.lambda-trigger.pre-token-generation-add-suppress-claims] exports.handler = (event, context, callback) => { - event.response = { - "claimsOverrideDetails": { - "claimsToAddOrOverride": { - "attribute_key2": "attribute_value2", - "attribute_key": "attribute_value" - }, - "claimsToSuppress": ["email"] - } - }; + event.response = { + claimsOverrideDetails: { + claimsToAddOrOverride: { + attribute_key2: "attribute_value2", + attribute_key: "attribute_value", + }, + claimsToSuppress: ["email"], + }, + }; - // Return to Amazon Cognito - callback(null, event); + // Return to Amazon Cognito + callback(null, event); }; -// snippet-end:[cognito.javascript.lambda-trigger.pre-token-generation-add-suppress-claims] \ No newline at end of file +// snippet-end:[cognito.javascript.lambda-trigger.pre-token-generation-add-suppress-claims] diff --git a/javascript/example_code/cognito/lambda-trigger-pre-token-generation-group-membership.js b/javascript/example_code/cognito/lambda-trigger-pre-token-generation-group-membership.js index 7988164a310..b618fa5d0d3 100644 --- a/javascript/example_code/cognito/lambda-trigger-pre-token-generation-group-membership.js +++ b/javascript/example_code/cognito/lambda-trigger-pre-token-generation-group-membership.js @@ -1,44 +1,28 @@ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. - -// snippet-sourcedescription:[This example uses the Pre Token Generation Lambda to modify the user's group membership.] -// snippet-service:[cognito-idp] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Cognito] -// snippet-keyword:[Code Sample] -// snippet-keyword:[lambda_trigger] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-30] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cognito.javascript.lambda-trigger.pre-token-generation-group-membership] exports.handler = (event, context, callback) => { - event.response = { - "claimsOverrideDetails": { - "claimsToAddOrOverride": { - "attribute_key2": "attribute_value2", - "attribute_key": "attribute_value" - }, - "claimsToSuppress": ["email"], - "groupOverrideDetails": { - "groupsToOverride": ["group-A", "group-B", "group-C"], - "iamRolesToOverride": ["arn:aws:iam::XXXXXXXXXXXX:role/sns_callerA", "arn:aws:iam::XXXXXXXXX:role/sns_callerB", "arn:aws:iam::XXXXXXXXXX:role/sns_callerC"], - "preferredRole": "arn:aws:iam::XXXXXXXXXXX:role/sns_caller" - } - } - }; + event.response = { + claimsOverrideDetails: { + claimsToAddOrOverride: { + attribute_key2: "attribute_value2", + attribute_key: "attribute_value", + }, + claimsToSuppress: ["email"], + groupOverrideDetails: { + groupsToOverride: ["group-A", "group-B", "group-C"], + iamRolesToOverride: [ + "arn:aws:iam::XXXXXXXXXXXX:role/sns_callerA", + "arn:aws:iam::XXXXXXXXX:role/sns_callerB", + "arn:aws:iam::XXXXXXXXXX:role/sns_callerC", + ], + preferredRole: "arn:aws:iam::XXXXXXXXXXX:role/sns_caller", + }, + }, + }; - // Return to Amazon Cognito - callback(null, event); + // Return to Amazon Cognito + callback(null, event); }; -// snippet-end:[cognito.javascript.lambda-trigger.pre-token-generation-group-membership] \ No newline at end of file +// snippet-end:[cognito.javascript.lambda-trigger.pre-token-generation-group-membership] diff --git a/javascript/example_code/connect/getHistoricalMetrics.js b/javascript/example_code/connect/getHistoricalMetrics.js index bcb06f3fc41..2be3fb784b3 100644 --- a/javascript/example_code/connect/getHistoricalMetrics.js +++ b/javascript/example_code/connect/getHistoricalMetrics.js @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[getRealtimeMetrics.js demonstrates how to .] -// snippet-service:[connect] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Connect] -// snippet-keyword:[Code Sample] -// snippet-keyword:[getMetricData] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-10-17] -// snippet-sourceauthor:[Doug-AWS] // snippet-start:[connect.javascript.getMetricData] /* This code uses callbacks to handle asynchronous function responses. @@ -33,178 +12,180 @@ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/calling-services-asynchronously.html https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html */ -const aws = require('aws-sdk') -const connect = new aws.Connect() +const aws = require("aws-sdk"); +const connect = new aws.Connect(); const params = { - InstanceId: 'Provide your connect instance id', + InstanceId: "Provide your connect instance id", EndTime: 1571184000, // enter a new end time StartTime: 1571153400, // enter a new start time Filters: { - Queues: ['Provide your connect instance queue id'], - Channels: ['VOICE'] + Queues: ["Provide your connect instance queue id"], + Channels: ["VOICE"], }, HistoricalMetrics: [ { - Name: 'AFTER_CONTACT_WORK_TIME', - Unit: 'SECONDS', - Statistic: 'AVG' + Name: "AFTER_CONTACT_WORK_TIME", + Unit: "SECONDS", + Statistic: "AVG", }, { - Name: 'CONTACTS_QUEUED', - Unit: 'COUNT', - Statistic: 'SUM' + Name: "CONTACTS_QUEUED", + Unit: "COUNT", + Statistic: "SUM", }, { - Name: 'CONTACTS_HANDLED', - Unit: 'COUNT', - Statistic: 'SUM' + Name: "CONTACTS_HANDLED", + Unit: "COUNT", + Statistic: "SUM", }, { - Name: 'HANDLE_TIME', - Unit: 'SECONDS', - Statistic: 'AVG' + Name: "HANDLE_TIME", + Unit: "SECONDS", + Statistic: "AVG", }, { - Name: 'CONTACTS_TRANSFERRED_OUT', - Unit: 'COUNT', - Statistic: 'SUM' + Name: "CONTACTS_TRANSFERRED_OUT", + Unit: "COUNT", + Statistic: "SUM", }, { - Name: 'CONTACTS_MISSED', - Unit: 'COUNT', - Statistic: 'SUM' + Name: "CONTACTS_MISSED", + Unit: "COUNT", + Statistic: "SUM", }, { - Name: 'OCCUPANCY', - Unit: 'PERCENT', - Statistic: 'AVG' + Name: "OCCUPANCY", + Unit: "PERCENT", + Statistic: "AVG", }, { - Name: 'QUEUED_TIME', - Unit: 'SECONDS', - Statistic: 'MAX' + Name: "QUEUED_TIME", + Unit: "SECONDS", + Statistic: "MAX", }, { - Name: 'HOLD_TIME', - Unit: 'SECONDS', - Statistic: 'AVG' + Name: "HOLD_TIME", + Unit: "SECONDS", + Statistic: "AVG", }, { - Name: 'SERVICE_LEVEL', + Name: "SERVICE_LEVEL", Threshold: { - Comparison: 'LT', - ThresholdValue: 60.0 + Comparison: "LT", + ThresholdValue: 60.0, }, - Unit: 'PERCENT', - Statistic: 'AVG' + Unit: "PERCENT", + Statistic: "AVG", }, { - Name: 'SERVICE_LEVEL', + Name: "SERVICE_LEVEL", Threshold: { - Comparison: 'LT', - ThresholdValue: 120.0 + Comparison: "LT", + ThresholdValue: 120.0, }, - Unit: 'PERCENT', - Statistic: 'AVG' + Unit: "PERCENT", + Statistic: "AVG", }, { - Name: 'SERVICE_LEVEL', + Name: "SERVICE_LEVEL", Threshold: { - Comparison: 'LT', - ThresholdValue: 30.0 + Comparison: "LT", + ThresholdValue: 30.0, }, - Unit: 'PERCENT', - Statistic: 'AVG' + Unit: "PERCENT", + Statistic: "AVG", }, { - Name: 'CONTACTS_ABANDONED', - Unit: 'COUNT', - Statistic: 'SUM' + Name: "CONTACTS_ABANDONED", + Unit: "COUNT", + Statistic: "SUM", }, { - Name: 'CONTACTS_CONSULTED', - Unit: 'COUNT', - Statistic: 'SUM' + Name: "CONTACTS_CONSULTED", + Unit: "COUNT", + Statistic: "SUM", }, { - Name: 'CONTACTS_AGENT_HUNG_UP_FIRST', - Unit: 'COUNT', - Statistic: 'SUM' + Name: "CONTACTS_AGENT_HUNG_UP_FIRST", + Unit: "COUNT", + Statistic: "SUM", }, { - Name: 'CONTACTS_HANDLED_INCOMING', - Unit: 'COUNT', - Statistic: 'SUM' + Name: "CONTACTS_HANDLED_INCOMING", + Unit: "COUNT", + Statistic: "SUM", }, { - Name: 'CONTACTS_HANDLED_OUTBOUND', - Unit: 'COUNT', - Statistic: 'SUM' + Name: "CONTACTS_HANDLED_OUTBOUND", + Unit: "COUNT", + Statistic: "SUM", }, { - Name: 'CONTACTS_HOLD_ABANDONS', - Unit: 'COUNT', - Statistic: 'SUM' + Name: "CONTACTS_HOLD_ABANDONS", + Unit: "COUNT", + Statistic: "SUM", }, { - Name: 'CONTACTS_TRANSFERRED_IN', - Unit: 'COUNT', - Statistic: 'SUM' + Name: "CONTACTS_TRANSFERRED_IN", + Unit: "COUNT", + Statistic: "SUM", }, { - Name: 'CONTACTS_TRANSFERRED_IN_FROM_QUEUE', - Unit: 'COUNT', - Statistic: 'SUM' + Name: "CONTACTS_TRANSFERRED_IN_FROM_QUEUE", + Unit: "COUNT", + Statistic: "SUM", }, { - Name: 'CONTACTS_TRANSFERRED_OUT_FROM_QUEUE', - Unit: 'COUNT', - Statistic: 'SUM' + Name: "CONTACTS_TRANSFERRED_OUT_FROM_QUEUE", + Unit: "COUNT", + Statistic: "SUM", }, { - Name: 'CALLBACK_CONTACTS_HANDLED', - Unit: 'COUNT', - Statistic: 'SUM' + Name: "CALLBACK_CONTACTS_HANDLED", + Unit: "COUNT", + Statistic: "SUM", }, { - Name: 'API_CONTACTS_HANDLED', - Unit: 'COUNT', - Statistic: 'SUM' + Name: "API_CONTACTS_HANDLED", + Unit: "COUNT", + Statistic: "SUM", }, { - Name: 'ABANDON_TIME', - Unit: 'SECONDS', - Statistic: 'AVG' + Name: "ABANDON_TIME", + Unit: "SECONDS", + Statistic: "AVG", }, { - Name: 'QUEUE_ANSWER_TIME', - Unit: 'SECONDS', - Statistic: 'AVG' + Name: "QUEUE_ANSWER_TIME", + Unit: "SECONDS", + Statistic: "AVG", }, { - Name: 'INTERACTION_TIME', - Unit: 'SECONDS', - Statistic: 'AVG' + Name: "INTERACTION_TIME", + Unit: "SECONDS", + Statistic: "AVG", }, { - Name: 'INTERACTION_AND_HOLD_TIME', - Unit: 'SECONDS', - Statistic: 'AVG' - } - ] -} + Name: "INTERACTION_AND_HOLD_TIME", + Unit: "SECONDS", + Statistic: "AVG", + }, + ], +}; exports.handler = async (event) => { - const result = await connect.getMetricData(params, function (err, data) { - if (err) { - console.log(err, err.stack) - } else { - console.log(data) - } - }).promise() + const result = await connect + .getMetricData(params, function (err, data) { + if (err) { + console.log(err, err.stack); + } else { + console.log(data); + } + }) + .promise(); - var metrics = result.MetricResults - console.log(metrics[0].Collections) -} + var metrics = result.MetricResults; + console.log(metrics[0].Collections); +}; // snippet-end:[connect.javascript.getMetricData] diff --git a/javascript/example_code/connect/getRealtimeMetrics.js b/javascript/example_code/connect/getRealtimeMetrics.js index d36e75608d8..c49cc6ea28c 100644 --- a/javascript/example_code/connect/getRealtimeMetrics.js +++ b/javascript/example_code/connect/getRealtimeMetrics.js @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[getRealtimeMetrics.js demonstrates how to .] -// snippet-service:[connect] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Connect] -// snippet-keyword:[Code Sample] -// snippet-keyword:[getCurrentMetricData] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-10-17] -// snippet-sourceauthor:[Doug-AWS] // snippet-start:[connect.javascript.getCurrentMetricData] /* This code uses callbacks to handle asynchronous function responses. @@ -33,25 +12,27 @@ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/calling-services-asynchronously.html https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html */ -const aws = require('aws-sdk') -const connect = new aws.Connect({ apiVersion: '2017-08-08' }) +const aws = require("aws-sdk"); +const connect = new aws.Connect({ apiVersion: "2017-08-08" }); const params = { - CurrentMetrics: [{ - Name: 'AGENTS_AVAILABLE', - Unit: 'COUNT' - }], + CurrentMetrics: [ + { + Name: "AGENTS_AVAILABLE", + Unit: "COUNT", + }, + ], Filters: { - Channels: ['VOICE'], - Queues: ['yourQueueID'] // replace 'yourQueueID' with your Queue ID + Channels: ["VOICE"], + Queues: ["yourQueueID"], // replace 'yourQueueID' with your Queue ID }, - InstanceId: 'yourInstanceID' // replace 'yourInstanceID' with your Instance ID -} + InstanceId: "yourInstanceID", // replace 'yourInstanceID' with your Instance ID +}; exports.handler = async (event) => { - const data = await connect.getCurrentMetricData(params).promise() - console.log(data) - var str = JSON.stringify(data, null, 2) - console.log(str) -} + const data = await connect.getCurrentMetricData(params).promise(); + console.log(data); + var str = JSON.stringify(data, null, 2); + console.log(str); +}; // snippet-end:[connect.javascript.getCurrentMetricData] diff --git a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesCreateTable.js b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesCreateTable.js index f1a74299851..927be4de709 100644 --- a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesCreateTable.js +++ b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesCreateTable.js @@ -1,58 +1,43 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesCreateTable] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesCreateTable] var AWS = require("aws-sdk"); AWS.config.update({ region: "us-west-2", - endpoint: "http://localhost:8000" + endpoint: "http://localhost:8000", }); var dynamodb = new AWS.DynamoDB(); var params = { - TableName : "Movies", - KeySchema: [ - { AttributeName: "year", KeyType: "HASH"}, //Partition key - { AttributeName: "title", KeyType: "RANGE" } //Sort key - ], - AttributeDefinitions: [ - { AttributeName: "year", AttributeType: "N" }, - { AttributeName: "title", AttributeType: "S" } - ], - ProvisionedThroughput: { - ReadCapacityUnits: 10, - WriteCapacityUnits: 10 - } + TableName: "Movies", + KeySchema: [ + { AttributeName: "year", KeyType: "HASH" }, //Partition key + { AttributeName: "title", KeyType: "RANGE" }, //Sort key + ], + AttributeDefinitions: [ + { AttributeName: "year", AttributeType: "N" }, + { AttributeName: "title", AttributeType: "S" }, + ], + ProvisionedThroughput: { + ReadCapacityUnits: 10, + WriteCapacityUnits: 10, + }, }; -dynamodb.createTable(params, function(err, data) { - if (err) { - console.error("Unable to create table. Error JSON:", JSON.stringify(err, null, 2)); - } else { - console.log("Created table. Table description JSON:", JSON.stringify(data, null, 2)); - } +dynamodb.createTable(params, function (err, data) { + if (err) { + console.error( + "Unable to create table. Error JSON:", + JSON.stringify(err, null, 2) + ); + } else { + console.log( + "Created table. Table description JSON:", + JSON.stringify(data, null, 2) + ); + } }); -// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesCreateTable] \ No newline at end of file +// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesCreateTable] diff --git a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesDeleteTable.js b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesDeleteTable.js index 1a059eccdad..832c7628b6d 100644 --- a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesDeleteTable.js +++ b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesDeleteTable.js @@ -1,47 +1,32 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesDeleteTable] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesDeleteTable] var AWS = require("aws-sdk"); AWS.config.update({ region: "us-west-2", - endpoint: "http://localhost:8000" + endpoint: "http://localhost:8000", }); var dynamodb = new AWS.DynamoDB(); var params = { - TableName : "Movies" + TableName: "Movies", }; -dynamodb.deleteTable(params, function(err, data) { - if (err) { - console.error("Unable to delete table. Error JSON:", JSON.stringify(err, null, 2)); - } else { - console.log("Deleted table. Table description JSON:", JSON.stringify(data, null, 2)); - } +dynamodb.deleteTable(params, function (err, data) { + if (err) { + console.error( + "Unable to delete table. Error JSON:", + JSON.stringify(err, null, 2) + ); + } else { + console.log( + "Deleted table. Table description JSON:", + JSON.stringify(data, null, 2) + ); + } }); -// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesDeleteTable] \ No newline at end of file +// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesDeleteTable] diff --git a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps01.js b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps01.js index 47bec82122a..a351377a076 100644 --- a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps01.js +++ b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps01.js @@ -1,33 +1,12 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesItemOps01] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesItemOps01] var AWS = require("aws-sdk"); AWS.config.update({ region: "us-west-2", - endpoint: "http://localhost:8000" + endpoint: "http://localhost:8000", }); var docClient = new AWS.DynamoDB.DocumentClient(); @@ -38,23 +17,26 @@ var year = 2015; var title = "The Big New Movie"; var params = { - TableName:table, - Item:{ - "year": year, - "title": title, - "info":{ - "plot": "Nothing happens at all.", - "rating": 0 - } - } + TableName: table, + Item: { + year: year, + title: title, + info: { + plot: "Nothing happens at all.", + rating: 0, + }, + }, }; console.log("Adding a new item..."); -docClient.put(params, function(err, data) { - if (err) { - console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2)); - } else { - console.log("Added item:", JSON.stringify(data, null, 2)); - } +docClient.put(params, function (err, data) { + if (err) { + console.error( + "Unable to add item. Error JSON:", + JSON.stringify(err, null, 2) + ); + } else { + console.log("Added item:", JSON.stringify(data, null, 2)); + } }); -// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesItemOps01] \ No newline at end of file +// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesItemOps01] diff --git a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps02.js b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps02.js index cb1c0543432..1d9b8529650 100644 --- a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps02.js +++ b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps02.js @@ -1,33 +1,12 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesItemOps02] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesItemOps02] var AWS = require("aws-sdk"); AWS.config.update({ region: "us-west-2", - endpoint: "http://localhost:8000" + endpoint: "http://localhost:8000", }); var docClient = new AWS.DynamoDB.DocumentClient(); @@ -38,18 +17,21 @@ var year = 2015; var title = "The Big New Movie"; var params = { - TableName: table, - Key:{ - "year": year, - "title": title - } + TableName: table, + Key: { + year: year, + title: title, + }, }; -docClient.get(params, function(err, data) { - if (err) { - console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2)); - } else { - console.log("GetItem succeeded:", JSON.stringify(data, null, 2)); - } +docClient.get(params, function (err, data) { + if (err) { + console.error( + "Unable to read item. Error JSON:", + JSON.stringify(err, null, 2) + ); + } else { + console.log("GetItem succeeded:", JSON.stringify(data, null, 2)); + } }); -// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesItemOps02] \ No newline at end of file +// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesItemOps02] diff --git a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps03.js b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps03.js index 64fcf0be888..2ca19149df7 100644 --- a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps03.js +++ b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps03.js @@ -1,36 +1,15 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesItemOps03] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesItemOps03] var AWS = require("aws-sdk"); AWS.config.update({ region: "us-west-2", - endpoint: "http://localhost:8000" + endpoint: "http://localhost:8000", }); -var docClient = new AWS.DynamoDB.DocumentClient() +var docClient = new AWS.DynamoDB.DocumentClient(); var table = "Movies"; @@ -40,26 +19,29 @@ var title = "The Big New Movie"; // Update the item, unconditionally, var params = { - TableName:table, - Key:{ - "year": year, - "title": title - }, - UpdateExpression: "set info.rating = :r, info.plot=:p, info.actors=:a", - ExpressionAttributeValues:{ - ":r":5.5, - ":p":"Everything happens all at once.", - ":a":["Larry", "Moe", "Curly"] - }, - ReturnValues:"UPDATED_NEW" + TableName: table, + Key: { + year: year, + title: title, + }, + UpdateExpression: "set info.rating = :r, info.plot=:p, info.actors=:a", + ExpressionAttributeValues: { + ":r": 5.5, + ":p": "Everything happens all at once.", + ":a": ["Larry", "Moe", "Curly"], + }, + ReturnValues: "UPDATED_NEW", }; console.log("Updating the item..."); -docClient.update(params, function(err, data) { - if (err) { - console.error("Unable to update item. Error JSON:", JSON.stringify(err, null, 2)); - } else { - console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2)); - } +docClient.update(params, function (err, data) { + if (err) { + console.error( + "Unable to update item. Error JSON:", + JSON.stringify(err, null, 2) + ); + } else { + console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2)); + } }); -// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesItemOps03] \ No newline at end of file +// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesItemOps03] diff --git a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps04.js b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps04.js index ea7c4ad7eb8..6b2c7f683ae 100644 --- a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps04.js +++ b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps04.js @@ -1,36 +1,15 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesItemOps04] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesItemOps04] var AWS = require("aws-sdk"); AWS.config.update({ region: "us-west-2", - endpoint: "http://localhost:8000" + endpoint: "http://localhost:8000", }); -var docClient = new AWS.DynamoDB.DocumentClient() +var docClient = new AWS.DynamoDB.DocumentClient(); var table = "Movies"; @@ -40,24 +19,27 @@ var title = "The Big New Movie"; // Increment an atomic counter var params = { - TableName:table, - Key:{ - "year": year, - "title": title - }, - UpdateExpression: "set info.rating = info.rating + :val", - ExpressionAttributeValues:{ - ":val": 1 - }, - ReturnValues:"UPDATED_NEW" + TableName: table, + Key: { + year: year, + title: title, + }, + UpdateExpression: "set info.rating = info.rating + :val", + ExpressionAttributeValues: { + ":val": 1, + }, + ReturnValues: "UPDATED_NEW", }; console.log("Updating the item..."); -docClient.update(params, function(err, data) { - if (err) { - console.error("Unable to update item. Error JSON:", JSON.stringify(err, null, 2)); - } else { - console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2)); - } +docClient.update(params, function (err, data) { + if (err) { + console.error( + "Unable to update item. Error JSON:", + JSON.stringify(err, null, 2) + ); + } else { + console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2)); + } }); -// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesItemOps04] \ No newline at end of file +// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesItemOps04] diff --git a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps05.js b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps05.js index c7d4a335714..1e23954bccf 100644 --- a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps05.js +++ b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps05.js @@ -1,36 +1,15 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesItemOps05] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesItemOps05] var AWS = require("aws-sdk"); AWS.config.update({ region: "us-west-2", - endpoint: "http://localhost:8000" + endpoint: "http://localhost:8000", }); -var docClient = new AWS.DynamoDB.DocumentClient() +var docClient = new AWS.DynamoDB.DocumentClient(); var table = "Movies"; @@ -40,25 +19,28 @@ var title = "The Big New Movie"; // Conditional update (will fail) var params = { - TableName:table, - Key:{ - "year": year, - "title": title - }, - UpdateExpression: "remove info.actors[0]", - ConditionExpression: "size(info.actors) > :num", - ExpressionAttributeValues:{ - ":num": 3 - }, - ReturnValues:"UPDATED_NEW" + TableName: table, + Key: { + year: year, + title: title, + }, + UpdateExpression: "remove info.actors[0]", + ConditionExpression: "size(info.actors) > :num", + ExpressionAttributeValues: { + ":num": 3, + }, + ReturnValues: "UPDATED_NEW", }; console.log("Attempting a conditional update..."); -docClient.update(params, function(err, data) { - if (err) { - console.error("Unable to update item. Error JSON:", JSON.stringify(err, null, 2)); - } else { - console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2)); - } +docClient.update(params, function (err, data) { + if (err) { + console.error( + "Unable to update item. Error JSON:", + JSON.stringify(err, null, 2) + ); + } else { + console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2)); + } }); -// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesItemOps05] \ No newline at end of file +// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesItemOps05] diff --git a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps06.js b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps06.js index 8e17ad68c47..350a07697f9 100644 --- a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps06.js +++ b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesItemOps06.js @@ -1,33 +1,13 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesItemOps06] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesItemOps06] +/*/ var AWS = require("aws-sdk"); AWS.config.update({ region: "us-west-2", - endpoint: "http://localhost:8000" + endpoint: "http://localhost:8000", }); var docClient = new AWS.DynamoDB.DocumentClient(); @@ -38,23 +18,26 @@ var year = 2015; var title = "The Big New Movie"; var params = { - TableName:table, - Key:{ - "year": year, - "title": title - }, - ConditionExpression:"info.rating <= :val", - ExpressionAttributeValues: { - ":val": 5.0 - } + TableName: table, + Key: { + year: year, + title: title, + }, + ConditionExpression: "info.rating <= :val", + ExpressionAttributeValues: { + ":val": 5.0, + }, }; console.log("Attempting a conditional delete..."); -docClient.delete(params, function(err, data) { - if (err) { - console.error("Unable to delete item. Error JSON:", JSON.stringify(err, null, 2)); - } else { - console.log("DeleteItem succeeded:", JSON.stringify(data, null, 2)); - } +docClient.delete(params, function (err, data) { + if (err) { + console.error( + "Unable to delete item. Error JSON:", + JSON.stringify(err, null, 2) + ); + } else { + console.log("DeleteItem succeeded:", JSON.stringify(data, null, 2)); + } }); -// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesItemOps06] \ No newline at end of file +// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesItemOps06] diff --git a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesLoadData.js b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesLoadData.js index bc20a4fbaaf..3a46435573d 100644 --- a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesLoadData.js +++ b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesLoadData.js @@ -1,57 +1,41 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesLoadData] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesLoadData] var AWS = require("aws-sdk"); -var fs = require('fs'); +var fs = require("fs"); AWS.config.update({ - region: "us-west-2", - endpoint: "http://localhost:8000" + region: "us-west-2", + endpoint: "http://localhost:8000", }); var docClient = new AWS.DynamoDB.DocumentClient(); console.log("Importing movies into DynamoDB. Please wait."); -var allMovies = JSON.parse(fs.readFileSync('moviedata.json', 'utf8')); -allMovies.forEach(function(movie) { - var params = { - TableName: "Movies", - Item: { - "year": movie.year, - "title": movie.title, - "info": movie.info - } - }; +var allMovies = JSON.parse(fs.readFileSync("moviedata.json", "utf8")); +allMovies.forEach(function (movie) { + var params = { + TableName: "Movies", + Item: { + year: movie.year, + title: movie.title, + info: movie.info, + }, + }; - docClient.put(params, function(err, data) { - if (err) { - console.error("Unable to add movie", movie.title, ". Error JSON:", JSON.stringify(err, null, 2)); - } else { - console.log("PutItem succeeded:", movie.title); - } - }); + docClient.put(params, function (err, data) { + if (err) { + console.error( + "Unable to add movie", + movie.title, + ". Error JSON:", + JSON.stringify(err, null, 2) + ); + } else { + console.log("PutItem succeeded:", movie.title); + } + }); }); -// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesLoadData] \ No newline at end of file +// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesLoadData] diff --git a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesQuery01.js b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesQuery01.js index fa2119ae106..4fe141569a5 100644 --- a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesQuery01.js +++ b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesQuery01.js @@ -1,33 +1,12 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesQuery01] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesQuery01] var AWS = require("aws-sdk"); AWS.config.update({ region: "us-west-2", - endpoint: "http://localhost:8000" + endpoint: "http://localhost:8000", }); var docClient = new AWS.DynamoDB.DocumentClient(); @@ -35,24 +14,24 @@ var docClient = new AWS.DynamoDB.DocumentClient(); console.log("Querying for movies from 1985."); var params = { - TableName : "Movies", - KeyConditionExpression: "#yr = :yyyy", - ExpressionAttributeNames:{ - "#yr": "year" - }, - ExpressionAttributeValues: { - ":yyyy": 1985 - } + TableName: "Movies", + KeyConditionExpression: "#yr = :yyyy", + ExpressionAttributeNames: { + "#yr": "year", + }, + ExpressionAttributeValues: { + ":yyyy": 1985, + }, }; -docClient.query(params, function(err, data) { - if (err) { - console.error("Unable to query. Error:", JSON.stringify(err, null, 2)); - } else { - console.log("Query succeeded."); - data.Items.forEach(function(item) { - console.log(" -", item.year + ": " + item.title); - }); - } +docClient.query(params, function (err, data) { + if (err) { + console.error("Unable to query. Error:", JSON.stringify(err, null, 2)); + } else { + console.log("Query succeeded."); + data.Items.forEach(function (item) { + console.log(" -", item.year + ": " + item.title); + }); + } }); -// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesQuery01] \ No newline at end of file +// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesQuery01] diff --git a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesQuery02.js b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesQuery02.js index 84d10b6fdda..14f2607ff83 100644 --- a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesQuery02.js +++ b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesQuery02.js @@ -1,65 +1,52 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesQuery02] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesQuery02] var AWS = require("aws-sdk"); AWS.config.update({ region: "us-west-2", - endpoint: "http://localhost:8000" + endpoint: "http://localhost:8000", }); var docClient = new AWS.DynamoDB.DocumentClient(); -console.log("Querying for movies from 1992 - titles A-L, with genres and lead actor"); +console.log( + "Querying for movies from 1992 - titles A-L, with genres and lead actor" +); var params = { - TableName : "Movies", - ProjectionExpression:"#yr, title, info.genres, info.actors[0]", - KeyConditionExpression: "#yr = :yyyy and title between :letter1 and :letter2", - ExpressionAttributeNames:{ - "#yr": "year" - }, - ExpressionAttributeValues: { - ":yyyy": 1992, - ":letter1": "A", - ":letter2": "L" - } + TableName: "Movies", + ProjectionExpression: "#yr, title, info.genres, info.actors[0]", + KeyConditionExpression: "#yr = :yyyy and title between :letter1 and :letter2", + ExpressionAttributeNames: { + "#yr": "year", + }, + ExpressionAttributeValues: { + ":yyyy": 1992, + ":letter1": "A", + ":letter2": "L", + }, }; -docClient.query(params, function(err, data) { - if (err) { - console.log("Unable to query. Error:", JSON.stringify(err, null, 2)); - } else { - console.log("Query succeeded."); - data.Items.forEach(function(item) { - console.log(" -", item.year + ": " + item.title - + " ... " + item.info.genres - + " ... " + item.info.actors[0]); - }); - } +docClient.query(params, function (err, data) { + if (err) { + console.log("Unable to query. Error:", JSON.stringify(err, null, 2)); + } else { + console.log("Query succeeded."); + data.Items.forEach(function (item) { + console.log( + " -", + item.year + + ": " + + item.title + + " ... " + + item.info.genres + + " ... " + + item.info.actors[0] + ); + }); + } }); - -// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesQuery02] \ No newline at end of file +// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesQuery02] diff --git a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesScan.js b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesScan.js index 95f08a31975..6361d629e53 100644 --- a/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesScan.js +++ b/javascript/example_code/dynamodb/GettingStarted/Node.js/MoviesScan.js @@ -1,72 +1,57 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesScan] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.JavaScript.CodeExample.MoviesScan] var AWS = require("aws-sdk"); AWS.config.update({ - region: "us-west-2", - endpoint: "http://localhost:8000" + region: "us-west-2", + endpoint: "http://localhost:8000", }); var docClient = new AWS.DynamoDB.DocumentClient(); var params = { - TableName: "Movies", - ProjectionExpression: "#yr, title, info.rating", - FilterExpression: "#yr between :start_yr and :end_yr", - ExpressionAttributeNames: { - "#yr": "year", - }, - ExpressionAttributeValues: { - ":start_yr": 1950, - ":end_yr": 1959 - } + TableName: "Movies", + ProjectionExpression: "#yr, title, info.rating", + FilterExpression: "#yr between :start_yr and :end_yr", + ExpressionAttributeNames: { + "#yr": "year", + }, + ExpressionAttributeValues: { + ":start_yr": 1950, + ":end_yr": 1959, + }, }; console.log("Scanning Movies table."); docClient.scan(params, onScan); function onScan(err, data) { - if (err) { - console.error("Unable to scan the table. Error JSON:", JSON.stringify(err, null, 2)); - } else { - // print all the movies - console.log("Scan succeeded."); - data.Items.forEach(function(movie) { - console.log( - movie.year + ": ", - movie.title, "- rating:", movie.info.rating); - }); + if (err) { + console.error( + "Unable to scan the table. Error JSON:", + JSON.stringify(err, null, 2) + ); + } else { + // print all the movies + console.log("Scan succeeded."); + data.Items.forEach(function (movie) { + console.log( + movie.year + ": ", + movie.title, + "- rating:", + movie.info.rating + ); + }); - // continue scanning if we have more movies, because - // scan can retrieve a maximum of 1MB of data - if (typeof data.LastEvaluatedKey != "undefined") { - console.log("Scanning for more..."); - params.ExclusiveStartKey = data.LastEvaluatedKey; - docClient.scan(params, onScan); - } + // continue scanning if we have more movies, because + // scan can retrieve a maximum of 1MB of data + if (typeof data.LastEvaluatedKey != "undefined") { + console.log("Scanning for more..."); + params.ExclusiveStartKey = data.LastEvaluatedKey; + docClient.scan(params, onScan); } + } } -// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesScan] \ No newline at end of file +// snippet-end:[dynamodb.JavaScript.CodeExample.MoviesScan] diff --git a/javascript/example_code/dynamodb/TryDax/01-create-table.js b/javascript/example_code/dynamodb/TryDax/01-create-table.js index ff4b4836878..014d35ac650 100644 --- a/javascript/example_code/dynamodb/TryDax/01-create-table.js +++ b/javascript/example_code/dynamodb/TryDax/01-create-table.js @@ -1,63 +1,48 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.javascript.trydax.01-create-table] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ -const AmazonDaxClient = require('amazon-dax-client'); +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[dynamodb.javascript.trydax.01-create-table] +const AmazonDaxClient = require("amazon-dax-client"); var AWS = require("aws-sdk"); var region = "us-west-2"; AWS.config.update({ - region: region + region: region, }); -var dynamodb = new AWS.DynamoDB() //low-level client +var dynamodb = new AWS.DynamoDB(); //low-level client var tableName = "TryDaxTable"; var params = { - TableName : tableName, - KeySchema: [ - { AttributeName: "pk", KeyType: "HASH"}, //Partition key - { AttributeName: "sk", KeyType: "RANGE" } //Sort key - ], - AttributeDefinitions: [ - { AttributeName: "pk", AttributeType: "N" }, - { AttributeName: "sk", AttributeType: "N" } - ], - ProvisionedThroughput: { - ReadCapacityUnits: 10, - WriteCapacityUnits: 10 - } + TableName: tableName, + KeySchema: [ + { AttributeName: "pk", KeyType: "HASH" }, //Partition key + { AttributeName: "sk", KeyType: "RANGE" }, //Sort key + ], + AttributeDefinitions: [ + { AttributeName: "pk", AttributeType: "N" }, + { AttributeName: "sk", AttributeType: "N" }, + ], + ProvisionedThroughput: { + ReadCapacityUnits: 10, + WriteCapacityUnits: 10, + }, }; -dynamodb.createTable(params, function(err, data) { - if (err) { - console.error("Unable to create table. Error JSON:", JSON.stringify(err, null, 2)); - } else { - console.log("Created table. Table description JSON:", JSON.stringify(data, null, 2)); - } +dynamodb.createTable(params, function (err, data) { + if (err) { + console.error( + "Unable to create table. Error JSON:", + JSON.stringify(err, null, 2) + ); + } else { + console.log( + "Created table. Table description JSON:", + JSON.stringify(data, null, 2) + ); + } }); -// snippet-end:[dynamodb.javascript.trydax.01-create-table] \ No newline at end of file +// snippet-end:[dynamodb.javascript.trydax.01-create-table] diff --git a/javascript/example_code/dynamodb/TryDax/02-write-data.js b/javascript/example_code/dynamodb/TryDax/02-write-data.js index 10fb768504f..76d21803ec8 100644 --- a/javascript/example_code/dynamodb/TryDax/02-write-data.js +++ b/javascript/example_code/dynamodb/TryDax/02-write-data.js @@ -1,71 +1,46 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.javascript.trydax.02-write-data] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ -const AmazonDaxClient = require('amazon-dax-client'); +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[dynamodb.javascript.trydax.02-write-data] +const AmazonDaxClient = require("amazon-dax-client"); var AWS = require("aws-sdk"); var region = "us-west-2"; AWS.config.update({ - region: region + region: region, }); -var ddbClient = new AWS.DynamoDB.DocumentClient() +var ddbClient = new AWS.DynamoDB.DocumentClient(); var tableName = "TryDaxTable"; - var someData = "X".repeat(1000); var pkmax = 10; var skmax = 10; -for (var ipk = 1; ipk <= pkmax; ipk++) { - - for (var isk = 1; isk <= skmax; isk++) { - var params = { - TableName: tableName, - Item: { - "pk": ipk, - "sk": isk, - "someData": someData - } - }; - - // - //put item - - ddbClient.put(params, function(err, data) { - if (err) { - console.error("Unable to write data: ", JSON.stringify(err, null, 2)); - } else { - console.log("PutItem succeeded"); - } - }); - - } +for (var ipk = 1; ipk <= pkmax; ipk++) { + for (var isk = 1; isk <= skmax; isk++) { + var params = { + TableName: tableName, + Item: { + pk: ipk, + sk: isk, + someData: someData, + }, + }; + + // + //put item + + ddbClient.put(params, function (err, data) { + if (err) { + console.error("Unable to write data: ", JSON.stringify(err, null, 2)); + } else { + console.log("PutItem succeeded"); + } + }); + } } - -// snippet-end:[dynamodb.javascript.trydax.02-write-data] \ No newline at end of file +// snippet-end:[dynamodb.javascript.trydax.02-write-data] diff --git a/javascript/example_code/dynamodb/TryDax/03-getitem-test.js b/javascript/example_code/dynamodb/TryDax/03-getitem-test.js index cbedf3ac3c3..12c1983ae99 100644 --- a/javascript/example_code/dynamodb/TryDax/03-getitem-test.js +++ b/javascript/example_code/dynamodb/TryDax/03-getitem-test.js @@ -1,43 +1,25 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.javascript.trydax.03-getitem-test] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ -const AmazonDaxClient = require('amazon-dax-client'); +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[dynamodb.javascript.trydax.03-getitem-test] +const AmazonDaxClient = require("amazon-dax-client"); var AWS = require("aws-sdk"); var region = "us-west-2"; AWS.config.update({ - region: region + region: region, }); -var ddbClient = new AWS.DynamoDB.DocumentClient() +var ddbClient = new AWS.DynamoDB.DocumentClient(); var daxClient = null; if (process.argv.length > 2) { - var dax = new AmazonDaxClient({endpoints: [process.argv[2]], region: region}) - daxClient = new AWS.DynamoDB.DocumentClient({service: dax }); + var dax = new AmazonDaxClient({ + endpoints: [process.argv[2]], + region: region, + }); + daxClient = new AWS.DynamoDB.DocumentClient({ service: dax }); } var client = daxClient != null ? daxClient : ddbClient; @@ -48,33 +30,39 @@ var sk = 10; var iterations = 5; for (var i = 0; i < iterations; i++) { + var startTime = new Date().getTime(); - var startTime = new Date().getTime(); - - for (var ipk = 1; ipk <= pk; ipk++) { - for (var isk = 1; isk <= sk; isk++) { - - var params = { - TableName: tableName, - Key:{ - "pk": ipk, - "sk": isk - } - }; + for (var ipk = 1; ipk <= pk; ipk++) { + for (var isk = 1; isk <= sk; isk++) { + var params = { + TableName: tableName, + Key: { + pk: ipk, + sk: isk, + }, + }; - client.get(params, function(err, data) { - if (err) { - console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2)); - } else { - // GetItem succeeded - } - }); + client.get(params, function (err, data) { + if (err) { + console.error( + "Unable to read item. Error JSON:", + JSON.stringify(err, null, 2) + ); + } else { + // GetItem succeeded } + }); } - - var endTime = new Date().getTime(); - console.log("\tTotal time: ", (endTime - startTime) , "ms - Avg time: ", (endTime - startTime) / iterations, "ms"); + } + var endTime = new Date().getTime(); + console.log( + "\tTotal time: ", + endTime - startTime, + "ms - Avg time: ", + (endTime - startTime) / iterations, + "ms" + ); } -// snippet-end:[dynamodb.javascript.trydax.03-getitem-test] \ No newline at end of file +// snippet-end:[dynamodb.javascript.trydax.03-getitem-test] diff --git a/javascript/example_code/dynamodb/TryDax/04-query-test.js b/javascript/example_code/dynamodb/TryDax/04-query-test.js index 1a1d85d385a..d8007b6fa3f 100644 --- a/javascript/example_code/dynamodb/TryDax/04-query-test.js +++ b/javascript/example_code/dynamodb/TryDax/04-query-test.js @@ -1,43 +1,25 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.javascript.trydax.04-query-test] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ -const AmazonDaxClient = require('amazon-dax-client'); +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[dynamodb.javascript.trydax.04-query-test] +const AmazonDaxClient = require("amazon-dax-client"); var AWS = require("aws-sdk"); var region = "us-west-2"; AWS.config.update({ - region: region + region: region, }); -var ddbClient = new AWS.DynamoDB.DocumentClient() +var ddbClient = new AWS.DynamoDB.DocumentClient(); var daxClient = null; if (process.argv.length > 2) { - var dax = new AmazonDaxClient({endpoints: [process.argv[2]], region: region}) - daxClient = new AWS.DynamoDB.DocumentClient({service: dax }); + var dax = new AmazonDaxClient({ + endpoints: [process.argv[2]], + region: region, + }); + daxClient = new AWS.DynamoDB.DocumentClient({ service: dax }); } var client = daxClient != null ? daxClient : ddbClient; @@ -49,29 +31,37 @@ var sk2 = 9; var iterations = 5; var params = { - TableName: tableName, - KeyConditionExpression: "pk = :pkval and sk between :skval1 and :skval2", - ExpressionAttributeValues: { - ":pkval":pk, - ":skval1":sk1, - ":skval2":sk2 - } + TableName: tableName, + KeyConditionExpression: "pk = :pkval and sk between :skval1 and :skval2", + ExpressionAttributeValues: { + ":pkval": pk, + ":skval1": sk1, + ":skval2": sk2, + }, }; for (var i = 0; i < iterations; i++) { - var startTime = new Date().getTime(); + var startTime = new Date().getTime(); - client.query(params, function(err, data) { - if (err) { - console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2)); - } else { - // Query succeeded - } - }); - - var endTime = new Date().getTime(); - console.log("\tTotal time: ", (endTime - startTime) , "ms - Avg time: ", (endTime - startTime) / iterations, "ms"); + client.query(params, function (err, data) { + if (err) { + console.error( + "Unable to read item. Error JSON:", + JSON.stringify(err, null, 2) + ); + } else { + // Query succeeded + } + }); + var endTime = new Date().getTime(); + console.log( + "\tTotal time: ", + endTime - startTime, + "ms - Avg time: ", + (endTime - startTime) / iterations, + "ms" + ); } -// snippet-end:[dynamodb.javascript.trydax.04-query-test] \ No newline at end of file +// snippet-end:[dynamodb.javascript.trydax.04-query-test] diff --git a/javascript/example_code/dynamodb/TryDax/05-scan-test.js b/javascript/example_code/dynamodb/TryDax/05-scan-test.js index 20c32144120..24dc13dc926 100644 --- a/javascript/example_code/dynamodb/TryDax/05-scan-test.js +++ b/javascript/example_code/dynamodb/TryDax/05-scan-test.js @@ -1,43 +1,25 @@ -// snippet-sourcedescription:[05-scan-js demonstrates how to ] -// snippet-service:[dynamodb] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.javascript.trydax.05-scan-test] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ -const AmazonDaxClient = require('amazon-dax-client'); +// snippet-start:[dynamodb.javascript.trydax.05-scan-test] +const AmazonDaxClient = require("amazon-dax-client"); var AWS = require("aws-sdk"); var region = "us-west-2"; AWS.config.update({ - region: region + region: region, }); -var ddbClient = new AWS.DynamoDB.DocumentClient() +var ddbClient = new AWS.DynamoDB.DocumentClient(); var daxClient = null; if (process.argv.length > 2) { - var dax = new AmazonDaxClient({endpoints: [process.argv[2]], region: region}) - daxClient = new AWS.DynamoDB.DocumentClient({service: dax }); + var dax = new AmazonDaxClient({ + endpoints: [process.argv[2]], + region: region, + }); + daxClient = new AWS.DynamoDB.DocumentClient({ service: dax }); } var client = daxClient != null ? daxClient : ddbClient; @@ -46,22 +28,29 @@ var tableName = "TryDaxTable"; var iterations = 5; var params = { - TableName: tableName + TableName: tableName, }; var startTime = new Date().getTime(); for (var i = 0; i < iterations; i++) { - - client.scan(params, function(err, data) { - if (err) { - console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2)); - } else { - // Scan succeeded - } - }); - + client.scan(params, function (err, data) { + if (err) { + console.error( + "Unable to read item. Error JSON:", + JSON.stringify(err, null, 2) + ); + } else { + // Scan succeeded + } + }); } var endTime = new Date().getTime(); -console.log("\tTotal time: ", (endTime - startTime) , "ms - Avg time: ", (endTime - startTime) / iterations, "ms"); +console.log( + "\tTotal time: ", + endTime - startTime, + "ms - Avg time: ", + (endTime - startTime) / iterations, + "ms" +); // snippet-end:[dynamodb.javascript.trydax.05-scan-test] diff --git a/javascript/example_code/dynamodb/TryDax/06-delete-table.js b/javascript/example_code/dynamodb/TryDax/06-delete-table.js index 79ed920f474..176426d810d 100644 --- a/javascript/example_code/dynamodb/TryDax/06-delete-table.js +++ b/javascript/example_code/dynamodb/TryDax/06-delete-table.js @@ -1,53 +1,36 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.javascript.trydax.06-delete-table] - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ -const AmazonDaxClient = require('amazon-dax-client'); +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[dynamodb.javascript.trydax.06-delete-table] +const AmazonDaxClient = require("amazon-dax-client"); var AWS = require("aws-sdk"); var region = "us-west-2"; AWS.config.update({ - region: region + region: region, }); -var dynamodb = new AWS.DynamoDB(); //low-level client +var dynamodb = new AWS.DynamoDB(); //low-level client var tableName = "TryDaxTable"; - -var params = { - TableName : tableName +var params = { + TableName: tableName, }; - -dynamodb.deleteTable(params, function(err, data) { - if (err) { - console.error("Unable to delete table. Error JSON:", JSON.stringify(err, null, 2)); - } else { - console.log("Deleted table. Table description JSON:", JSON.stringify(data, null, 2)); - } +dynamodb.deleteTable(params, function (err, data) { + if (err) { + console.error( + "Unable to delete table. Error JSON:", + JSON.stringify(err, null, 2) + ); + } else { + console.log( + "Deleted table. Table description JSON:", + JSON.stringify(data, null, 2) + ); + } }); -// snippet-end:[dynamodb.javascript.trydax.06-delete-table] \ No newline at end of file +// snippet-end:[dynamodb.javascript.trydax.06-delete-table] diff --git a/javascript/example_code/dynamodb/blog/parsewiki.js b/javascript/example_code/dynamodb/blog/parsewiki.js index ebf5aebe79c..7af70af5fc5 100644 --- a/javascript/example_code/dynamodb/blog/parsewiki.js +++ b/javascript/example_code/dynamodb/blog/parsewiki.js @@ -1,105 +1,90 @@ -// snippet-sourcedescription:[ ] -// snippet-service:[dynamodb] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon DynamoDB] -// snippet-keyword:[Code Sample] -// snippet-keyword:[ ] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[ ] -// snippet-sourceauthor:[AWS] -// snippet-start:[dynamodb.JavaScript.CodeExample.parsewiki] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// snippet-start:[dynamodb.JavaScript.CodeExample.parsewiki] var InstaView = require("instaview"); var AWS = require("aws-sdk"); -exports.handler = function(event, context, callback) { - // Uncomment for logging incoming event and records. - //console.log('Received event:', JSON.stringify(event, null, 2)); - event.Records.forEach(function(record) { - // Uncomment for logging event information. - //console.log(record.eventID); - //console.log(record.eventName); - - // Get the relevant fields from the record. - var id = record.dynamodb.NewImage.id.S; - var wiki = record.dynamodb.NewImage.wiki.S; - - AWS.config.update({ - region: "us-east-1" - }); +exports.handler = function (event, context, callback) { + // Uncomment for logging incoming event and records. + //console.log('Received event:', JSON.stringify(event, null, 2)); + event.Records.forEach(function (record) { + // Uncomment for logging event information. + //console.log(record.eventID); + //console.log(record.eventName); - var dynamodbDoc = new AWS.DynamoDB.DocumentClient(); - - // Set the InstaView parameters to ensure links have proper path. - - InstaView.conf.paths = { - base_href: '', - articles: 'wiki.htm?id=', - math: '/math/', - images: '', - images_fallback: 'http://upload.wikimedia.org/wikipedia/commons/', - magnify_icon: 'skins/common/images/magnify-clip.png' - }; + // Get the relevant fields from the record. + var id = record.dynamodb.NewImage.id.S; + var wiki = record.dynamodb.NewImage.wiki.S; - // Use InstaView to render HTML content from wiki markup. - var rendered = InstaView.convert(wiki); + AWS.config.update({ + region: "us-east-1", + }); + + var dynamodbDoc = new AWS.DynamoDB.DocumentClient(); + + // Set the InstaView parameters to ensure links have proper path. + + InstaView.conf.paths = { + base_href: "", + articles: "wiki.htm?id=", + math: "/math/", + images: "", + images_fallback: "http://upload.wikimedia.org/wikipedia/commons/", + magnify_icon: "skins/common/images/magnify-clip.png", + }; + + // Use InstaView to render HTML content from wiki markup. + var rendered = InstaView.convert(wiki); - // Update the record with the HTML output. - var params = { - TableName: "Wiki", - Key:{ - "id": id - }, - AttributeUpdates: { - content: { - Action: 'PUT', - Value: rendered - } - } - }; + // Update the record with the HTML output. + var params = { + TableName: "Wiki", + Key: { + id: id, + }, + AttributeUpdates: { + content: { + Action: "PUT", + Value: rendered, + }, + }, + }; - // Send update request to DynamoDB service. - dynamodbDoc.update(params, function(err, data) { - // Only log if there is an error. - if (err) { - console.error("Unable to update item. Error JSON:", JSON.stringify(err, null, 2)); - } - }); - - // Add entry with timestamp to history table for all previous versions. - params = { - TableName: "WikiHistory", - Item:{ - "id": id, - "timestamp": Math.floor(new Date() / 1000), - "wiki": wiki - } - }; - - // Send put item request to DynamoDB service. - dynamodbDoc.put(params, function(err, data) { - // Only log if there is an error. - if (err) { - console.error("Unable to update item. Error JSON:", JSON.stringify(err, null, 2)); - } - }); + // Send update request to DynamoDB service. + dynamodbDoc.update(params, function (err, data) { + // Only log if there is an error. + if (err) { + console.error( + "Unable to update item. Error JSON:", + JSON.stringify(err, null, 2) + ); + } }); - - // Exit when all calls return. - callback(); + + // Add entry with timestamp to history table for all previous versions. + params = { + TableName: "WikiHistory", + Item: { + id: id, + timestamp: Math.floor(new Date() / 1000), + wiki: wiki, + }, + }; + + // Send put item request to DynamoDB service. + dynamodbDoc.put(params, function (err, data) { + // Only log if there is an error. + if (err) { + console.error( + "Unable to update item. Error JSON:", + JSON.stringify(err, null, 2) + ); + } + }); + }); + + // Exit when all calls return. + callback(); }; -// snippet-end:[dynamodb.JavaScript.CodeExample.parsewiki] \ No newline at end of file +// snippet-end:[dynamodb.JavaScript.CodeExample.parsewiki] diff --git a/javascript/example_code/dynamodb/ddb_batchgetitem.js b/javascript/example_code/dynamodb/ddb_batchgetitem.js index bcf3db39252..dcc6f4b2b46 100755 --- a/javascript/example_code/dynamodb/ddb_batchgetitem.js +++ b/javascript/example_code/dynamodb/ddb_batchgetitem.js @@ -1,57 +1,36 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ddb_batchgetitem.js demonstrates how to retrieve items from an Amazon DynamoDB table.] -//snippet-service:[dynamodb] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-table-read-write-batch.html // snippet-start:[dynamodb.JavaScript.batch.GetItem] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create DynamoDB service object -var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); +var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { RequestItems: { - 'TABLE_NAME': { + TABLE_NAME: { Keys: [ - {'KEY_NAME': {N: 'KEY_VALUE_1'}}, - {'KEY_NAME': {N: 'KEY_VALUE_2'}}, - {'KEY_NAME': {N: 'KEY_VALUE_3'}} + { KEY_NAME: { N: "KEY_VALUE_1" } }, + { KEY_NAME: { N: "KEY_VALUE_2" } }, + { KEY_NAME: { N: "KEY_VALUE_3" } }, ], - ProjectionExpression: 'KEY_NAME, ATTRIBUTE' - } - } + ProjectionExpression: "KEY_NAME, ATTRIBUTE", + }, + }, }; -ddb.batchGetItem(params, function(err, data) { +ddb.batchGetItem(params, function (err, data) { if (err) { console.log("Error", err); } else { - data.Responses.TABLE_NAME.forEach(function(element, index, array) { + data.Responses.TABLE_NAME.forEach(function (element, index, array) { console.log(element); }); } diff --git a/javascript/example_code/dynamodb/ddb_batchwriteitem.js b/javascript/example_code/dynamodb/ddb_batchwriteitem.js index d4c0452edae..03323ded29b 100755 --- a/javascript/example_code/dynamodb/ddb_batchwriteitem.js +++ b/javascript/example_code/dynamodb/ddb_batchwriteitem.js @@ -1,65 +1,44 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ddb_batchwriteitem.js demonstrates how to put or delete items into an Amazon DynamoDB table.] -//snippet-service:[dynamodb] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-table-read-write-batch.html // snippet-start:[dynamodb.JavaScript.batch.WriteItem] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set the region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create DynamoDB service object -var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); +var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { RequestItems: { - "TABLE_NAME": [ - { - PutRequest: { - Item: { - "KEY": { "N": "KEY_VALUE" }, - "ATTRIBUTE_1": { "S": "ATTRIBUTE_1_VALUE" }, - "ATTRIBUTE_2": { "N": "ATTRIBUTE_2_VALUE" } - } - } - }, - { - PutRequest: { - Item: { - "KEY": { "N": "KEY_VALUE" }, - "ATTRIBUTE_1": { "S": "ATTRIBUTE_1_VALUE" }, - "ATTRIBUTE_2": { "N": "ATTRIBUTE_2_VALUE" } - } - } - } - ] - } + TABLE_NAME: [ + { + PutRequest: { + Item: { + KEY: { N: "KEY_VALUE" }, + ATTRIBUTE_1: { S: "ATTRIBUTE_1_VALUE" }, + ATTRIBUTE_2: { N: "ATTRIBUTE_2_VALUE" }, + }, + }, + }, + { + PutRequest: { + Item: { + KEY: { N: "KEY_VALUE" }, + ATTRIBUTE_1: { S: "ATTRIBUTE_1_VALUE" }, + ATTRIBUTE_2: { N: "ATTRIBUTE_2_VALUE" }, + }, + }, + }, + ], + }, }; -ddb.batchWriteItem(params, function(err, data) { +ddb.batchWriteItem(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/dynamodb/ddb_createtable.js b/javascript/example_code/dynamodb/ddb_createtable.js index 38e57b132cd..d44cd49442d 100755 --- a/javascript/example_code/dynamodb/ddb_createtable.js +++ b/javascript/example_code/dynamodb/ddb_createtable.js @@ -1,72 +1,51 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ddb_createtable.js demonstrates how to create an Amazon DynamoDB table.] -//snippet-service:[dynamodb] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-examples-using-tables.html // snippet-start:[dynamodb.JavaScript.table.createTable] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object -var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); +var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { AttributeDefinitions: [ { - AttributeName: 'CUSTOMER_ID', - AttributeType: 'N' + AttributeName: "CUSTOMER_ID", + AttributeType: "N", }, { - AttributeName: 'CUSTOMER_NAME', - AttributeType: 'S' - } + AttributeName: "CUSTOMER_NAME", + AttributeType: "S", + }, ], KeySchema: [ { - AttributeName: 'CUSTOMER_ID', - KeyType: 'HASH' + AttributeName: "CUSTOMER_ID", + KeyType: "HASH", }, { - AttributeName: 'CUSTOMER_NAME', - KeyType: 'RANGE' - } + AttributeName: "CUSTOMER_NAME", + KeyType: "RANGE", + }, ], ProvisionedThroughput: { ReadCapacityUnits: 1, - WriteCapacityUnits: 1 + WriteCapacityUnits: 1, }, - TableName: 'CUSTOMER_LIST', + TableName: "CUSTOMER_LIST", StreamSpecification: { - StreamEnabled: false - } + StreamEnabled: false, + }, }; // Call DynamoDB to create the table -ddb.createTable(params, function(err, data) { +ddb.createTable(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/dynamodb/ddb_deleteitem.js b/javascript/example_code/dynamodb/ddb_deleteitem.js index 11a9337ced4..d403bf065cf 100755 --- a/javascript/example_code/dynamodb/ddb_deleteitem.js +++ b/javascript/example_code/dynamodb/ddb_deleteitem.js @@ -1,48 +1,27 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ddb_deleteitem.js demonstrates how to delete an item from an Amazon DynamoDB table.] -//snippet-service:[dynamodb] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-table-read-write.html // snippet-start:[dynamodb.JavaScript.item.deleteItem] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object -var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); +var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { - TableName: 'TABLE', + TableName: "TABLE", Key: { - 'KEY_NAME': {N: 'VALUE'} - } + KEY_NAME: { N: "VALUE" }, + }, }; // Call DynamoDB to delete the item from the table -ddb.deleteItem(params, function(err, data) { +ddb.deleteItem(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/dynamodb/ddb_deletetable.js b/javascript/example_code/dynamodb/ddb_deletetable.js index 4ec30bedcad..80de52a9b13 100755 --- a/javascript/example_code/dynamodb/ddb_deletetable.js +++ b/javascript/example_code/dynamodb/ddb_deletetable.js @@ -1,48 +1,27 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ddb_deletetable.js demonstrates how to delete an Amazon DynamoDB table.] -//snippet-service:[dynamodb] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-examples-using-tables.html // snippet-start:[dynamodb.JavaScript.table.deleteTable] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object -var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); +var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { - TableName: process.argv[2] + TableName: process.argv[2], }; // Call DynamoDB to delete the specified table -ddb.deleteTable(params, function(err, data) { - if (err && err.code === 'ResourceNotFoundException') { +ddb.deleteTable(params, function (err, data) { + if (err && err.code === "ResourceNotFoundException") { console.log("Error: Table not found"); - } else if (err && err.code === 'ResourceInUseException') { + } else if (err && err.code === "ResourceInUseException") { console.log("Error: Table in use"); } else { console.log("Success", data); diff --git a/javascript/example_code/dynamodb/ddb_describetable.js b/javascript/example_code/dynamodb/ddb_describetable.js index 994a1a7ae87..c848532919e 100755 --- a/javascript/example_code/dynamodb/ddb_describetable.js +++ b/javascript/example_code/dynamodb/ddb_describetable.js @@ -1,45 +1,24 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ddb_describetable.js demonstrates how to retrieve information about an Amazon DynamoDB table.] -//snippet-service:[dynamodb] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-examples-using-tables.html // snippet-start:[dynamodb.JavaScript.table.describeTable] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object -var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); +var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { - TableName: process.argv[2] + TableName: process.argv[2], }; // Call DynamoDB to retrieve the selected table descriptions -ddb.describeTable(params, function(err, data) { +ddb.describeTable(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/dynamodb/ddb_getitem.js b/javascript/example_code/dynamodb/ddb_getitem.js index 9d441a1abdd..e95292a5e51 100755 --- a/javascript/example_code/dynamodb/ddb_getitem.js +++ b/javascript/example_code/dynamodb/ddb_getitem.js @@ -1,49 +1,28 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ddb_getitem.js demonstrates how to retrieve the attributes of an item from an Amazon DynamoDB table.] -//snippet-service:[dynamodb] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-table-read-write.html // snippet-start:[dynamodb.JavaScript.item.getItem] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object -var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); +var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { - TableName: 'TABLE', + TableName: "TABLE", Key: { - 'KEY_NAME': {N: '001'} + KEY_NAME: { N: "001" }, }, - ProjectionExpression: 'ATTRIBUTE_NAME' + ProjectionExpression: "ATTRIBUTE_NAME", }; // Call DynamoDB to read the item from the table -ddb.getItem(params, function(err, data) { +ddb.getItem(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/dynamodb/ddb_listtables.js b/javascript/example_code/dynamodb/ddb_listtables.js index 046bc39b8ff..139508c23b7 100755 --- a/javascript/example_code/dynamodb/ddb_listtables.js +++ b/javascript/example_code/dynamodb/ddb_listtables.js @@ -1,41 +1,20 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ddb_listtables.js demonstrates how to retrieve a list of Amazon DynamoDB table names.] -//snippet-service:[dynamodb] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-examples-using-tables.html // snippet-start:[dynamodb.JavaScript.table.listTables] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object -var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); +var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); // Call DynamoDB to retrieve the list of tables -ddb.listTables({Limit: 10}, function(err, data) { +ddb.listTables({ Limit: 10 }, function (err, data) { if (err) { console.log("Error", err.code); } else { diff --git a/javascript/example_code/dynamodb/ddb_putitem.js b/javascript/example_code/dynamodb/ddb_putitem.js index 962bd3dd30d..74683fddd71 100755 --- a/javascript/example_code/dynamodb/ddb_putitem.js +++ b/javascript/example_code/dynamodb/ddb_putitem.js @@ -1,49 +1,28 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ddb_putitem.js demonstrates how to create or update an item in an Amazon DynamoDB table.] -//snippet-service:[dynamodb] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-table-read-write.html // snippet-start:[dynamodb.JavaScript.item.putItem] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object -var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); +var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { - TableName: 'CUSTOMER_LIST', + TableName: "CUSTOMER_LIST", Item: { - 'CUSTOMER_ID' : {N: '001'}, - 'CUSTOMER_NAME' : {S: 'Richard Roe'} - } + CUSTOMER_ID: { N: "001" }, + CUSTOMER_NAME: { S: "Richard Roe" }, + }, }; // Call DynamoDB to add the item to the table -ddb.putItem(params, function(err, data) { +ddb.putItem(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/dynamodb/ddb_query.js b/javascript/example_code/dynamodb/ddb_query.js index de865128c5f..5df9b365c02 100755 --- a/javascript/example_code/dynamodb/ddb_query.js +++ b/javascript/example_code/dynamodb/ddb_query.js @@ -1,57 +1,36 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ddb_query.js demonstrates how to find items in an Amazon DynamoDB table.] -//snippet-service:[dynamodb] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-query-scan.html // snippet-start:[dynamodb.JavaScript.table.query] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set the region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create DynamoDB service object -var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); +var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { ExpressionAttributeValues: { - ':s': {N: '2'}, - ':e' : {N: '09'}, - ':topic' : {S: 'PHRASE'} + ":s": { N: "2" }, + ":e": { N: "09" }, + ":topic": { S: "PHRASE" }, }, - KeyConditionExpression: 'Season = :s and Episode > :e', - ProjectionExpression: 'Episode, Title, Subtitle', - FilterExpression: 'contains (Subtitle, :topic)', - TableName: 'EPISODES_TABLE' + KeyConditionExpression: "Season = :s and Episode > :e", + ProjectionExpression: "Episode, Title, Subtitle", + FilterExpression: "contains (Subtitle, :topic)", + TableName: "EPISODES_TABLE", }; -ddb.query(params, function(err, data) { +ddb.query(params, function (err, data) { if (err) { console.log("Error", err); } else { //console.log("Success", data.Items); - data.Items.forEach(function(element, index, array) { + data.Items.forEach(function (element, index, array) { console.log(element.Title.S + " (" + element.Subtitle.S + ")"); }); } diff --git a/javascript/example_code/dynamodb/ddb_scan.js b/javascript/example_code/dynamodb/ddb_scan.js index 399bb7252d9..cf7ab289241 100755 --- a/javascript/example_code/dynamodb/ddb_scan.js +++ b/javascript/example_code/dynamodb/ddb_scan.js @@ -1,32 +1,11 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ddb_scan.js demonstrates how to return items and attributes from an Amazon DynamoDB table.] -//snippet-service:[dynamodb] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-query-scan.html // snippet-start:[dynamodb.JavaScript.table.scan] - // Load the AWS SDK for Node.js. +// Load the AWS SDK for Node.js. var AWS = require("aws-sdk"); // Set the AWS Region. AWS.config.update({ region: "REGION" }); @@ -39,9 +18,9 @@ const params = { FilterExpression: "Subtitle = :topic AND Season = :s AND Episode = :e", // Define the expression attribute value, which are substitutes for the values you want to compare. ExpressionAttributeValues: { - ":topic": {S: "SubTitle2"}, - ":s": {N: 1}, - ":e": {N: 2}, + ":topic": { S: "SubTitle2" }, + ":s": { N: 1 }, + ":e": { N: 2 }, }, // Set the projection expression, which are the attributes that you want. ProjectionExpression: "Season, Episode, Title, Subtitle", @@ -55,8 +34,8 @@ ddb.scan(params, function (err, data) { console.log("Success", data); data.Items.forEach(function (element, index, array) { console.log( - "printing", - element.Title.S + " (" + element.Subtitle.S + ")" + "printing", + element.Title.S + " (" + element.Subtitle.S + ")" ); }); } diff --git a/javascript/example_code/dynamodb/ddbdoc_delete.js b/javascript/example_code/dynamodb/ddbdoc_delete.js index 15ce96e9b18..b20bfda1f49 100755 --- a/javascript/example_code/dynamodb/ddbdoc_delete.js +++ b/javascript/example_code/dynamodb/ddbdoc_delete.js @@ -1,47 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ddbdoc_delete.js demonstrates how to use a DocumentClient to delete an item from an Amazon DynamoDB table.] -//snippet-service:[dynamodb] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-document-client.html // snippet-start:[dynamodb.JavaScript.docClient.delete] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create DynamoDB document client -var docClient = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); +var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" }); var params = { Key: { - 'HASH_KEY': VALUE + HASH_KEY: VALUE, }, - TableName: 'TABLE' + TableName: "TABLE", }; -docClient.delete(params, function(err, data) { +docClient.delete(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/dynamodb/ddbdoc_get.js b/javascript/example_code/dynamodb/ddbdoc_get.js index 12eddb54d1e..d37b0065810 100755 --- a/javascript/example_code/dynamodb/ddbdoc_get.js +++ b/javascript/example_code/dynamodb/ddbdoc_get.js @@ -1,45 +1,24 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ddbdoc_get.js demonstrates how to use a DocumentClient to retrieve a set of attributes for an item in an Amazon DynamoDB table.] -//snippet-service:[dynamodb] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-document-client.html // snippet-start:[dynamodb.JavaScript.docClient.get] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create DynamoDB document client -var docClient = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); +var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" }); var params = { - TableName: 'EPISODES_TABLE', - Key: {'KEY_NAME': VALUE} + TableName: "EPISODES_TABLE", + Key: { KEY_NAME: VALUE }, }; -docClient.get(params, function(err, data) { +docClient.get(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/dynamodb/ddbdoc_put.js b/javascript/example_code/dynamodb/ddbdoc_put.js index fb8462c0154..cb0553a4cd1 100755 --- a/javascript/example_code/dynamodb/ddbdoc_put.js +++ b/javascript/example_code/dynamodb/ddbdoc_put.js @@ -1,49 +1,28 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ddbdoc_put.js demonstrates how to ues a DocumentClient to create or replace an item in an Amazon DynamoDB table.] -//snippet-service:[dynamodb] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-document-client.html // snippet-start:[dynamodb.JavaScript.docClient.put] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create DynamoDB document client -var docClient = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); +var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" }); var params = { - TableName: 'TABLE', + TableName: "TABLE", Item: { - 'HASHKEY': VALUE, - 'ATTRIBUTE_1': 'STRING_VALUE', - 'ATTRIBUTE_2': VALUE_2 - } + HASHKEY: VALUE, + ATTRIBUTE_1: "STRING_VALUE", + ATTRIBUTE_2: VALUE_2, + }, }; -docClient.put(params, function(err, data) { +docClient.put(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/dynamodb/ddbdoc_query.js b/javascript/example_code/dynamodb/ddbdoc_query.js index d2618a3b8aa..d9621a48afd 100755 --- a/javascript/example_code/dynamodb/ddbdoc_query.js +++ b/javascript/example_code/dynamodb/ddbdoc_query.js @@ -1,51 +1,30 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ddbdoc_query.js demonstrates how to use a DocumentClient to retrieve items from an Amazon DynamoDB table.] -//snippet-service:[dynamodb] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-document-client.html // snippet-start:[dynamodb.JavaScript.docClient.query] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create DynamoDB document client -var docClient = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); +var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" }); var params = { ExpressionAttributeValues: { - ':s': 2, - ':e': 9, - ':topic': 'PHRASE' - }, - KeyConditionExpression: 'Season = :s and Episode > :e', - FilterExpression: 'contains (Subtitle, :topic)', - TableName: 'EPISODES_TABLE' + ":s": 2, + ":e": 9, + ":topic": "PHRASE", + }, + KeyConditionExpression: "Season = :s and Episode > :e", + FilterExpression: "contains (Subtitle, :topic)", + TableName: "EPISODES_TABLE", }; -docClient.query(params, function(err, data) { +docClient.query(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/dynamodb/ddbdoc_update.js b/javascript/example_code/dynamodb/ddbdoc_update.js index c0e11427467..f8145e6309e 100755 --- a/javascript/example_code/dynamodb/ddbdoc_update.js +++ b/javascript/example_code/dynamodb/ddbdoc_update.js @@ -1,57 +1,36 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ddbdoc_update.js demonstrates how to use a DocumentClient to create or update an item in an Amazon DynamoDB table.] -//snippet-service:[dynamodb] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-document-client.html // snippet-start:[dynamodb.JavaScript.docClient.update] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set the region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create DynamoDB document client -var docClient = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); +var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" }); // Create variables to hold numeric key values var season = SEASON_NUMBER; var episode = EPISODES_NUMBER; var params = { - TableName: 'EPISODES_TABLE', + TableName: "EPISODES_TABLE", Key: { - 'Season' : season, - 'Episode' : episode + Season: season, + Episode: episode, }, - UpdateExpression: 'set Title = :t, Subtitle = :s', + UpdateExpression: "set Title = :t, Subtitle = :s", ExpressionAttributeValues: { - ':t' : 'NEW_TITLE', - ':s' : 'NEW_SUBTITLE' - } + ":t": "NEW_TITLE", + ":s": "NEW_SUBTITLE", + }, }; -docClient.update(params, function(err, data) { +docClient.update(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/ec2/ec2_allocateaddress.js b/javascript/example_code/ec2/ec2_allocateaddress.js index 294ea32eefe..7e0914a3787 100755 --- a/javascript/example_code/ec2/ec2_allocateaddress.js +++ b/javascript/example_code/ec2/ec2_allocateaddress.js @@ -1,61 +1,40 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ec2_allocateaddress.js demonstrates how to allocate and associate an Elastic IP address to an Amazon EC2 instance.] -//snippet-service:[ec2] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide//ec2-example-elastic-ip-addresses.html // snippet-start:[ec2.JavaScript.Addresses.allocateAddress] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create EC2 service object -var ec2 = new AWS.EC2({apiVersion: '2016-11-15'}); +var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" }); var paramsAllocateAddress = { - Domain: 'vpc' + Domain: "vpc", }; // Allocate the Elastic IP address -ec2.allocateAddress(paramsAllocateAddress, function(err, data) { - if (err) { - console.log("Address Not Allocated", err); - } else { - console.log("Address allocated:", data.AllocationId); - var paramsAssociateAddress = { - AllocationId: data.AllocationId, - InstanceId: 'INSTANCE_ID' - }; - // Associate the new Elastic IP address with an EC2 instance - ec2.associateAddress(paramsAssociateAddress, function(err, data) { - if (err) { - console.log("Address Not Associated", err); - } else { - console.log("Address associated:", data.AssociationId); - } - }); - } +ec2.allocateAddress(paramsAllocateAddress, function (err, data) { + if (err) { + console.log("Address Not Allocated", err); + } else { + console.log("Address allocated:", data.AllocationId); + var paramsAssociateAddress = { + AllocationId: data.AllocationId, + InstanceId: "INSTANCE_ID", + }; + // Associate the new Elastic IP address with an EC2 instance + ec2.associateAddress(paramsAssociateAddress, function (err, data) { + if (err) { + console.log("Address Not Associated", err); + } else { + console.log("Address associated:", data.AssociationId); + } + }); + } }); // snippet-end:[ec2.JavaScript.Addresses.allocateAddress] diff --git a/javascript/example_code/ec2/ec2_createinstances.js b/javascript/example_code/ec2/ec2_createinstances.js index 40eaaf8c713..edf5b7c9d65 100755 --- a/javascript/example_code/ec2/ec2_createinstances.js +++ b/javascript/example_code/ec2/ec2_createinstances.js @@ -1,76 +1,62 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ec2_createinstances.js demonstrates how to create an Amazon EC2 instance.] -//snippet-service:[ec2] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide//ec2-example-creating-an-instance.html // snippet-start:[ec2.JavaScript.Instances.create_instances] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Load credentials and set region from JSON file -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create EC2 service object -var ec2 = new AWS.EC2({apiVersion: '2016-11-15'}); +var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" }); // AMI is amzn-ami-2011.09.1.x86_64-ebs var instanceParams = { - ImageId: 'AMI_ID', - InstanceType: 't2.micro', - KeyName: 'KEY_PAIR_NAME', - MinCount: 1, - MaxCount: 1 + ImageId: "AMI_ID", + InstanceType: "t2.micro", + KeyName: "KEY_PAIR_NAME", + MinCount: 1, + MaxCount: 1, }; // Create a promise on an EC2 service object -var instancePromise = new AWS.EC2({apiVersion: '2016-11-15'}).runInstances(instanceParams).promise(); +var instancePromise = new AWS.EC2({ apiVersion: "2016-11-15" }) + .runInstances(instanceParams) + .promise(); // Handle promise's fulfilled/rejected states -instancePromise.then( - function(data) { +instancePromise + .then(function (data) { console.log(data); var instanceId = data.Instances[0].InstanceId; console.log("Created instance", instanceId); // Add tags to the instance - tagParams = {Resources: [instanceId], Tags: [ - { - Key: 'Name', - Value: 'SDK Sample' - } - ]}; + tagParams = { + Resources: [instanceId], + Tags: [ + { + Key: "Name", + Value: "SDK Sample", + }, + ], + }; // Create a promise on an EC2 service object - var tagPromise = new AWS.EC2({apiVersion: '2016-11-15'}).createTags(tagParams).promise(); + var tagPromise = new AWS.EC2({ apiVersion: "2016-11-15" }) + .createTags(tagParams) + .promise(); // Handle promise's fulfilled/rejected states - tagPromise.then( - function(data) { + tagPromise + .then(function (data) { console.log("Instance tagged"); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[ec2.JavaScript.Instances.create_instances] diff --git a/javascript/example_code/ec2/ec2_createkeypair.js b/javascript/example_code/ec2/ec2_createkeypair.js index c283b6fa18a..aaeec290cb7 100755 --- a/javascript/example_code/ec2/ec2_createkeypair.js +++ b/javascript/example_code/ec2/ec2_createkeypair.js @@ -1,49 +1,28 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ec2_createkeypair.js demonstrates how to create an RSA key pair for an Amazon EC2 instance.] -//snippet-service:[ec2] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ec2-example-key-pairs.html // snippet-start:[ec2.JavaScript.keypairs.createKeyPair] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create EC2 service object -var ec2 = new AWS.EC2({apiVersion: '2016-11-15'}); +var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" }); var params = { - KeyName: 'KEY_PAIR_NAME' + KeyName: "KEY_PAIR_NAME", }; // Create the key pair -ec2.createKeyPair(params, function(err, data) { - if (err) { - console.log("Error", err); - } else { - console.log(JSON.stringify(data)); - } +ec2.createKeyPair(params, function (err, data) { + if (err) { + console.log("Error", err); + } else { + console.log(JSON.stringify(data)); + } }); // snippet-end:[ec2.JavaScript.keypairs.createKeyPair] diff --git a/javascript/example_code/ec2/ec2_createsecuritygroup.js b/javascript/example_code/ec2/ec2_createsecuritygroup.js index afa5bc7ad79..a7c479b8cfc 100755 --- a/javascript/example_code/ec2/ec2_createsecuritygroup.js +++ b/javascript/example_code/ec2/ec2_createsecuritygroup.js @@ -1,86 +1,65 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ec2_createsecuritygroup.js demonstrates how to create a security group for an Amazon EC2 instance.] -//snippet-service:[ec2] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2019-08-06] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ec2-example-security-groups.html // snippet-start:[ec2.JavaScript.SecurityGroups.createSecurityGroup] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Load credentials and set region from JSON file -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create EC2 service object -var ec2 = new AWS.EC2({apiVersion: '2016-11-15'}); +var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" }); // Variable to hold a ID of a VPC var vpc = null; // Retrieve the ID of a VPC -ec2.describeVpcs(function(err, data) { - if (err) { - console.log("Cannot retrieve a VPC", err); - } else { - vpc = data.Vpcs[0].VpcId; - var paramsSecurityGroup = { - Description: 'DESCRIPTION', - GroupName: 'SECURITY_GROUP_NAME', - VpcId: vpc - }; - // Create the instance - ec2.createSecurityGroup(paramsSecurityGroup, function(err, data) { - if (err) { - console.log("Error", err); - } else { - var SecurityGroupId = data.GroupId; - console.log("Success", SecurityGroupId); - var paramsIngress = { - GroupId: 'SECURITY_GROUP_ID', - IpPermissions:[ - { - IpProtocol: "tcp", - FromPort: 80, - ToPort: 80, - IpRanges: [{"CidrIp":"0.0.0.0/0"}] - }, - { - IpProtocol: "tcp", - FromPort: 22, - ToPort: 22, - IpRanges: [{"CidrIp":"0.0.0.0/0"}] - } - ] - }; - ec2.authorizeSecurityGroupIngress(paramsIngress, function(err, data) { - if (err) { - console.log("Error", err); - } else { - console.log("Ingress Successfully Set", data); - } - }); - } - }); - } +ec2.describeVpcs(function (err, data) { + if (err) { + console.log("Cannot retrieve a VPC", err); + } else { + vpc = data.Vpcs[0].VpcId; + var paramsSecurityGroup = { + Description: "DESCRIPTION", + GroupName: "SECURITY_GROUP_NAME", + VpcId: vpc, + }; + // Create the instance + ec2.createSecurityGroup(paramsSecurityGroup, function (err, data) { + if (err) { + console.log("Error", err); + } else { + var SecurityGroupId = data.GroupId; + console.log("Success", SecurityGroupId); + var paramsIngress = { + GroupId: "SECURITY_GROUP_ID", + IpPermissions: [ + { + IpProtocol: "tcp", + FromPort: 80, + ToPort: 80, + IpRanges: [{ CidrIp: "0.0.0.0/0" }], + }, + { + IpProtocol: "tcp", + FromPort: 22, + ToPort: 22, + IpRanges: [{ CidrIp: "0.0.0.0/0" }], + }, + ], + }; + ec2.authorizeSecurityGroupIngress(paramsIngress, function (err, data) { + if (err) { + console.log("Error", err); + } else { + console.log("Ingress Successfully Set", data); + } + }); + } + }); + } }); // snippet-end:[ec2.JavaScript.SecurityGroups.createSecurityGroup] diff --git a/javascript/example_code/ec2/ec2_deletekeypair.js b/javascript/example_code/ec2/ec2_deletekeypair.js index ed1888b62a0..96e52269637 100755 --- a/javascript/example_code/ec2/ec2_deletekeypair.js +++ b/javascript/example_code/ec2/ec2_deletekeypair.js @@ -1,49 +1,28 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ec2_deletekeypair.js demonstrates how to delete a key pair from an Amazon EC2 instance.] -//snippet-service:[ec2] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ec2-example-key-pairs.html // snippet-start:[ec2.JavaScript.keypairs.deleteKeyPair] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create EC2 service object -var ec2 = new AWS.EC2({apiVersion: '2016-11-15'}); +var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" }); var params = { - KeyName: 'KEY_PAIR_NAME' + KeyName: "KEY_PAIR_NAME", }; // Delete the key pair -ec2.deleteKeyPair(params, function(err, data) { - if (err) { - console.log("Error", err); - } else { - console.log("Key Pair Deleted"); - } +ec2.deleteKeyPair(params, function (err, data) { + if (err) { + console.log("Error", err); + } else { + console.log("Key Pair Deleted"); + } }); // snippet-end:[ec2.JavaScript.keypairs.deleteKeyPair] diff --git a/javascript/example_code/ec2/ec2_deletesecuritygroup.js b/javascript/example_code/ec2/ec2_deletesecuritygroup.js index 61a7c6044b7..0da27a604ab 100755 --- a/javascript/example_code/ec2/ec2_deletesecuritygroup.js +++ b/javascript/example_code/ec2/ec2_deletesecuritygroup.js @@ -1,49 +1,28 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ec2_deletesecuritygroup.js demonstrates how to delete a security group from an Amazon EC2 instance.] -//snippet-service:[ec2] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ec2-example-security-groups.html // snippet-start:[ec2.JavaScript.SecurityGroups.deleteSecurityGroup] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create EC2 service object -var ec2 = new AWS.EC2({apiVersion: '2016-11-15'}); +var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" }); var params = { - GroupId: 'SECURITY_GROUP_ID' + GroupId: "SECURITY_GROUP_ID", }; // Delete the security group -ec2.deleteSecurityGroup(params, function(err, data) { - if (err) { - console.log("Error", err); - } else { - console.log("Security Group Deleted"); - } +ec2.deleteSecurityGroup(params, function (err, data) { + if (err) { + console.log("Error", err); + } else { + console.log("Security Group Deleted"); + } }); // snippet-end:[ec2.JavaScript.SecurityGroups.deleteSecurityGroup] diff --git a/javascript/example_code/ec2/ec2_describeaddresses.js b/javascript/example_code/ec2/ec2_describeaddresses.js index f8e4347dc17..f483ca775e2 100755 --- a/javascript/example_code/ec2/ec2_describeaddresses.js +++ b/javascript/example_code/ec2/ec2_describeaddresses.js @@ -1,47 +1,24 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ec2_describeaddresses.js demonstrates how to retrieve information about one or more Elastic IP addresses.] -//snippet-service:[ec2] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide//ec2-example-elastic-ip-addresses.html // snippet-start:[ec2.JavaScript.Addresses.describeAddresses] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create EC2 service object -var ec2 = new AWS.EC2({apiVersion: '2016-11-15'}); +var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" }); var params = { - Filters: [ - {Name: 'domain', Values: ['vpc']} - ] + Filters: [{ Name: "domain", Values: ["vpc"] }], }; // Retrieve Elastic IP address descriptions -ec2.describeAddresses(params, function(err, data) { +ec2.describeAddresses(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/ec2/ec2_describeinstances.js b/javascript/example_code/ec2/ec2_describeinstances.js index 1ab5cd7ba3c..e01a9b17756 100755 --- a/javascript/example_code/ec2/ec2_describeinstances.js +++ b/javascript/example_code/ec2/ec2_describeinstances.js @@ -1,45 +1,24 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ec2_describeinstances.js demonstrates how to retrieve information about one or more Amazon EC2 instances.] -//snippet-service:[ec2] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ec2-example-managing-instances.html // snippet-start:[ec2.JavaScript.Instances.describeInstances] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create EC2 service object -var ec2 = new AWS.EC2({apiVersion: '2016-11-15'}); +var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" }); var params = { - DryRun: false + DryRun: false, }; // Call EC2 to retrieve policy for selected bucket -ec2.describeInstances(params, function(err, data) { +ec2.describeInstances(params, function (err, data) { if (err) { console.log("Error", err.stack); } else { diff --git a/javascript/example_code/ec2/ec2_describekeypairs.js b/javascript/example_code/ec2/ec2_describekeypairs.js index bc7dcbc1653..1d6020a62f6 100755 --- a/javascript/example_code/ec2/ec2_describekeypairs.js +++ b/javascript/example_code/ec2/ec2_describekeypairs.js @@ -1,45 +1,24 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ec2_describekeypairs.js demonstrates how to retrieve information about one or more key pairs.] -//snippet-service:[ec2] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ec2-example-key-pairs.html // snippet-start:[ec2.JavaScript.keypairs.describeKeyPair] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create EC2 service object -var ec2 = new AWS.EC2({apiVersion: '2016-11-15'}); +var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" }); // Retrieve key pair descriptions; no params needed -ec2.describeKeyPairs(function(err, data) { - if (err) { - console.log("Error", err); - } else { - console.log("Success", JSON.stringify(data.KeyPairs)); - } +ec2.describeKeyPairs(function (err, data) { + if (err) { + console.log("Error", err); + } else { + console.log("Success", JSON.stringify(data.KeyPairs)); + } }); // snippet-end:[ec2.JavaScript.keypairs.describeKeyPair] diff --git a/javascript/example_code/ec2/ec2_describeregionsandzones.js b/javascript/example_code/ec2/ec2_describeregionsandzones.js index df662fda0b2..94c2dfe29dd 100755 --- a/javascript/example_code/ec2/ec2_describeregionsandzones.js +++ b/javascript/example_code/ec2/ec2_describeregionsandzones.js @@ -1,43 +1,22 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ec2_describeregionsandzones.js demonstrates how to retrieve information about Amazon EC2 regions and availability zones.] -//snippet-service:[ec2] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ec2-example-security-groups.html // snippet-start:[ec2.JavaScript.Regions.describeRegions] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create EC2 service object -var ec2 = new AWS.EC2({apiVersion: '2016-11-15'}); +var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" }); var params = {}; // Retrieves all regions/endpoints that work with EC2 -ec2.describeRegions(params, function(err, data) { +ec2.describeRegions(params, function (err, data) { if (err) { console.log("Error", err); } else { @@ -46,7 +25,7 @@ ec2.describeRegions(params, function(err, data) { }); // Retrieves availability zones only for region of the ec2 service object -ec2.describeAvailabilityZones(params, function(err, data) { +ec2.describeAvailabilityZones(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/ec2/ec2_describesecuritygroups.js b/javascript/example_code/ec2/ec2_describesecuritygroups.js index 9d926e2695a..7547ae633d8 100755 --- a/javascript/example_code/ec2/ec2_describesecuritygroups.js +++ b/javascript/example_code/ec2/ec2_describesecuritygroups.js @@ -1,49 +1,28 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ec2_describesecuritygroups.js demonstrates how to retrieve information about one or more security groups.] -//snippet-service:[ec2] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ec2-example-security-groups.html // snippet-start:[ec2.JavaScript.SecurityGroups.describeSecurityGroups] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create EC2 service object -var ec2 = new AWS.EC2({apiVersion: '2016-11-15'}); +var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" }); var params = { - GroupIds: ['SECURITY_GROUP_ID'] + GroupIds: ["SECURITY_GROUP_ID"], }; // Retrieve security group descriptions -ec2.describeSecurityGroups(params, function(err, data) { - if (err) { - console.log("Error", err); - } else { - console.log("Success", JSON.stringify(data.SecurityGroups)); - } +ec2.describeSecurityGroups(params, function (err, data) { + if (err) { + console.log("Error", err); + } else { + console.log("Success", JSON.stringify(data.SecurityGroups)); + } }); // snippet-end:[ec2.JavaScript.SecurityGroups.describeSecurityGroups] diff --git a/javascript/example_code/ec2/ec2_monitorinstances.js b/javascript/example_code/ec2/ec2_monitorinstances.js index 939d29c4a4a..b96b07f562d 100755 --- a/javascript/example_code/ec2/ec2_monitorinstances.js +++ b/javascript/example_code/ec2/ec2_monitorinstances.js @@ -1,55 +1,34 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ec2_monitorinstances.js demonstrates how to enable detailed monitoring for Amazon EC2 instances.] -//snippet-service:[ec2] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ec2-example-managing-instances.html // snippet-start:[ec2.JavaScript.Instances.monitorInstances] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create EC2 service object -var ec2 = new AWS.EC2({apiVersion: '2016-11-15'}); +var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" }); var params = { - InstanceIds: ['INSTANCE_ID'], - DryRun: true + InstanceIds: ["INSTANCE_ID"], + DryRun: true, }; if (process.argv[2].toUpperCase() === "ON") { // Call EC2 to start monitoring the selected instances - ec2.monitorInstances(params, function(err, data) { - if (err && err.code === 'DryRunOperation') { + ec2.monitorInstances(params, function (err, data) { + if (err && err.code === "DryRunOperation") { params.DryRun = false; - ec2.monitorInstances(params, function(err, data) { - if (err) { - console.log("Error", err); - } else if (data) { - console.log("Success", data.InstanceMonitorings); - } + ec2.monitorInstances(params, function (err, data) { + if (err) { + console.log("Error", err); + } else if (data) { + console.log("Success", data.InstanceMonitorings); + } }); } else { console.log("You don't have permission to change instance monitoring."); @@ -57,15 +36,15 @@ if (process.argv[2].toUpperCase() === "ON") { }); } else if (process.argv[2].toUpperCase() === "OFF") { // Call EC2 to stop monitoring the selected instances - ec2.unmonitorInstances(params, function(err, data) { - if (err && err.code === 'DryRunOperation') { + ec2.unmonitorInstances(params, function (err, data) { + if (err && err.code === "DryRunOperation") { params.DryRun = false; - ec2.unmonitorInstances(params, function(err, data) { - if (err) { - console.log("Error", err); - } else if (data) { - console.log("Success", data.InstanceMonitorings); - } + ec2.unmonitorInstances(params, function (err, data) { + if (err) { + console.log("Error", err); + } else if (data) { + console.log("Success", data.InstanceMonitorings); + } }); } else { console.log("You don't have permission to change instance monitoring."); diff --git a/javascript/example_code/ec2/ec2_rebootinstances.js b/javascript/example_code/ec2/ec2_rebootinstances.js index 8389db7cbb1..bd7e559e0a2 100755 --- a/javascript/example_code/ec2/ec2_rebootinstances.js +++ b/javascript/example_code/ec2/ec2_rebootinstances.js @@ -1,54 +1,33 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ec2_rebootinstances.js demonstrates how to queue a reboot request for one or more Amazon EC2 instances.] -//snippet-service:[ec2] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ec2-example-managing-instances.html // snippet-start:[ec2.JavaScript.Instances.rebootInstances] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create EC2 service object -var ec2 = new AWS.EC2({apiVersion: '2016-11-15'}); +var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" }); var params = { - InstanceIds: ['INSTANCE_ID'], - DryRun: true + InstanceIds: ["INSTANCE_ID"], + DryRun: true, }; // Call EC2 to reboot instances -ec2.rebootInstances(params, function(err, data) { - if (err && err.code === 'DryRunOperation') { +ec2.rebootInstances(params, function (err, data) { + if (err && err.code === "DryRunOperation") { params.DryRun = false; - ec2.rebootInstances(params, function(err, data) { - if (err) { - console.log("Error", err); - } else if (data) { - console.log("Success", data); - } + ec2.rebootInstances(params, function (err, data) { + if (err) { + console.log("Error", err); + } else if (data) { + console.log("Success", data); + } }); } else { console.log("You don't have permission to reboot instances."); diff --git a/javascript/example_code/ec2/ec2_releaseaddress.js b/javascript/example_code/ec2/ec2_releaseaddress.js index 068d4a605e5..1c5138eb31a 100755 --- a/javascript/example_code/ec2/ec2_releaseaddress.js +++ b/javascript/example_code/ec2/ec2_releaseaddress.js @@ -1,49 +1,28 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ec2_releaseaddress.js demonstrates how to release an Elastic IP address.] -//snippet-service:[ec2] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide//ec2-example-elastic-ip-addresses.html // snippet-start:[ec2.JavaScript.Addresses.releaseAddress] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create EC2 service object -var ec2 = new AWS.EC2({apiVersion: '2016-11-15'}); +var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" }); var paramsReleaseAddress = { - AllocationId: 'ALLOCATION_ID' + AllocationId: "ALLOCATION_ID", }; // Disassociate the Elastic IP address from EC2 instance -ec2.releaseAddress(paramsReleaseAddress, function(err, data) { - if (err) { - console.log("Error", err); - } else { - console.log("Address released"); - } +ec2.releaseAddress(paramsReleaseAddress, function (err, data) { + if (err) { + console.log("Error", err); + } else { + console.log("Address released"); + } }); // snippet-end:[ec2.JavaScript.Addresses.releaseAddress] diff --git a/javascript/example_code/ec2/ec2_startstopinstances.js b/javascript/example_code/ec2/ec2_startstopinstances.js index 19971b0a676..518d816bbd9 100755 --- a/javascript/example_code/ec2/ec2_startstopinstances.js +++ b/javascript/example_code/ec2/ec2_startstopinstances.js @@ -1,55 +1,34 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[ec2_startstopinstances.js demonstrates how to start and stop an Amazon EC2 instance that is backed by Amazon Elastic Block Store.] -//snippet-service:[ec2] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EC2] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ec2-example-managing-instances.html // snippet-start:[ec2.JavaScript.Instances.start_stopInstances] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create EC2 service object -var ec2 = new AWS.EC2({apiVersion: '2016-11-15'}); +var ec2 = new AWS.EC2({ apiVersion: "2016-11-15" }); var params = { InstanceIds: [process.argv[3]], - DryRun: true + DryRun: true, }; if (process.argv[2].toUpperCase() === "START") { // Call EC2 to start the selected instances - ec2.startInstances(params, function(err, data) { - if (err && err.code === 'DryRunOperation') { + ec2.startInstances(params, function (err, data) { + if (err && err.code === "DryRunOperation") { params.DryRun = false; - ec2.startInstances(params, function(err, data) { - if (err) { - console.log("Error", err); - } else if (data) { - console.log("Success", data.StartingInstances); - } + ec2.startInstances(params, function (err, data) { + if (err) { + console.log("Error", err); + } else if (data) { + console.log("Success", data.StartingInstances); + } }); } else { console.log("You don't have permission to start instances."); @@ -57,15 +36,15 @@ if (process.argv[2].toUpperCase() === "START") { }); } else if (process.argv[2].toUpperCase() === "STOP") { // Call EC2 to stop the selected instances - ec2.stopInstances(params, function(err, data) { - if (err && err.code === 'DryRunOperation') { + ec2.stopInstances(params, function (err, data) { + if (err && err.code === "DryRunOperation") { params.DryRun = false; - ec2.stopInstances(params, function(err, data) { - if (err) { - console.log("Error", err); - } else if (data) { - console.log("Success", data.StoppingInstances); - } + ec2.stopInstances(params, function (err, data) { + if (err) { + console.log("Error", err); + } else if (data) { + console.log("Success", data.StoppingInstances); + } }); } else { console.log("You don't have permission to stop instances"); diff --git a/javascript/example_code/eventbridge/eb_putevents.js b/javascript/example_code/eventbridge/eb_putevents.js index f59e8cac790..728f5a03b5c 100644 --- a/javascript/example_code/eventbridge/eb_putevents.js +++ b/javascript/example_code/eventbridge/eb_putevents.js @@ -1,41 +1,27 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 - */ - -//snippet-sourcedescription:[eb_putevents.js demonstrates how to send custom events to Amazon EventBridge (formerly Amazon CloudWatch) events so they can be matched with rules.] -//snippet-service:[cw_events] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EventBridge] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[eventBridge.JavaScript.eb.putEvents] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set the region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create CloudWatchEvents service object -var ebevents = new AWS.EventBridge({apiVersion: '2015-10-07'}); +var ebevents = new AWS.EventBridge({ apiVersion: "2015-10-07" }); var params = { Entries: [ { - Detail: '{ \"key1\": \"value1\", \"key2\": \"value2\" }', - DetailType: 'appRequestSubmitted', - Resources: [ - 'RESOURCE_ARN', - ], - Source: 'com.company.app' - } - ] + Detail: '{ "key1": "value1", "key2": "value2" }', + DetailType: "appRequestSubmitted", + Resources: ["RESOURCE_ARN"], + Source: "com.company.app", + }, + ], }; -ebevents.putEvents(params, function(err, data) { +ebevents.putEvents(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/eventbridge/eb_putrule.js b/javascript/example_code/eventbridge/eb_putrule.js index 61244247215..e66c77a15ed 100644 --- a/javascript/example_code/eventbridge/eb_putrule.js +++ b/javascript/example_code/eventbridge/eb_putrule.js @@ -1,34 +1,23 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 - */ - -//snippet-sourcedescription:[eb_putrule.js demonstrates how to create or update an Amazon EventBridge (formerly Amazon CloudWatch) rule.] -//snippet-service:[cw_events] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EventBridge] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[eventBridge.JavaScript.eb.putRule] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set the region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create CloudWatchEvents service object -var ebevents = new AWS.EventBridge({apiVersion: '2015-10-07'}); +var ebevents = new AWS.EventBridge({ apiVersion: "2015-10-07" }); var params = { - Name: 'DEMO_EVENT', - RoleArn: 'IAM_ROLE_ARN', - ScheduleExpression: 'rate(5 minutes)', - State: 'ENABLED' + Name: "DEMO_EVENT", + RoleArn: "IAM_ROLE_ARN", + ScheduleExpression: "rate(5 minutes)", + State: "ENABLED", }; -ebevents.putRule(params, function(err, data) { +ebevents.putRule(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/eventbridge/eb_puttargets.js b/javascript/example_code/eventbridge/eb_puttargets.js index 546e8d7a96e..c06afe25096 100644 --- a/javascript/example_code/eventbridge/eb_puttargets.js +++ b/javascript/example_code/eventbridge/eb_puttargets.js @@ -1,38 +1,26 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 - */ - -//snippet-sourcedescription:[eb_puttargets.js demonstrates how to add or update a target to an Amazon EventBridge (formerly Amazon CloudWatch) rule.] -//snippet-service:[cw_events] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EventBridge] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[eventBridge.JavaScript.eb.putTargets] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set the region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create CloudWatchEvents service object -var ebevents = new AWS.EventBridge({apiVersion: '2015-10-07'}); +var ebevents = new AWS.EventBridge({ apiVersion: "2015-10-07" }); var params = { - Rule: 'DEMO_EVENT', + Rule: "DEMO_EVENT", Targets: [ { - Arn: 'LAMBDA_FUNCTION_ARN', - Id: 'myEventBridgeTarget', - } - ] + Arn: "LAMBDA_FUNCTION_ARN", + Id: "myEventBridgeTarget", + }, + ], }; -ebevents.putTargets(params, function(err, data) { +ebevents.putTargets(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/glacier/createVault.js b/javascript/example_code/glacier/createVault.js index 1840282d155..74ccb6ca61b 100644 --- a/javascript/example_code/glacier/createVault.js +++ b/javascript/example_code/glacier/createVault.js @@ -1,39 +1,18 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[createVault.js demonstrates how to create a vault in Amazon S3 Glacier] -// snippet-service:[glacier] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon S3 Glacier] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[] -// snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[glacier.JavaScript.vault.createVault] // Load the SDK for JavaScript -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create a new service object -var glacier = new AWS.Glacier({apiVersion: '2012-06-01'}); +var glacier = new AWS.Glacier({ apiVersion: "2012-06-01" }); // Call Glacier to create the vault -glacier.createVault({vaultName: 'YOUR_VAULT_NAME'}, function(err) { +glacier.createVault({ vaultName: "YOUR_VAULT_NAME" }, function (err) { if (!err) { - console.log("Created vault!") + console.log("Created vault!"); } }); // snippet-end:[glacier.JavaScript.vault.createVault] diff --git a/javascript/example_code/glacier/initiateMultipartUpload.js b/javascript/example_code/glacier/initiateMultipartUpload.js index 5cbafa17f1a..0d91be8da45 100644 --- a/javascript/example_code/glacier/initiateMultipartUpload.js +++ b/javascript/example_code/glacier/initiateMultipartUpload.js @@ -1,85 +1,67 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[initiateMultipartUpload.js demonstrates how to create a multipart upload out of 1 megabyte chunks of a Buffer object] -// snippet-service:[glacier] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon S3 Glacier] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[] -// snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[glacier.JavaScript.multipartUpload.initiateMultipartUpload] // Create a new service object and some supporting variables -var glacier = new AWS.Glacier({apiVersion: '2012-06-01'}), - vaultName = 'YOUR_VAULT_NAME', - buffer = new Buffer(2.5 * 1024 * 1024), // 2.5MB buffer - partSize = 1024 * 1024, // 1MB chunks, - numPartsLeft = Math.ceil(buffer.length / partSize), - startTime = new Date(), - params = {vaultName: vaultName, partSize: partSize.toString()}; +var glacier = new AWS.Glacier({ apiVersion: "2012-06-01" }), + vaultName = "YOUR_VAULT_NAME", + buffer = new Buffer(2.5 * 1024 * 1024), // 2.5MB buffer + partSize = 1024 * 1024, // 1MB chunks, + numPartsLeft = Math.ceil(buffer.length / partSize), + startTime = new Date(), + params = { vaultName: vaultName, partSize: partSize.toString() }; // Compute the complete SHA-256 tree hash so we can pass it // to completeMultipartUpload request at the end var treeHash = glacier.computeChecksums(buffer).treeHash; // Initiate the multipart upload -console.log('Initiating upload to', vaultName); +console.log("Initiating upload to", vaultName); // Call Glacier to initiate the upload. glacier.initiateMultipartUpload(params, function (mpErr, multipart) { - if (mpErr) { console.log('Error!', mpErr.stack); return; } - console.log("Got upload ID", multipart.uploadId); + if (mpErr) { + console.log("Error!", mpErr.stack); + return; + } + console.log("Got upload ID", multipart.uploadId); - // Grab each partSize chunk and upload it as a part - for (var i = 0; i < buffer.length; i += partSize) { - var end = Math.min(i + partSize, buffer.length), - partParams = { - vaultName: vaultName, - uploadId: multipart.uploadId, - range: 'bytes ' + i + '-' + (end-1) + '/*', - body: buffer.slice(i, end) - }; + // Grab each partSize chunk and upload it as a part + for (var i = 0; i < buffer.length; i += partSize) { + var end = Math.min(i + partSize, buffer.length), + partParams = { + vaultName: vaultName, + uploadId: multipart.uploadId, + range: "bytes " + i + "-" + (end - 1) + "/*", + body: buffer.slice(i, end), + }; - // Send a single part - console.log('Uploading part', i, '=', partParams.range); - glacier.uploadMultipartPart(partParams, function(multiErr, mData) { - if (multiErr) return; - console.log("Completed part", this.request.params.range); - if (--numPartsLeft > 0) return; // complete only when all parts uploaded + // Send a single part + console.log("Uploading part", i, "=", partParams.range); + glacier.uploadMultipartPart(partParams, function (multiErr, mData) { + if (multiErr) return; + console.log("Completed part", this.request.params.range); + if (--numPartsLeft > 0) return; // complete only when all parts uploaded - var doneParams = { - vaultName: vaultName, - uploadId: multipart.uploadId, - archiveSize: buffer.length.toString(), - checksum: treeHash // the computed tree hash - }; + var doneParams = { + vaultName: vaultName, + uploadId: multipart.uploadId, + archiveSize: buffer.length.toString(), + checksum: treeHash, // the computed tree hash + }; - console.log("Completing upload..."); - glacier.completeMultipartUpload(doneParams, function(err, data) { - if (err) { - console.log("An error occurred while uploading the archive"); - console.log(err); - } else { - var delta = (new Date() - startTime) / 1000; - console.log('Completed upload in', delta, 'seconds'); - console.log('Archive ID:', data.archiveId); - console.log('Checksum: ', data.checksum); - } - }); - }); - } + console.log("Completing upload..."); + glacier.completeMultipartUpload(doneParams, function (err, data) { + if (err) { + console.log("An error occurred while uploading the archive"); + console.log(err); + } else { + var delta = (new Date() - startTime) / 1000; + console.log("Completed upload in", delta, "seconds"); + console.log("Archive ID:", data.archiveId); + console.log("Checksum: ", data.checksum); + } + }); + }); + } }); // snippet-end:[glacier.JavaScript.multipartUpload.initiateMultipartUpload] diff --git a/javascript/example_code/glacier/uploadArchive.js b/javascript/example_code/glacier/uploadArchive.js index 0f34ad5458f..40167dbeb0c 100644 --- a/javascript/example_code/glacier/uploadArchive.js +++ b/javascript/example_code/glacier/uploadArchive.js @@ -1,40 +1,19 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[uploadArchive.js demonstrates how to upload an archive to Amazon S3 Glacier] -// snippet-service:[glacier] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon S3 Glacier] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[] -// snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[glacier.JavaScript.upload.uploadArchive] // Load the SDK for JavaScript -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set the region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create a new service object and buffer -var glacier = new AWS.Glacier({apiVersion: '2012-06-01'}); +var glacier = new AWS.Glacier({ apiVersion: "2012-06-01" }); buffer = Buffer.alloc(2.5 * 1024 * 1024); // 2.5MB buffer -var params = {vaultName: 'YOUR_VAULT_NAME', body: buffer}; +var params = { vaultName: "YOUR_VAULT_NAME", body: buffer }; // Call Glacier to upload the archive. -glacier.uploadArchive(params, function(err, data) { +glacier.uploadArchive(params, function (err, data) { if (err) { console.log("Error uploading archive!", err); } else { diff --git a/javascript/example_code/iam/iam_accesskeylastused.js b/javascript/example_code/iam/iam_accesskeylastused.js index 64727a2f2c6..88cc2ce6de2 100755 --- a/javascript/example_code/iam/iam_accesskeylastused.js +++ b/javascript/example_code/iam/iam_accesskeylastused.js @@ -1,45 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[iam_accesskeylastused.js demonstrates how to retrieve information about the last time an IAM access key was used.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-access-keys.html // snippet-start:[iam.JavaScript.keys.getAccessKeyLastUsed] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the IAM service object -var iam = new AWS.IAM({apiVersion: '2010-05-08'}); +var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); -iam.getAccessKeyLastUsed({AccessKeyId: 'ACCESS_KEY_ID'}, function(err, data) { - if (err) { - console.log("Error", err); - } else { - console.log("Success", data.AccessKeyLastUsed); +iam.getAccessKeyLastUsed( + { AccessKeyId: "ACCESS_KEY_ID" }, + function (err, data) { + if (err) { + console.log("Error", err); + } else { + console.log("Success", data.AccessKeyLastUsed); + } } -}); +); // snippet-end:[iam.JavaScript.keys.getAccessKeyLastUsed] diff --git a/javascript/example_code/iam/iam_attachrolepolicy.js b/javascript/example_code/iam/iam_attachrolepolicy.js index eb39f0200c9..cf3f017865e 100755 --- a/javascript/example_code/iam/iam_attachrolepolicy.js +++ b/javascript/example_code/iam/iam_attachrolepolicy.js @@ -1,60 +1,40 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[iam_attachrolepolicy.js demonstrates how to attach a managed policy to an IAM role.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-policies.html // snippet-start:[iam.JavaScript.policies.attachRolePolicy] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the IAM service object -var iam = new AWS.IAM({apiVersion: '2010-05-08'}); +var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var paramsRoleList = { - RoleName: process.argv[2] + RoleName: process.argv[2], }; -iam.listAttachedRolePolicies(paramsRoleList, function(err, data) { +iam.listAttachedRolePolicies(paramsRoleList, function (err, data) { if (err) { console.log("Error", err); } else { var myRolePolicies = data.AttachedPolicies; myRolePolicies.forEach(function (val, index, array) { - if (myRolePolicies[index].PolicyName === 'AmazonDynamoDBFullAccess') { - console.log("AmazonDynamoDBFullAccess is already attached to this role.") + if (myRolePolicies[index].PolicyName === "AmazonDynamoDBFullAccess") { + console.log( + "AmazonDynamoDBFullAccess is already attached to this role." + ); process.exit(); } }); var params = { - PolicyArn: 'arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess', - RoleName: process.argv[2] + PolicyArn: "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess", + RoleName: process.argv[2], }; - iam.attachRolePolicy(params, function(err, data) { + iam.attachRolePolicy(params, function (err, data) { if (err) { console.log("Unable to attach policy to role", err); } else { diff --git a/javascript/example_code/iam/iam_createaccesskeys.js b/javascript/example_code/iam/iam_createaccesskeys.js index 52ae929c921..1b0db4c3b17 100755 --- a/javascript/example_code/iam/iam_createaccesskeys.js +++ b/javascript/example_code/iam/iam_createaccesskeys.js @@ -1,41 +1,19 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[iam_createaccesskeys.js demonstrates how to create a new AWS access key and AWS access key ID for an IAM user.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-access-keys.html // snippet-start:[iam.JavaScript.keys.createAccessKey] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the IAM service object -var iam = new AWS.IAM({apiVersion: '2010-05-08'}); +var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); -iam.createAccessKey({UserName: 'IAM_USER_NAME'}, function(err, data) { +iam.createAccessKey({ UserName: "IAM_USER_NAME" }, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/iam/iam_createaccountalias.js b/javascript/example_code/iam/iam_createaccountalias.js index d388f0e0bf0..88374053653 100755 --- a/javascript/example_code/iam/iam_createaccountalias.js +++ b/javascript/example_code/iam/iam_createaccountalias.js @@ -1,41 +1,19 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[iam_createaccountalias.js demonstrates how to create an alias for an AWS account.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-account-aliases.html // snippet-start:[iam.JavaScript.alias.createAccountAlias] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the IAM service object -var iam = new AWS.IAM({apiVersion: '2010-05-08'}); +var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); -iam.createAccountAlias({AccountAlias: process.argv[2]}, function(err, data) { +iam.createAccountAlias({ AccountAlias: process.argv[2] }, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/iam/iam_createpolicy.js b/javascript/example_code/iam/iam_createpolicy.js index 8f266ee4f86..cc5afaf739f 100755 --- a/javascript/example_code/iam/iam_createpolicy.js +++ b/javascript/example_code/iam/iam_createpolicy.js @@ -1,68 +1,46 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[iam_createpolicy.js demonstrates how to create a managed policy for an AWS account.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-policies.html // snippet-start:[iam.JavaScript.policies.createPolicy] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the IAM service object -var iam = new AWS.IAM({apiVersion: '2010-05-08'}); +var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var myManagedPolicy = { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Action": "logs:CreateLogGroup", - "Resource": "RESOURCE_ARN" - }, - { - "Effect": "Allow", - "Action": [ - "dynamodb:DeleteItem", - "dynamodb:GetItem", - "dynamodb:PutItem", - "dynamodb:Scan", - "dynamodb:UpdateItem" - ], - "Resource": "RESOURCE_ARN" - } - ] + Version: "2012-10-17", + Statement: [ + { + Effect: "Allow", + Action: "logs:CreateLogGroup", + Resource: "RESOURCE_ARN", + }, + { + Effect: "Allow", + Action: [ + "dynamodb:DeleteItem", + "dynamodb:GetItem", + "dynamodb:PutItem", + "dynamodb:Scan", + "dynamodb:UpdateItem", + ], + Resource: "RESOURCE_ARN", + }, + ], }; var params = { PolicyDocument: JSON.stringify(myManagedPolicy), - PolicyName: 'myDynamoDBPolicy', + PolicyName: "myDynamoDBPolicy", }; -iam.createPolicy(params, function(err, data) { +iam.createPolicy(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/iam/iam_createuser.js b/javascript/example_code/iam/iam_createuser.js index cd7a6a985c1..fead8234646 100755 --- a/javascript/example_code/iam/iam_createuser.js +++ b/javascript/example_code/iam/iam_createuser.js @@ -1,47 +1,25 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[iam_createuser.js demonstrates how to create an IAM user for an AWS account.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-users.html // snippet-start:[iam.JavaScript.users.getUser] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the IAM service object -var iam = new AWS.IAM({apiVersion: '2010-05-08'}); +var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var params = { - UserName: process.argv[2] + UserName: process.argv[2], }; -iam.getUser(params, function(err, data) { - if (err && err.code === 'NoSuchEntity') { - iam.createUser(params, function(err, data) { +iam.getUser(params, function (err, data) { + if (err && err.code === "NoSuchEntity") { + iam.createUser(params, function (err, data) { if (err) { console.log("Error", err); } else { @@ -49,7 +27,10 @@ iam.getUser(params, function(err, data) { } }); } else { - console.log("User " + process.argv[2] + " already exists", data.User.UserId); + console.log( + "User " + process.argv[2] + " already exists", + data.User.UserId + ); } }); // snippet-end:[iam.JavaScript.users.getUser] diff --git a/javascript/example_code/iam/iam_deleteaccesskey.js b/javascript/example_code/iam/iam_deleteaccesskey.js index 95020ce941b..156e6d9f229 100755 --- a/javascript/example_code/iam/iam_deleteaccesskey.js +++ b/javascript/example_code/iam/iam_deleteaccesskey.js @@ -1,46 +1,24 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[iam_deleteaccesskey.js demonstrates how to delete the AWS access key pair for an IAM user.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-access-keys.html // snippet-start:[iam.JavaScript.keys.deleteAccessKey] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the IAM service object -var iam = new AWS.IAM({apiVersion: '2010-05-08'}); +var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var params = { - AccessKeyId: 'ACCESS_KEY_ID', - UserName: 'USER_NAME' + AccessKeyId: "ACCESS_KEY_ID", + UserName: "USER_NAME", }; -iam.deleteAccessKey(params, function(err, data) { +iam.deleteAccessKey(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/iam/iam_deleteaccountalias.js b/javascript/example_code/iam/iam_deleteaccountalias.js index 9b05425cf8c..6498b4969a6 100755 --- a/javascript/example_code/iam/iam_deleteaccountalias.js +++ b/javascript/example_code/iam/iam_deleteaccountalias.js @@ -1,41 +1,19 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[iam_deleteaccountalias.js demonstrates how to delete an alias for an AWS account.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-account-aliases.html // snippet-start:[iam.JavaScript.alias.deleteAccountAlias] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the IAM service object -var iam = new AWS.IAM({apiVersion: '2010-05-08'}); +var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); -iam.deleteAccountAlias({AccountAlias: process.argv[2]}, function(err, data) { +iam.deleteAccountAlias({ AccountAlias: process.argv[2] }, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/iam/iam_deleteservercert.js b/javascript/example_code/iam/iam_deleteservercert.js index 578f821d109..56ac08fcb91 100755 --- a/javascript/example_code/iam/iam_deleteservercert.js +++ b/javascript/example_code/iam/iam_deleteservercert.js @@ -1,45 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[iam_deleteservercert.js demonstrates how to delete an IAM SSL/TLS server certificate.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-server-certificates.html // snippet-start:[iam.JavaScript.certs.deleteServerCertificate] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the IAM service object -var iam = new AWS.IAM({apiVersion: '2010-05-08'}); +var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); -iam.deleteServerCertificate({ServerCertificateName: 'CERTIFICATE_NAME'}, function(err, data) { - if (err) { - console.log("Error", err); - } else { - console.log("Success", data); +iam.deleteServerCertificate( + { ServerCertificateName: "CERTIFICATE_NAME" }, + function (err, data) { + if (err) { + console.log("Error", err); + } else { + console.log("Success", data); + } } -}); +); // snippet-end:[iam.JavaScript.certs.deleteServerCertificate] diff --git a/javascript/example_code/iam/iam_deleteuser.js b/javascript/example_code/iam/iam_deleteuser.js index bcc5707501b..58f38e1c348 100755 --- a/javascript/example_code/iam/iam_deleteuser.js +++ b/javascript/example_code/iam/iam_deleteuser.js @@ -1,49 +1,27 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[iam_deleteuser.js demonstrates how to delete an IAM user from an AWS account.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-users.html // snippet-start:[iam.JavaScript.users.deleteUser] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the IAM service object -var iam = new AWS.IAM({apiVersion: '2010-05-08'}); +var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var params = { - UserName: process.argv[2] + UserName: process.argv[2], }; -iam.getUser(params, function(err, data) { - if (err && err.code === 'NoSuchEntity') { +iam.getUser(params, function (err, data) { + if (err && err.code === "NoSuchEntity") { console.log("User " + process.argv[2] + " does not exist."); } else { - iam.deleteUser(params, function(err, data) { + iam.deleteUser(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/iam/iam_detachrolepolicy.js b/javascript/example_code/iam/iam_detachrolepolicy.js index 3612b83f762..cfa7acc4aa1 100755 --- a/javascript/example_code/iam/iam_detachrolepolicy.js +++ b/javascript/example_code/iam/iam_detachrolepolicy.js @@ -1,56 +1,34 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[iam_detachrolepolicy.js demonstrates how to detach a managed policy from an IAM role.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-policies.html // snippet-start:[iam.JavaScript.policies.detachRolePolicy] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the IAM service object -var iam = new AWS.IAM({apiVersion: '2010-05-08'}); +var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var paramsRoleList = { - RoleName: process.argv[2] + RoleName: process.argv[2], }; -iam.listAttachedRolePolicies(paramsRoleList, function(err, data) { +iam.listAttachedRolePolicies(paramsRoleList, function (err, data) { if (err) { console.log("Error", err); } else { var myRolePolicies = data.AttachedPolicies; myRolePolicies.forEach(function (val, index, array) { - if (myRolePolicies[index].PolicyName === 'AmazonDynamoDBFullAccess') { + if (myRolePolicies[index].PolicyName === "AmazonDynamoDBFullAccess") { var params = { - PolicyArn: 'arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess', - RoleName: process.argv[2] + PolicyArn: "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess", + RoleName: process.argv[2], }; - iam.detachRolePolicy(params, function(err, data) { + iam.detachRolePolicy(params, function (err, data) { if (err) { console.log("Unable to detach policy from role", err); } else { diff --git a/javascript/example_code/iam/iam_getpolicy.js b/javascript/example_code/iam/iam_getpolicy.js index 2a39074349e..05fc7d3c7dc 100755 --- a/javascript/example_code/iam/iam_getpolicy.js +++ b/javascript/example_code/iam/iam_getpolicy.js @@ -1,45 +1,23 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[iam_getpolicy.js demonstrates how to retrieve information about an IAM managed policy.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-policies.html // snippet-start:[iam.JavaScript.policies.getPolicy] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the IAM service object -var iam = new AWS.IAM({apiVersion: '2010-05-08'}); +var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var params = { - PolicyArn: 'arn:aws:iam::aws:policy/AWSLambdaExecute' + PolicyArn: "arn:aws:iam::aws:policy/AWSLambdaExecute", }; -iam.getPolicy(params, function(err, data) { +iam.getPolicy(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/iam/iam_getservercert.js b/javascript/example_code/iam/iam_getservercert.js index 60d696a63a3..2ba58d169a6 100755 --- a/javascript/example_code/iam/iam_getservercert.js +++ b/javascript/example_code/iam/iam_getservercert.js @@ -1,45 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[iam_getservercert.js demonstrates how to retrieve information about an IAM SSL/TLS server certificate.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-server-certificates.html // snippet-start:[iam.JavaScript.certs.getServerCertificate] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the IAM service object -var iam = new AWS.IAM({apiVersion: '2010-05-08'}); +var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); -iam.getServerCertificate({ServerCertificateName: 'CERTIFICATE_NAME'}, function(err, data) { - if (err) { - console.log("Error", err); - } else { - console.log("Success", data); +iam.getServerCertificate( + { ServerCertificateName: "CERTIFICATE_NAME" }, + function (err, data) { + if (err) { + console.log("Error", err); + } else { + console.log("Success", data); + } } -}); +); // snippet-end:[iam.JavaScript.certs.getServerCertificate] diff --git a/javascript/example_code/iam/iam_listaccesskeys.js b/javascript/example_code/iam/iam_listaccesskeys.js index bbf917b2f58..f7c24c8bc13 100755 --- a/javascript/example_code/iam/iam_listaccesskeys.js +++ b/javascript/example_code/iam/iam_listaccesskeys.js @@ -1,46 +1,24 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[iam_listaccesskeys.js demonstrates how to retrieve information about the access keys of an IAM user.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-access-keys.html // snippet-start:[iam.JavaScript.keys.listAccessKeys] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the IAM service object -var iam = new AWS.IAM({apiVersion: '2010-05-08'}); +var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var params = { MaxItems: 5, - UserName: 'IAM_USER_NAME' + UserName: "IAM_USER_NAME", }; -iam.listAccessKeys(params, function(err, data) { +iam.listAccessKeys(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/iam/iam_listaccountaliases.js b/javascript/example_code/iam/iam_listaccountaliases.js index 3bedbc5f16e..e5577cd3266 100755 --- a/javascript/example_code/iam/iam_listaccountaliases.js +++ b/javascript/example_code/iam/iam_listaccountaliases.js @@ -1,41 +1,19 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[iam_listaccountaliases.js demonstrates how to retrieve information about the aliases for an AWS account.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-account-aliases.html // snippet-start:[iam.JavaScript.alias.listAccountAliases] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the IAM service object -var iam = new AWS.IAM({apiVersion: '2010-05-08'}); +var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); -iam.listAccountAliases({MaxItems: 10}, function(err, data) { +iam.listAccountAliases({ MaxItems: 10 }, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/iam/iam_listservercerts.js b/javascript/example_code/iam/iam_listservercerts.js index 10963a96c31..6c2a7294fcb 100755 --- a/javascript/example_code/iam/iam_listservercerts.js +++ b/javascript/example_code/iam/iam_listservercerts.js @@ -1,41 +1,19 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[iam_listservercerts.js demonstrates how to list the IAM SSL/TLS server certificates.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-server-certificates.html // snippet-start:[iam.JavaScript.certs.listServerCertificates] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the IAM service object -var iam = new AWS.IAM({apiVersion: '2010-05-08'}); +var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); -iam.listServerCertificates({}, function(err, data) { +iam.listServerCertificates({}, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/iam/iam_listusers.js b/javascript/example_code/iam/iam_listusers.js index 90b42e133f5..990edb93ad9 100755 --- a/javascript/example_code/iam/iam_listusers.js +++ b/javascript/example_code/iam/iam_listusers.js @@ -1,50 +1,28 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[iam_listusers.js demonstrates how to list IAM users.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-users.html // snippet-start:[iam.JavaScript.users.listUsers] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the IAM service object -var iam = new AWS.IAM({apiVersion: '2010-05-08'}); +var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var params = { - MaxItems: 10 + MaxItems: 10, }; -iam.listUsers(params, function(err, data) { +iam.listUsers(params, function (err, data) { if (err) { console.log("Error", err); } else { var users = data.Users || []; - users.forEach(function(user) { + users.forEach(function (user) { console.log("User " + user.UserName + " created", user.CreateDate); }); } diff --git a/javascript/example_code/iam/iam_updateaccesskey.js b/javascript/example_code/iam/iam_updateaccesskey.js index a1ac657bb65..0724dbc89de 100755 --- a/javascript/example_code/iam/iam_updateaccesskey.js +++ b/javascript/example_code/iam/iam_updateaccesskey.js @@ -1,47 +1,25 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[iam_updateaccesskey.js demonstrates how to update the status of an IAM user's access key.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-access-keys.html // snippet-start:[iam.JavaScript.keys.updateAccessKey] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the IAM service object -var iam = new AWS.IAM({apiVersion: '2010-05-08'}); +var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var params = { - AccessKeyId: 'ACCESS_KEY_ID', - Status: 'Active', - UserName: 'USER_NAME' + AccessKeyId: "ACCESS_KEY_ID", + Status: "Active", + UserName: "USER_NAME", }; -iam.updateAccessKey(params, function(err, data) { +iam.updateAccessKey(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/iam/iam_updateservercert.js b/javascript/example_code/iam/iam_updateservercert.js index a70429bbbfc..ce90afdf631 100755 --- a/javascript/example_code/iam/iam_updateservercert.js +++ b/javascript/example_code/iam/iam_updateservercert.js @@ -1,46 +1,24 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[iam_updateservercert.js demonstrates how to update the name of an IAM SSL/TLS server certificate.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-server-certificates.html // snippet-start:[iam.JavaScript.certs.updateServerCertificate] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the IAM service object -var iam = new AWS.IAM({apiVersion: '2010-05-08'}); +var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var params = { - ServerCertificateName: 'CERTIFICATE_NAME', - NewServerCertificateName: 'NEW_CERTIFICATE_NAME' + ServerCertificateName: "CERTIFICATE_NAME", + NewServerCertificateName: "NEW_CERTIFICATE_NAME", }; -iam.updateServerCertificate(params, function(err, data) { +iam.updateServerCertificate(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/iam/iam_updateuser.js b/javascript/example_code/iam/iam_updateuser.js index b0c61aa64c8..a211460b22d 100755 --- a/javascript/example_code/iam/iam_updateuser.js +++ b/javascript/example_code/iam/iam_updateuser.js @@ -1,46 +1,24 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[iam_updateuser.js demonstrates how to update the name of an IAM user.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Identity and Access Management (IAM)] -//snippet-service:[iam] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-users.html // snippet-start:[iam.JavaScript.users.updateUser] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the IAM service object -var iam = new AWS.IAM({apiVersion: '2010-05-08'}); +var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var params = { UserName: process.argv[2], - NewUserName: process.argv[3] + NewUserName: process.argv[3], }; -iam.updateUser(params, function(err, data) { +iam.updateUser(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/kinesis/kinesis-example.js b/javascript/example_code/kinesis/kinesis-example.js index 3dc75c31421..65f6b6f521c 100644 --- a/javascript/example_code/kinesis/kinesis-example.js +++ b/javascript/example_code/kinesis/kinesis-example.js @@ -1,28 +1,5 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[kinesis-example.js demonstrates how to capture web page scroll progress] -// snippet-service:[kinesis] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Kinesis] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[] -// snippet-sourceauthor:[AWS_JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/kinesis-examples-capturing-page-scrolling-full.html @@ -31,79 +8,84 @@ // snippet-start:[kinesis.JavaScript.kinesis-example.config] // Configure Credentials to use Cognito AWS.config.credentials = new AWS.CognitoIdentityCredentials({ - IdentityPoolId: 'IDENTITY_POOL_ID' + IdentityPoolId: "IDENTITY_POOL_ID", }); -AWS.config.region = 'REGION'; +AWS.config.region = "REGION"; // We're going to partition Amazon Kinesis records based on an identity. // We need to get credentials first, then attach our event listeners. -AWS.config.credentials.get(function(err) { - // attach event listener - if (err) { - alert('Error retrieving credentials.'); - console.error(err); - return; - } - // create Amazon Kinesis service object - var kinesis = new AWS.Kinesis({ - apiVersion: '2013-12-02' - }); - // snippet-end:[kinesis.JavaScript.kinesis-example.config] +AWS.config.credentials.get(function (err) { + // attach event listener + if (err) { + alert("Error retrieving credentials."); + console.error(err); + return; + } + // create Amazon Kinesis service object + var kinesis = new AWS.Kinesis({ + apiVersion: "2013-12-02", + }); + // snippet-end:[kinesis.JavaScript.kinesis-example.config] - // snippet-start:[kinesis.JavaScript.kinesis-example.addEventListener] - // Get the ID of the Web page element. - var blogContent = document.getElementById('BlogContent'); + // snippet-start:[kinesis.JavaScript.kinesis-example.addEventListener] + // Get the ID of the Web page element. + var blogContent = document.getElementById("BlogContent"); - // Get Scrollable height - var scrollableHeight = blogContent.clientHeight; + // Get Scrollable height + var scrollableHeight = blogContent.clientHeight; - var recordData = []; - var TID = null; - blogContent.addEventListener('scroll', function(event) { - clearTimeout(TID); - // Prevent creating a record while a user is actively scrolling - TID = setTimeout(function() { - // calculate percentage - var scrollableElement = event.target; - var scrollHeight = scrollableElement.scrollHeight; - var scrollTop = scrollableElement.scrollTop; + var recordData = []; + var TID = null; + blogContent.addEventListener("scroll", function (event) { + clearTimeout(TID); + // Prevent creating a record while a user is actively scrolling + TID = setTimeout(function () { + // calculate percentage + var scrollableElement = event.target; + var scrollHeight = scrollableElement.scrollHeight; + var scrollTop = scrollableElement.scrollTop; - var scrollTopPercentage = Math.round((scrollTop / scrollHeight) * 100); - var scrollBottomPercentage = Math.round(((scrollTop + scrollableHeight) / scrollHeight) * 100); + var scrollTopPercentage = Math.round((scrollTop / scrollHeight) * 100); + var scrollBottomPercentage = Math.round( + ((scrollTop + scrollableHeight) / scrollHeight) * 100 + ); - // Create the Amazon Kinesis record - var record = { - Data: JSON.stringify({ - blog: window.location.href, - scrollTopPercentage: scrollTopPercentage, - scrollBottomPercentage: scrollBottomPercentage, - time: new Date() - }), - PartitionKey: 'partition-' + AWS.config.credentials.identityId - }; - recordData.push(record); - }, 100); - }); - // snippet-end:[kinesis.JavaScript.kinesis-example.addEventListener] + // Create the Amazon Kinesis record + var record = { + Data: JSON.stringify({ + blog: window.location.href, + scrollTopPercentage: scrollTopPercentage, + scrollBottomPercentage: scrollBottomPercentage, + time: new Date(), + }), + PartitionKey: "partition-" + AWS.config.credentials.identityId, + }; + recordData.push(record); + }, 100); + }); + // snippet-end:[kinesis.JavaScript.kinesis-example.addEventListener] - // snippet-start:[kinesis.JavaScript.kinesis-example.putRecords] - // upload data to Amazon Kinesis every second if data exists - setInterval(function() { - if (!recordData.length) { - return; + // snippet-start:[kinesis.JavaScript.kinesis-example.putRecords] + // upload data to Amazon Kinesis every second if data exists + setInterval(function () { + if (!recordData.length) { + return; + } + // upload data to Amazon Kinesis + kinesis.putRecords( + { + Records: recordData, + StreamName: "NAME_OF_STREAM", + }, + function (err, data) { + if (err) { + console.error(err); } - // upload data to Amazon Kinesis - kinesis.putRecords({ - Records: recordData, - StreamName: 'NAME_OF_STREAM' - }, function(err, data) { - if (err) { - console.error(err); - } - }); - // clear record data - recordData = []; - }, 1000); + } + ); + // clear record data + recordData = []; + }, 1000); }); // snippet-end:[kinesis.JavaScript.kinesis-example.putRecords] -// snippet-end:[kinesis.JavaScript.kinesis-example.complete] \ No newline at end of file +// snippet-end:[kinesis.JavaScript.kinesis-example.complete] diff --git a/javascript/example_code/lambda/lambda-for-browser/index.js b/javascript/example_code/lambda/lambda-for-browser/index.js index 2a2a94fc7ab..217703db02f 100644 --- a/javascript/example_code/lambda/lambda-for-browser/index.js +++ b/javascript/example_code/lambda/lambda-for-browser/index.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with AWS SDK for JavaScript version 3 (lambda-for-browser). // Purpose: diff --git a/javascript/example_code/lambda/lambda-for-browser/main.js b/javascript/example_code/lambda/lambda-for-browser/main.js index eecc01fcfd6..0664772fdac 100644 --- a/javascript/example_code/lambda/lambda-for-browser/main.js +++ b/javascript/example_code/lambda/lambda-for-browser/main.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with AWS SDK for JavaScript version 3 (lambda-for-browser). // Purpose: diff --git a/javascript/example_code/lambda/writeLambdaFunction.js b/javascript/example_code/lambda/writeLambdaFunction.js index 05e21e5012a..55ca5fb63a1 100644 --- a/javascript/example_code/lambda/writeLambdaFunction.js +++ b/javascript/example_code/lambda/writeLambdaFunction.js @@ -1,28 +1,5 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[writeLambdaFunction.js demonstrates how to write a Lambda function code] -// snippet-service:[lambda] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[AWS Lambda] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[] -// snippet-sourceauthor:[AWS_JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/nodejs-write-lambda-function-example-full.html @@ -32,58 +9,75 @@ // snippet-start:[lambda.JavaScript.writeLambdaFunction.complete] // Configuring the AWS SDK -var AWS = require('aws-sdk'); -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +AWS.config.update({ region: "REGION" }); exports.handler = (event, context, callback) => { + const URL_BASE = "S3_BUCKET_URL"; -const URL_BASE = "S3_BUCKET_URL"; - -// Define the object that will hold the data values returned -var slotResults = { - 'isWinner' : false, - 'leftWheelImage' : {'file' : {S: ''}}, - 'middleWheelImage' : {'file' : {S: ''}}, - 'rightWheelImage' : {'file' : {S: ''}} -}; - -// define parameters JSON for retrieving slot pull data from the database -var thisPullParams = { - Key : {'slotPosition' : {N: ''}}, - TableName: 'slotWheels', - ProjectionExpression: 'imageFile' -}; + // Define the object that will hold the data values returned + var slotResults = { + isWinner: false, + leftWheelImage: { file: { S: "" } }, + middleWheelImage: { file: { S: "" } }, + rightWheelImage: { file: { S: "" } }, + }; -// create DynamoDB service object -var request = new AWS.DynamoDB({region: 'REGION', apiVersion: '2012-08-10'}); + // define parameters JSON for retrieving slot pull data from the database + var thisPullParams = { + Key: { slotPosition: { N: "" } }, + TableName: "slotWheels", + ProjectionExpression: "imageFile", + }; -// set a random number 0-9 for the slot position -thisPullParams.Key.slotPosition.N = Math.floor(Math.random()*15).toString(); -// call DynamoDB to retrieve the image to use for the Left slot result -var myLeftPromise = request.getItem(thisPullParams).promise().then(function(data) {return URL_BASE + data.Item.imageFile.S}); + // create DynamoDB service object + var request = new AWS.DynamoDB({ + region: "REGION", + apiVersion: "2012-08-10", + }); -// set a random number 0-9 for the slot position -thisPullParams.Key.slotPosition.N = Math.floor(Math.random()*15).toString(); -// call DynamoDB to retrieve the image to use for the Left slot result -var myMiddlePromise = request.getItem(thisPullParams).promise().then(function(data) {return URL_BASE + data.Item.imageFile.S}); + // set a random number 0-9 for the slot position + thisPullParams.Key.slotPosition.N = Math.floor(Math.random() * 15).toString(); + // call DynamoDB to retrieve the image to use for the Left slot result + var myLeftPromise = request + .getItem(thisPullParams) + .promise() + .then(function (data) { + return URL_BASE + data.Item.imageFile.S; + }); -// set a random number 0-9 for the slot position -thisPullParams.Key.slotPosition.N = Math.floor(Math.random()*15).toString(); -// call DynamoDB to retrieve the image to use for the Left slot result -var myRightPromise = request.getItem(thisPullParams).promise().then(function(data) {return URL_BASE + data.Item.imageFile.S}); + // set a random number 0-9 for the slot position + thisPullParams.Key.slotPosition.N = Math.floor(Math.random() * 15).toString(); + // call DynamoDB to retrieve the image to use for the Left slot result + var myMiddlePromise = request + .getItem(thisPullParams) + .promise() + .then(function (data) { + return URL_BASE + data.Item.imageFile.S; + }); + // set a random number 0-9 for the slot position + thisPullParams.Key.slotPosition.N = Math.floor(Math.random() * 15).toString(); + // call DynamoDB to retrieve the image to use for the Left slot result + var myRightPromise = request + .getItem(thisPullParams) + .promise() + .then(function (data) { + return URL_BASE + data.Item.imageFile.S; + }); -Promise.all([myLeftPromise, myMiddlePromise, myRightPromise]).then(function(values) { + Promise.all([myLeftPromise, myMiddlePromise, myRightPromise]).then(function ( + values + ) { slotResults.leftWheelImage.file.S = values[0]; slotResults.middleWheelImage.file.S = values[1]; slotResults.rightWheelImage.file.S = values[2]; // if all three values are identical, the spin is a winner - if ((values[0] === values[1]) && (values[0] === values[2])) { - slotResults.isWinner = true; + if (values[0] === values[1] && values[0] === values[2]) { + slotResults.isWinner = true; } // return the JSON result to the caller of the Lambda function callback(null, slotResults); -}); - + }); }; // snippet-end:[lambda.JavaScript.writeLambdaFunction.complete] diff --git a/javascript/example_code/mediaconvert/emc_canceljob.js b/javascript/example_code/mediaconvert/emc_canceljob.js index 964ca450333..4ec34960509 100644 --- a/javascript/example_code/mediaconvert/emc_canceljob.js +++ b/javascript/example_code/mediaconvert/emc_canceljob.js @@ -1,53 +1,32 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[emc_canceljob.js demonstrates how to remove a transcoding job from the queue.] -//snippet-service:[mediaconvert] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Elemental MediaConvert] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/emc-examples-jobs.html // snippet-start:[mediaconvert.JavaScript.jobs.cancelJob] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set the Region -AWS.config.update({region: 'us-west-2'}); +AWS.config.update({ region: "us-west-2" }); // Set MediaConvert to customer endpoint -AWS.config.mediaconvert = {endpoint : 'ACCOUNT_ENDPOINT'}; - +AWS.config.mediaconvert = { endpoint: "ACCOUNT_ENDPOINT" }; var params = { - Id: 'JOB_ID' /* required */ + Id: "JOB_ID" /* required */, }; - // Create a promise on a MediaConvert object -var endpointPromise = new AWS.MediaConvert({apiVersion: '2017-08-29'}).cancelJob(params).promise(); +var endpointPromise = new AWS.MediaConvert({ apiVersion: "2017-08-29" }) + .cancelJob(params) + .promise(); // Handle promise's fulfilled/rejected status endpointPromise.then( - function(data) { + function (data) { console.log("Job " + params.Id + " is canceled"); }, - function(err) { + function (err) { console.log("Error", err); } ); diff --git a/javascript/example_code/mediaconvert/emc_create_jobtemplate.js b/javascript/example_code/mediaconvert/emc_create_jobtemplate.js index 422b828713d..33e970b75d7 100644 --- a/javascript/example_code/mediaconvert/emc_create_jobtemplate.js +++ b/javascript/example_code/mediaconvert/emc_create_jobtemplate.js @@ -1,177 +1,156 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[emc_create_jobtemplate.js demonstrates how to create a transcoding job template.] -//snippet-service:[mediaconvert] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Elemental MediaConvert] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/emc-examples-templates.html // snippet-start:[mediaconvert.JavaScript.templates.createJobTemplate] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set the Region -AWS.config.update({region: 'us-west-2'}); +AWS.config.update({ region: "us-west-2" }); // Set the custom endpoint for your account -AWS.config.mediaconvert = {endpoint : 'ACCOUNT_ENDPOINT'}; +AWS.config.mediaconvert = { endpoint: "ACCOUNT_ENDPOINT" }; var params = { - Category: 'YouTube Jobs', - Description: 'Final production transcode', - Name: 'DemoTemplate', - Queue: 'JOB_QUEUE_ARN', - "Settings": { - "OutputGroups": [ + Category: "YouTube Jobs", + Description: "Final production transcode", + Name: "DemoTemplate", + Queue: "JOB_QUEUE_ARN", + Settings: { + OutputGroups: [ { - "Name": "File Group", - "OutputGroupSettings": { - "Type": "FILE_GROUP_SETTINGS", - "FileGroupSettings": { - "Destination": "s3://BUCKET_NAME/" - } + Name: "File Group", + OutputGroupSettings: { + Type: "FILE_GROUP_SETTINGS", + FileGroupSettings: { + Destination: "s3://BUCKET_NAME/", + }, }, - "Outputs": [ + Outputs: [ { - "VideoDescription": { - "ScalingBehavior": "DEFAULT", - "TimecodeInsertion": "DISABLED", - "AntiAlias": "ENABLED", - "Sharpness": 50, - "CodecSettings": { - "Codec": "H_264", - "H264Settings": { - "InterlaceMode": "PROGRESSIVE", - "NumberReferenceFrames": 3, - "Syntax": "DEFAULT", - "Softness": 0, - "GopClosedCadence": 1, - "GopSize": 90, - "Slices": 1, - "GopBReference": "DISABLED", - "SlowPal": "DISABLED", - "SpatialAdaptiveQuantization": "ENABLED", - "TemporalAdaptiveQuantization": "ENABLED", - "FlickerAdaptiveQuantization": "DISABLED", - "EntropyEncoding": "CABAC", - "Bitrate": 5000000, - "FramerateControl": "SPECIFIED", - "RateControlMode": "CBR", - "CodecProfile": "MAIN", - "Telecine": "NONE", - "MinIInterval": 0, - "AdaptiveQuantization": "HIGH", - "CodecLevel": "AUTO", - "FieldEncoding": "PAFF", - "SceneChangeDetect": "ENABLED", - "QualityTuningLevel": "SINGLE_PASS", - "FramerateConversionAlgorithm": "DUPLICATE_DROP", - "UnregisteredSeiTimecode": "DISABLED", - "GopSizeUnits": "FRAMES", - "ParControl": "SPECIFIED", - "NumberBFramesBetweenReferenceFrames": 2, - "RepeatPps": "DISABLED", - "FramerateNumerator": 30, - "FramerateDenominator": 1, - "ParNumerator": 1, - "ParDenominator": 1 - } + VideoDescription: { + ScalingBehavior: "DEFAULT", + TimecodeInsertion: "DISABLED", + AntiAlias: "ENABLED", + Sharpness: 50, + CodecSettings: { + Codec: "H_264", + H264Settings: { + InterlaceMode: "PROGRESSIVE", + NumberReferenceFrames: 3, + Syntax: "DEFAULT", + Softness: 0, + GopClosedCadence: 1, + GopSize: 90, + Slices: 1, + GopBReference: "DISABLED", + SlowPal: "DISABLED", + SpatialAdaptiveQuantization: "ENABLED", + TemporalAdaptiveQuantization: "ENABLED", + FlickerAdaptiveQuantization: "DISABLED", + EntropyEncoding: "CABAC", + Bitrate: 5000000, + FramerateControl: "SPECIFIED", + RateControlMode: "CBR", + CodecProfile: "MAIN", + Telecine: "NONE", + MinIInterval: 0, + AdaptiveQuantization: "HIGH", + CodecLevel: "AUTO", + FieldEncoding: "PAFF", + SceneChangeDetect: "ENABLED", + QualityTuningLevel: "SINGLE_PASS", + FramerateConversionAlgorithm: "DUPLICATE_DROP", + UnregisteredSeiTimecode: "DISABLED", + GopSizeUnits: "FRAMES", + ParControl: "SPECIFIED", + NumberBFramesBetweenReferenceFrames: 2, + RepeatPps: "DISABLED", + FramerateNumerator: 30, + FramerateDenominator: 1, + ParNumerator: 1, + ParDenominator: 1, + }, }, - "AfdSignaling": "NONE", - "DropFrameTimecode": "ENABLED", - "RespondToAfd": "NONE", - "ColorMetadata": "INSERT" + AfdSignaling: "NONE", + DropFrameTimecode: "ENABLED", + RespondToAfd: "NONE", + ColorMetadata: "INSERT", }, - "AudioDescriptions": [ + AudioDescriptions: [ { - "AudioTypeControl": "FOLLOW_INPUT", - "CodecSettings": { - "Codec": "AAC", - "AacSettings": { - "AudioDescriptionBroadcasterMix": "NORMAL", - "RateControlMode": "CBR", - "CodecProfile": "LC", - "CodingMode": "CODING_MODE_2_0", - "RawFormat": "NONE", - "SampleRate": 48000, - "Specification": "MPEG4", - "Bitrate": 64000 - } + AudioTypeControl: "FOLLOW_INPUT", + CodecSettings: { + Codec: "AAC", + AacSettings: { + AudioDescriptionBroadcasterMix: "NORMAL", + RateControlMode: "CBR", + CodecProfile: "LC", + CodingMode: "CODING_MODE_2_0", + RawFormat: "NONE", + SampleRate: 48000, + Specification: "MPEG4", + Bitrate: 64000, + }, }, - "LanguageCodeControl": "FOLLOW_INPUT", - "AudioSourceName": "Audio Selector 1" - } + LanguageCodeControl: "FOLLOW_INPUT", + AudioSourceName: "Audio Selector 1", + }, ], - "ContainerSettings": { - "Container": "MP4", - "Mp4Settings": { - "CslgAtom": "INCLUDE", - "FreeSpaceBox": "EXCLUDE", - "MoovPlacement": "PROGRESSIVE_DOWNLOAD" - } + ContainerSettings: { + Container: "MP4", + Mp4Settings: { + CslgAtom: "INCLUDE", + FreeSpaceBox: "EXCLUDE", + MoovPlacement: "PROGRESSIVE_DOWNLOAD", + }, }, - "NameModifier": "_1" - } - ] - } + NameModifier: "_1", + }, + ], + }, ], - "AdAvailOffset": 0, - "Inputs": [ + AdAvailOffset: 0, + Inputs: [ { - "AudioSelectors": { + AudioSelectors: { "Audio Selector 1": { - "Offset": 0, - "DefaultSelection": "NOT_DEFAULT", - "ProgramSelection": 1, - "SelectorType": "TRACK", - "Tracks": [ - 1 - ] - } + Offset: 0, + DefaultSelection: "NOT_DEFAULT", + ProgramSelection: 1, + SelectorType: "TRACK", + Tracks: [1], + }, }, - "VideoSelector": { - "ColorSpace": "FOLLOW" + VideoSelector: { + ColorSpace: "FOLLOW", }, - "FilterEnable": "AUTO", - "PsiControl": "USE_PSI", - "FilterStrength": 0, - "DeblockFilter": "DISABLED", - "DenoiseFilter": "DISABLED", - "TimecodeSource": "EMBEDDED", - } + FilterEnable: "AUTO", + PsiControl: "USE_PSI", + FilterStrength: 0, + DeblockFilter: "DISABLED", + DenoiseFilter: "DISABLED", + TimecodeSource: "EMBEDDED", + }, ], - "TimecodeConfig": { - "Source": "EMBEDDED" - } - } + TimecodeConfig: { + Source: "EMBEDDED", + }, + }, }; // Create a promise on a MediaConvert object -var templatePromise = new AWS.MediaConvert({apiVersion: '2017-08-29'}).createJobTemplate(params).promise(); +var templatePromise = new AWS.MediaConvert({ apiVersion: "2017-08-29" }) + .createJobTemplate(params) + .promise(); // Handle promise's fulfilled/rejected status templatePromise.then( - function(data) { + function (data) { console.log("Success!", data); }, - function(err) { + function (err) { console.log("Error", err); } ); diff --git a/javascript/example_code/mediaconvert/emc_createjob.js b/javascript/example_code/mediaconvert/emc_createjob.js index 738b0132639..31324227d7f 100644 --- a/javascript/example_code/mediaconvert/emc_createjob.js +++ b/javascript/example_code/mediaconvert/emc_createjob.js @@ -1,26 +1,5 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[emc_createjob.js demonstrates how to create a transcoding job.] -//snippet-service:[mediaconvert] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Elemental MediaConvert] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/emc-examples-jobs.html @@ -29,157 +8,157 @@ // snippet-start:[mediaconvert.JavaScript.jobs.createJob_config] // Load the SDK for JavaScript -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set the Region -AWS.config.update({region: 'us-west-2'}); +AWS.config.update({ region: "us-west-2" }); // Set the custom endpoint for your account -AWS.config.mediaconvert = {endpoint : 'ACCOUNT_ENDPOINT'}; +AWS.config.mediaconvert = { endpoint: "ACCOUNT_ENDPOINT" }; // snippet-end:[mediaconvert.JavaScript.jobs.createJob_config] // snippet-start:[mediaconvert.JavaScript.jobs.createJob_define] var params = { - "Queue": "JOB_QUEUE_ARN", - "UserMetadata": { - "Customer": "Amazon" + Queue: "JOB_QUEUE_ARN", + UserMetadata: { + Customer: "Amazon", }, - "Role": "IAM_ROLE_ARN", - "Settings": { - "OutputGroups": [ + Role: "IAM_ROLE_ARN", + Settings: { + OutputGroups: [ { - "Name": "File Group", - "OutputGroupSettings": { - "Type": "FILE_GROUP_SETTINGS", - "FileGroupSettings": { - "Destination": "s3://OUTPUT_BUCKET_NAME/" - } + Name: "File Group", + OutputGroupSettings: { + Type: "FILE_GROUP_SETTINGS", + FileGroupSettings: { + Destination: "s3://OUTPUT_BUCKET_NAME/", + }, }, - "Outputs": [ + Outputs: [ { - "VideoDescription": { - "ScalingBehavior": "DEFAULT", - "TimecodeInsertion": "DISABLED", - "AntiAlias": "ENABLED", - "Sharpness": 50, - "CodecSettings": { - "Codec": "H_264", - "H264Settings": { - "InterlaceMode": "PROGRESSIVE", - "NumberReferenceFrames": 3, - "Syntax": "DEFAULT", - "Softness": 0, - "GopClosedCadence": 1, - "GopSize": 90, - "Slices": 1, - "GopBReference": "DISABLED", - "SlowPal": "DISABLED", - "SpatialAdaptiveQuantization": "ENABLED", - "TemporalAdaptiveQuantization": "ENABLED", - "FlickerAdaptiveQuantization": "DISABLED", - "EntropyEncoding": "CABAC", - "Bitrate": 5000000, - "FramerateControl": "SPECIFIED", - "RateControlMode": "CBR", - "CodecProfile": "MAIN", - "Telecine": "NONE", - "MinIInterval": 0, - "AdaptiveQuantization": "HIGH", - "CodecLevel": "AUTO", - "FieldEncoding": "PAFF", - "SceneChangeDetect": "ENABLED", - "QualityTuningLevel": "SINGLE_PASS", - "FramerateConversionAlgorithm": "DUPLICATE_DROP", - "UnregisteredSeiTimecode": "DISABLED", - "GopSizeUnits": "FRAMES", - "ParControl": "SPECIFIED", - "NumberBFramesBetweenReferenceFrames": 2, - "RepeatPps": "DISABLED", - "FramerateNumerator": 30, - "FramerateDenominator": 1, - "ParNumerator": 1, - "ParDenominator": 1 - } + VideoDescription: { + ScalingBehavior: "DEFAULT", + TimecodeInsertion: "DISABLED", + AntiAlias: "ENABLED", + Sharpness: 50, + CodecSettings: { + Codec: "H_264", + H264Settings: { + InterlaceMode: "PROGRESSIVE", + NumberReferenceFrames: 3, + Syntax: "DEFAULT", + Softness: 0, + GopClosedCadence: 1, + GopSize: 90, + Slices: 1, + GopBReference: "DISABLED", + SlowPal: "DISABLED", + SpatialAdaptiveQuantization: "ENABLED", + TemporalAdaptiveQuantization: "ENABLED", + FlickerAdaptiveQuantization: "DISABLED", + EntropyEncoding: "CABAC", + Bitrate: 5000000, + FramerateControl: "SPECIFIED", + RateControlMode: "CBR", + CodecProfile: "MAIN", + Telecine: "NONE", + MinIInterval: 0, + AdaptiveQuantization: "HIGH", + CodecLevel: "AUTO", + FieldEncoding: "PAFF", + SceneChangeDetect: "ENABLED", + QualityTuningLevel: "SINGLE_PASS", + FramerateConversionAlgorithm: "DUPLICATE_DROP", + UnregisteredSeiTimecode: "DISABLED", + GopSizeUnits: "FRAMES", + ParControl: "SPECIFIED", + NumberBFramesBetweenReferenceFrames: 2, + RepeatPps: "DISABLED", + FramerateNumerator: 30, + FramerateDenominator: 1, + ParNumerator: 1, + ParDenominator: 1, + }, }, - "AfdSignaling": "NONE", - "DropFrameTimecode": "ENABLED", - "RespondToAfd": "NONE", - "ColorMetadata": "INSERT" + AfdSignaling: "NONE", + DropFrameTimecode: "ENABLED", + RespondToAfd: "NONE", + ColorMetadata: "INSERT", }, - "AudioDescriptions": [ + AudioDescriptions: [ { - "AudioTypeControl": "FOLLOW_INPUT", - "CodecSettings": { - "Codec": "AAC", - "AacSettings": { - "AudioDescriptionBroadcasterMix": "NORMAL", - "RateControlMode": "CBR", - "CodecProfile": "LC", - "CodingMode": "CODING_MODE_2_0", - "RawFormat": "NONE", - "SampleRate": 48000, - "Specification": "MPEG4", - "Bitrate": 64000 - } + AudioTypeControl: "FOLLOW_INPUT", + CodecSettings: { + Codec: "AAC", + AacSettings: { + AudioDescriptionBroadcasterMix: "NORMAL", + RateControlMode: "CBR", + CodecProfile: "LC", + CodingMode: "CODING_MODE_2_0", + RawFormat: "NONE", + SampleRate: 48000, + Specification: "MPEG4", + Bitrate: 64000, + }, }, - "LanguageCodeControl": "FOLLOW_INPUT", - "AudioSourceName": "Audio Selector 1" - } + LanguageCodeControl: "FOLLOW_INPUT", + AudioSourceName: "Audio Selector 1", + }, ], - "ContainerSettings": { - "Container": "MP4", - "Mp4Settings": { - "CslgAtom": "INCLUDE", - "FreeSpaceBox": "EXCLUDE", - "MoovPlacement": "PROGRESSIVE_DOWNLOAD" - } + ContainerSettings: { + Container: "MP4", + Mp4Settings: { + CslgAtom: "INCLUDE", + FreeSpaceBox: "EXCLUDE", + MoovPlacement: "PROGRESSIVE_DOWNLOAD", + }, }, - "NameModifier": "_1" - } - ] - } + NameModifier: "_1", + }, + ], + }, ], - "AdAvailOffset": 0, - "Inputs": [ + AdAvailOffset: 0, + Inputs: [ { - "AudioSelectors": { + AudioSelectors: { "Audio Selector 1": { - "Offset": 0, - "DefaultSelection": "NOT_DEFAULT", - "ProgramSelection": 1, - "SelectorType": "TRACK", - "Tracks": [ - 1 - ] - } + Offset: 0, + DefaultSelection: "NOT_DEFAULT", + ProgramSelection: 1, + SelectorType: "TRACK", + Tracks: [1], + }, }, - "VideoSelector": { - "ColorSpace": "FOLLOW" + VideoSelector: { + ColorSpace: "FOLLOW", }, - "FilterEnable": "AUTO", - "PsiControl": "USE_PSI", - "FilterStrength": 0, - "DeblockFilter": "DISABLED", - "DenoiseFilter": "DISABLED", - "TimecodeSource": "EMBEDDED", - "FileInput": "s3://INPUT_BUCKET_AND_FILE_NAME" - } + FilterEnable: "AUTO", + PsiControl: "USE_PSI", + FilterStrength: 0, + DeblockFilter: "DISABLED", + DenoiseFilter: "DISABLED", + TimecodeSource: "EMBEDDED", + FileInput: "s3://INPUT_BUCKET_AND_FILE_NAME", + }, ], - "TimecodeConfig": { - "Source": "EMBEDDED" - } - } + TimecodeConfig: { + Source: "EMBEDDED", + }, + }, }; // snippet-end:[mediaconvert.JavaScript.jobs.createJob_define] // snippet-start:[mediaconvert.JavaScript.jobs.createJob_create] // Create a promise on a MediaConvert object -var endpointPromise = new AWS.MediaConvert({apiVersion: '2017-08-29'}).createJob(params).promise(); +var endpointPromise = new AWS.MediaConvert({ apiVersion: "2017-08-29" }) + .createJob(params) + .promise(); // Handle promise's fulfilled/rejected status endpointPromise.then( - function(data) { + function (data) { console.log("Job created! ", data); }, - function(err) { + function (err) { console.log("Error", err); } ); diff --git a/javascript/example_code/mediaconvert/emc_deletetemplate.js b/javascript/example_code/mediaconvert/emc_deletetemplate.js index 1812083192f..cb6467c24da 100644 --- a/javascript/example_code/mediaconvert/emc_deletetemplate.js +++ b/javascript/example_code/mediaconvert/emc_deletetemplate.js @@ -1,51 +1,32 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[emc_deletetemplate.js demonstrates how to delete a transcoding job template.] -//snippet-service:[mediaconvert] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Elemental MediaConvert] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/emc-examples-templates.html // snippet-start:[mediaconvert.JavaScript.templates.deleteJobTemplate] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set the Region -AWS.config.update({region: 'us-west-2'}); +AWS.config.update({ region: "us-west-2" }); // Set the customer endpoint -AWS.config.mediaconvert = {endpoint : 'ACCOUNT_ENDPOINT'}; +AWS.config.mediaconvert = { endpoint: "ACCOUNT_ENDPOINT" }; var params = { - Name: 'TEMPLATE_NAME' + Name: "TEMPLATE_NAME", }; // Create a promise on a MediaConvert object -var deleteTemplatePromise = new AWS.MediaConvert({apiVersion: '2017-08-29'}).deleteJobTemplate(params).promise(); +var deleteTemplatePromise = new AWS.MediaConvert({ apiVersion: "2017-08-29" }) + .deleteJobTemplate(params) + .promise(); // Handle promise's fulfilled/rejected status deleteTemplatePromise.then( - function(data) { + function (data) { console.log("Success ", data); }, - function(err) { + function (err) { console.log("Error", err); } ); diff --git a/javascript/example_code/mediaconvert/emc_getendpoint.js b/javascript/example_code/mediaconvert/emc_getendpoint.js index 40d6857106e..581c18e2ff5 100644 --- a/javascript/example_code/mediaconvert/emc_getendpoint.js +++ b/javascript/example_code/mediaconvert/emc_getendpoint.js @@ -1,39 +1,18 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[emc_getendpoint.js demonstrates how to retrieve information about the endpoints for an AWS account.] -//snippet-service:[mediaconvert] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Elemental MediaConvert] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/emc-examples-getendpoint.html // snippet-start:[mediaconvert.JavaScript.endoint.describeEndpoints] // Load the SDK for JavaScript. -const aws = require('aws-sdk'); +const aws = require("aws-sdk"); // Set the AWS Region. -aws.config.update({region: 'us-west-2'}); +aws.config.update({ region: "us-west-2" }); // Create the client. -const mediaConvert = new aws.MediaConvert({apiVersion: '2017-08-29'}); +const mediaConvert = new aws.MediaConvert({ apiVersion: "2017-08-29" }); exports.handler = async (event, context) => { // Create empty request parameters @@ -42,10 +21,12 @@ exports.handler = async (event, context) => { }; try { - const { Endpoints } = await mediaConvert.describeEndpoints(params).promise(); + const { Endpoints } = await mediaConvert + .describeEndpoints(params) + .promise(); console.log("Your MediaConvert endpoint is ", Endpoints); } catch (err) { console.log("MediaConvert Error", err); } -} +}; // snippet-end:[mediaconvert.JavaScript.endoint.describeEndpoints] diff --git a/javascript/example_code/mediaconvert/emc_listjobs.js b/javascript/example_code/mediaconvert/emc_listjobs.js index f79e274aeec..cde2fc458f0 100644 --- a/javascript/example_code/mediaconvert/emc_listjobs.js +++ b/javascript/example_code/mediaconvert/emc_listjobs.js @@ -1,55 +1,35 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[emc_listjobs.js demonstrates how to retrieve a list of the most-recently created transcoding jobs.] -//snippet-service:[mediaconvert] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Elemental MediaConvert] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/emc-examples-jobs.html // snippet-start:[mediaconvert.JavaScript.jobs.listJobs] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set the Region -AWS.config.update({region: 'us-west-2'}); +AWS.config.update({ region: "us-west-2" }); // Set the customer endpoint -AWS.config.mediaconvert = {endpoint : 'ACCOUNT_ENDPOINT'}; - +AWS.config.mediaconvert = { endpoint: "ACCOUNT_ENDPOINT" }; var params = { MaxResults: 10, - Order: 'ASCENDING', - Queue: 'QUEUE_ARN', - Status: 'SUBMITTED' + Order: "ASCENDING", + Queue: "QUEUE_ARN", + Status: "SUBMITTED", }; // Create a promise on a MediaConvert object -var endpointPromise = new AWS.MediaConvert({apiVersion: '2017-08-29'}).listJobs(params).promise(); +var endpointPromise = new AWS.MediaConvert({ apiVersion: "2017-08-29" }) + .listJobs(params) + .promise(); // Handle promise's fulfilled/rejected status endpointPromise.then( - function(data) { + function (data) { console.log("Jobs: ", data); }, - function(err) { + function (err) { console.log("Error", err); } ); diff --git a/javascript/example_code/mediaconvert/emc_listtemplates.js b/javascript/example_code/mediaconvert/emc_listtemplates.js index a4d8b5964c2..e79a800d756 100644 --- a/javascript/example_code/mediaconvert/emc_listtemplates.js +++ b/javascript/example_code/mediaconvert/emc_listtemplates.js @@ -1,53 +1,34 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[emc_listtemplates.js demonstrates how to retrieve transcoding job templates.] -//snippet-service:[mediaconvert] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Elemental MediaConvert] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/emc-examples-templates.html // snippet-start:[mediaconvert.JavaScript.templates.listJobTemplates] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set the Region -AWS.config.update({region: 'us-west-2'}); +AWS.config.update({ region: "us-west-2" }); // Set the customer endpoint -AWS.config.mediaconvert = {endpoint : 'ACCOUNT_ENDPOINT'}; +AWS.config.mediaconvert = { endpoint: "ACCOUNT_ENDPOINT" }; var params = { - ListBy: 'NAME', + ListBy: "NAME", MaxResults: 10, - Order: 'ASCENDING', + Order: "ASCENDING", }; // Create a promise on a MediaConvert object -var listTemplatesPromise = new AWS.MediaConvert({apiVersion: '2017-08-29'}).listJobTemplates(params).promise(); +var listTemplatesPromise = new AWS.MediaConvert({ apiVersion: "2017-08-29" }) + .listJobTemplates(params) + .promise(); // Handle promise's fulfilled/rejected status listTemplatesPromise.then( - function(data) { + function (data) { console.log("Success ", data); }, - function(err) { + function (err) { console.log("Error", err); } ); diff --git a/javascript/example_code/mediaconvert/emc_template_createjob.js b/javascript/example_code/mediaconvert/emc_template_createjob.js index c703406d9b1..599ff1b6a5d 100644 --- a/javascript/example_code/mediaconvert/emc_template_createjob.js +++ b/javascript/example_code/mediaconvert/emc_template_createjob.js @@ -1,80 +1,59 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[emc_template_createjob.js demonstrates how to create a transcoding job using a template.] -//snippet-service:[mediaconvert] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Elemental MediaConvert] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/emc-examples-templates.html // snippet-start:[mediaconvert.JavaScript.templates.createJob] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set the Region -AWS.config.update({region: 'us-west-2'}); +AWS.config.update({ region: "us-west-2" }); // Set the custom endpoint for your account -AWS.config.mediaconvert = {endpoint : 'ACCOUNT_ENDPOINT'}; +AWS.config.mediaconvert = { endpoint: "ACCOUNT_ENDPOINT" }; var params = { - "Queue": "QUEUE_ARN", - "JobTemplate": "TEMPLATE_NAME", - "Role": "ROLE_ARN", - "Settings": { - "Inputs": [ + Queue: "QUEUE_ARN", + JobTemplate: "TEMPLATE_NAME", + Role: "ROLE_ARN", + Settings: { + Inputs: [ { - "AudioSelectors": { + AudioSelectors: { "Audio Selector 1": { - "Offset": 0, - "DefaultSelection": "NOT_DEFAULT", - "ProgramSelection": 1, - "SelectorType": "TRACK", - "Tracks": [ - 1 - ] - } + Offset: 0, + DefaultSelection: "NOT_DEFAULT", + ProgramSelection: 1, + SelectorType: "TRACK", + Tracks: [1], + }, }, - "VideoSelector": { - "ColorSpace": "FOLLOW" + VideoSelector: { + ColorSpace: "FOLLOW", }, - "FilterEnable": "AUTO", - "PsiControl": "USE_PSI", - "FilterStrength": 0, - "DeblockFilter": "DISABLED", - "DenoiseFilter": "DISABLED", - "TimecodeSource": "EMBEDDED", - "FileInput": "s3://BUCKET_NAME/FILE_NAME" - } - ] - } + FilterEnable: "AUTO", + PsiControl: "USE_PSI", + FilterStrength: 0, + DeblockFilter: "DISABLED", + DenoiseFilter: "DISABLED", + TimecodeSource: "EMBEDDED", + FileInput: "s3://BUCKET_NAME/FILE_NAME", + }, + ], + }, }; // Create a promise on a MediaConvert object -var templateJobPromise = new AWS.MediaConvert({apiVersion: '2017-08-29'}).createJob(params).promise(); +var templateJobPromise = new AWS.MediaConvert({ apiVersion: "2017-08-29" }) + .createJob(params) + .promise(); // Handle promise's fulfilled/rejected status templateJobPromise.then( - function(data) { + function (data) { console.log("Success! ", data); }, - function(err) { + function (err) { console.log("Error", err); } ); diff --git a/javascript/example_code/nodegetstarted/sample.js b/javascript/example_code/nodegetstarted/sample.js index 94b1e03b89a..6b3f6b0ec25 100644 --- a/javascript/example_code/nodegetstarted/sample.js +++ b/javascript/example_code/nodegetstarted/sample.js @@ -1,56 +1,44 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[sample.js demonstrates how to get started using the AWS SDK for JavaScript.] -// snippet-service:[nodejs] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Code Sample] -// snippet-keyword:[Node.js] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2018-06-02] -// snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/getting-started-nodejs.html // snippet-start:[GettingStarted.JavaScript.NodeJS.getStarted] // Load the SDK and UUID -var AWS = require('aws-sdk'); -var uuid = require('uuid'); +var AWS = require("aws-sdk"); +var uuid = require("uuid"); // Create unique bucket name -var bucketName = 'node-sdk-sample-' + uuid.v4(); +var bucketName = "node-sdk-sample-" + uuid.v4(); // Create name for uploaded object key -var keyName = 'hello_world.txt'; +var keyName = "hello_world.txt"; // Create a promise on S3 service object -var bucketPromise = new AWS.S3({apiVersion: '2006-03-01'}).createBucket({Bucket: bucketName}).promise(); +var bucketPromise = new AWS.S3({ apiVersion: "2006-03-01" }) + .createBucket({ Bucket: bucketName }) + .promise(); // Handle promise fulfilled/rejected states -bucketPromise.then( - function(data) { +bucketPromise + .then(function (data) { // Create params for putObject call - var objectParams = {Bucket: bucketName, Key: keyName, Body: 'Hello World!'}; + var objectParams = { + Bucket: bucketName, + Key: keyName, + Body: "Hello World!", + }; // Create object upload promise - var uploadPromise = new AWS.S3({apiVersion: '2006-03-01'}).putObject(objectParams).promise(); - uploadPromise.then( - function(data) { - console.log("Successfully uploaded data to " + bucketName + "/" + keyName); - }); -}).catch( - function(err) { + var uploadPromise = new AWS.S3({ apiVersion: "2006-03-01" }) + .putObject(objectParams) + .promise(); + uploadPromise.then(function (data) { + console.log( + "Successfully uploaded data to " + bucketName + "/" + keyName + ); + }); + }) + .catch(function (err) { console.error(err, err.stack); -}); + }); // snippet-end:[GettingStarted.JavaScript.NodeJS.getStarted] diff --git a/javascript/example_code/pinpoint-email/pinpoint_send_email_message_email_api.js b/javascript/example_code/pinpoint-email/pinpoint_send_email_message_email_api.js index a1f63cb74d4..5ce9aa78019 100644 --- a/javascript/example_code/pinpoint-email/pinpoint_send_email_message_email_api.js +++ b/javascript/example_code/pinpoint-email/pinpoint_send_email_message_email_api.js @@ -1,32 +1,11 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[pinpoint_send_email_message_email_api demonstrates how to send a transactional email message by using the SendEmail operation in the Amazon Pinpoint Email API.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Pinpoint Email API] -// snippet-keyword:[Code Sample] -// snippet-keyword:[SendEmail] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-20] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[pinpoint.javascript.pinpoint_send_email_message_email_api.complete] -'use strict'; +"use strict"; -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // The AWS Region that you want to use to send the email. For a list of // AWS Regions where the Amazon Pinpoint Email API is available, see @@ -43,12 +22,12 @@ var senderAddress = "Mary Major "; // easier to specify multiple recipients. Alternatively, you can make these // variables strings, and then modify the To/Cc/BccAddresses attributes in the // params variable so that it passes an array for each recipient type. -var toAddresses = [ "recipient@example.com" ]; +var toAddresses = ["recipient@example.com"]; // CC and BCC addresses. If your account is in the sandbox, these // addresses have to be verified. -var ccAddresses = [ "cc_recipient1@example.com","cc_recipient2@example.com" ]; -var bccAddresses = [ "bcc_recipient@example.com" ]; +var ccAddresses = ["cc_recipient1@example.com", "cc_recipient2@example.com"]; +var bccAddresses = ["bcc_recipient@example.com"]; // The configuration set that you want to use to send the email. var configuration_set = "ConfigSet"; @@ -75,8 +54,8 @@ var body_html = ` `; // The message tags that you want to apply to the email. -var tag0 = { 'Name':'key0', 'Value':'value0' }; -var tag1 = { 'Name':'key1', 'Value':'value1' }; +var tag0 = { Name: "key0", Value: "value0" }; +var tag1 = { Name: "key1", Value: "value1" }; // The character encoding the you want to use for the subject line and // message body of the email. @@ -84,11 +63,11 @@ var charset = "UTF-8"; // Specify that you're using a shared credentials file, and specify which // profile to use in the shared credentials file. -var credentials = new AWS.SharedIniFileCredentials({profile: 'default'}); +var credentials = new AWS.SharedIniFileCredentials({ profile: "default" }); AWS.config.credentials = credentials; // Specify the region. -AWS.config.update({region:aws_region}); +AWS.config.update({ region: aws_region }); //Create a new PinpointEmail object. var pinpointEmail = new AWS.PinpointEmail(); @@ -99,37 +78,34 @@ var params = { Destination: { ToAddresses: toAddresses, CcAddresses: ccAddresses, - BccAddresses: bccAddresses + BccAddresses: bccAddresses, }, Content: { Simple: { Body: { Html: { Data: body_html, - Charset: charset + Charset: charset, }, Text: { Data: body_text, - Charset: charset - } + Charset: charset, + }, }, Subject: { Data: subject, - Charset: charset - } - } + Charset: charset, + }, + }, }, ConfigurationSetName: configuration_set, - EmailTags: [ - tag0, - tag1 - ] + EmailTags: [tag0, tag1], }; //Try to send the email. -pinpointEmail.sendEmail(params, function(err, data) { +pinpointEmail.sendEmail(params, function (err, data) { // If something goes wrong, print an error message. - if(err) { + if (err) { console.log(err.message); } else { console.log("Email sent! Message ID: ", data.MessageId); @@ -137,4 +113,3 @@ pinpointEmail.sendEmail(params, function(err, data) { }); // snippet-end:[pinpoint.javascript.pinpoint_send_email_message_email_api.complete] - diff --git a/javascript/example_code/pinpoint-sms-voice/pinpoint_send_voice_message_sms_voice_api.js b/javascript/example_code/pinpoint-sms-voice/pinpoint_send_voice_message_sms_voice_api.js index 78d89ec1d85..b4122d0d76a 100644 --- a/javascript/example_code/pinpoint-sms-voice/pinpoint_send_voice_message_sms_voice_api.js +++ b/javascript/example_code/pinpoint-sms-voice/pinpoint_send_voice_message_sms_voice_api.js @@ -1,32 +1,11 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[pinpoint_send_voice_message_sms_voice_api demonstrates how to send a transactional voice message by using the SendVoiceMessage operation in the Amazon Pinpoint SMS and Voice API.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Pinpoint SMS and Voice API] -// snippet-keyword:[Code Sample] -// snippet-keyword:[SendVoiceMessage] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-20] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[pinpoint.javascript.pinpoint_send_voice_message_sms_voice_api.complete] -'use strict' +"use strict"; -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // The AWS Region that you want to use to send the voice message. For a list of // AWS Regions where the Amazon Pinpoint SMS and Voice API is available, see @@ -53,12 +32,13 @@ var voiceId = "Matthew"; // The content of the message. This example uses SSML to customize and control // certain aspects of the message, such as the volume or the speech rate. // The message can't contain any line breaks. -var ssmlMessage = "" - + "This is a test message sent from Amazon Pinpoint " - + "using the AWS SDK for JavaScript in Node.js. " - + "Thank you for listening." - + "" - + ""; +var ssmlMessage = + "" + + "This is a test message sent from Amazon Pinpoint " + + "using the AWS SDK for JavaScript in Node.js. " + + "Thank you for listening." + + "" + + ""; // The phone number that you want to appear on the recipient's device. The phone // number that you specify has to be associated with your Amazon Pinpoint account. @@ -69,11 +49,11 @@ var configurationSet = "ConfigSet"; // Specify that you're using a shared credentials file, and optionally specify // the profile that you want to use. -var credentials = new AWS.SharedIniFileCredentials({profile: 'default'}); +var credentials = new AWS.SharedIniFileCredentials({ profile: "default" }); AWS.config.credentials = credentials; // Specify the region. -AWS.config.update({region:aws_region}); +AWS.config.update({ region: aws_region }); //Create a new Pinpoint object. var pinpointsmsvoice = new AWS.PinpointSMSVoice(); @@ -85,21 +65,21 @@ var params = { SSMLMessage: { LanguageCode: languageCode, Text: ssmlMessage, - VoiceId: voiceId - } + VoiceId: voiceId, + }, }, DestinationPhoneNumber: destinationNumber, - OriginationPhoneNumber: originationNumber + OriginationPhoneNumber: originationNumber, }; //Try to send the message. -pinpointsmsvoice.sendVoiceMessage(params, function(err, data) { +pinpointsmsvoice.sendVoiceMessage(params, function (err, data) { // If something goes wrong, print an error message. - if(err) { + if (err) { console.log(err.message); - // Otherwise, show the unique ID for the message. + // Otherwise, show the unique ID for the message. } else { - console.log("Message sent! Message ID: " + data['MessageId']); + console.log("Message sent! Message ID: " + data["MessageId"]); } }); diff --git a/javascript/example_code/pinpoint/pinpoint_send_email_message_api.js b/javascript/example_code/pinpoint/pinpoint_send_email_message_api.js index 2e5ed977919..c940ccf9212 100644 --- a/javascript/example_code/pinpoint/pinpoint_send_email_message_api.js +++ b/javascript/example_code/pinpoint/pinpoint_send_email_message_api.js @@ -1,37 +1,16 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[pinpoint_send_email_message_api demonstrates how to send a transactional email message by using the SendMessages operation in the Amazon Pinpoint API.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Pinpoint] -// snippet-keyword:[Code Sample] -// snippet-keyword:[SendMessages] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-20] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[pinpoint.javascript.pinpoint_send_email_message_api.complete] -'use strict'; +"use strict"; -const AWS = require('aws-sdk'); +const AWS = require("aws-sdk"); // The AWS Region that you want to use to send the email. For a list of // AWS Regions where the Amazon Pinpoint API is available, see // https://docs.aws.amazon.com/pinpoint/latest/apireference/ -const aws_region = "us-west-2" +const aws_region = "us-west-2"; // The "From" address. This address has to be verified in Amazon Pinpoint // in the region that you use to send email. @@ -72,11 +51,11 @@ var body_html = ` var charset = "UTF-8"; // Specify that you're using a shared credentials file. -var credentials = new AWS.SharedIniFileCredentials({profile: 'default'}); +var credentials = new AWS.SharedIniFileCredentials({ profile: "default" }); AWS.config.credentials = credentials; // Specify the region. -AWS.config.update({region:aws_region}); +AWS.config.update({ region: aws_region }); //Create a new Pinpoint object. var pinpoint = new AWS.Pinpoint(); @@ -86,9 +65,9 @@ var params = { ApplicationId: appId, MessageRequest: { Addresses: { - [toAddress]:{ - ChannelType: 'EMAIL' - } + [toAddress]: { + ChannelType: "EMAIL", + }, }, MessageConfiguration: { EmailMessage: { @@ -96,32 +75,33 @@ var params = { SimpleEmail: { Subject: { Charset: charset, - Data: subject + Data: subject, }, HtmlPart: { Charset: charset, - Data: body_html + Data: body_html, }, TextPart: { Charset: charset, - Data: body_text - } - } - } - } - } + Data: body_text, + }, + }, + }, + }, + }, }; //Try to send the email. -pinpoint.sendMessages(params, function(err, data) { +pinpoint.sendMessages(params, function (err, data) { // If something goes wrong, print an error message. - if(err) { + if (err) { console.log(err.message); } else { - console.log("Email sent! Message ID: ", data['MessageResponse']['Result'][toAddress]['MessageId']); + console.log( + "Email sent! Message ID: ", + data["MessageResponse"]["Result"][toAddress]["MessageId"] + ); } }); // snippet-end:[pinpoint.javascript.pinpoint_send_email_message_api.complete] - - diff --git a/javascript/example_code/pinpoint/pinpoint_send_email_smtp.js b/javascript/example_code/pinpoint/pinpoint_send_email_smtp.js index d950cd10ba1..a1b23cf1e3c 100644 --- a/javascript/example_code/pinpoint/pinpoint_send_email_smtp.js +++ b/javascript/example_code/pinpoint/pinpoint_send_email_smtp.js @@ -1,27 +1,8 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -// snippet-sourcedescription:[pinpoint_send_email_smtp demonstrates how to send a transactional email message by using the Amazon Pinpoint SMTP interface and the Nodemailer module.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Pinpoint] -// snippet-keyword:[Code Sample] -// snippet-keyword:[n/a] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-20] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/*/ + // snippet-start:[pinpoint.javascript.pinpoint_send_email_smtp.complete] /* This code uses callbacks to handle asynchronous function responses. diff --git a/javascript/example_code/pinpoint/pinpoint_send_sms_message_api.js b/javascript/example_code/pinpoint/pinpoint_send_sms_message_api.js index bdc45582618..af68cb78c9e 100644 --- a/javascript/example_code/pinpoint/pinpoint_send_sms_message_api.js +++ b/javascript/example_code/pinpoint/pinpoint_send_sms_message_api.js @@ -1,32 +1,11 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[pinpoint_send_sms_message_api demonstrates how to send a transactional SMS message by using the SendMessages operation in the Amazon Pinpoint API.] -// snippet-service:[Amazon Pinpoint] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Pinpoint] -// snippet-keyword:[Code Sample] -// snippet-keyword:[SendMessages] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-01-20] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[pinpoint.javascript.pinpoint_send_sms_message_api.complete] -'use strict'; +"use strict"; -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // The AWS Region that you want to use to send the message. For a list of // AWS Regions where the Amazon Pinpoint API is available, see @@ -43,9 +22,10 @@ var originationNumber = "+12065550199"; var destinationNumber = "+14255550142"; // The content of the SMS message. -var message = "This message was sent through Amazon Pinpoint " - + "using the AWS SDK for JavaScript in Node.js. Reply STOP to " - + "opt out."; +var message = + "This message was sent through Amazon Pinpoint " + + "using the AWS SDK for JavaScript in Node.js. Reply STOP to " + + "opt out."; // The Amazon Pinpoint project/application ID to use when you send this message. // Make sure that the SMS channel is enabled for the project or application @@ -67,11 +47,11 @@ var senderId = "MySenderID"; // Specify that you're using a shared credentials file, and optionally specify // the profile that you want to use. -var credentials = new AWS.SharedIniFileCredentials({profile: 'default'}); +var credentials = new AWS.SharedIniFileCredentials({ profile: "default" }); AWS.config.credentials = credentials; // Specify the region. -AWS.config.update({region:aws_region}); +AWS.config.update({ region: aws_region }); //Create a new Pinpoint object. var pinpoint = new AWS.Pinpoint(); @@ -82,8 +62,8 @@ var params = { MessageRequest: { Addresses: { [destinationNumber]: { - ChannelType: 'SMS' - } + ChannelType: "SMS", + }, }, MessageConfiguration: { SMSMessage: { @@ -92,22 +72,23 @@ var params = { MessageType: messageType, OriginationNumber: originationNumber, SenderId: senderId, - } - } - } + }, + }, + }, }; //Try to send the message. -pinpoint.sendMessages(params, function(err, data) { +pinpoint.sendMessages(params, function (err, data) { // If something goes wrong, print an error message. - if(err) { + if (err) { console.log(err.message); - // Otherwise, show the unique ID for the message. + // Otherwise, show the unique ID for the message. } else { - console.log("Message sent! " - + data['MessageResponse']['Result'][destinationNumber]['StatusMessage']); + console.log( + "Message sent! " + + data["MessageResponse"]["Result"][destinationNumber]["StatusMessage"] + ); } }); // snippet-end:[pinpoint.javascript.pinpoint_send_sms_message_api.complete] - diff --git a/javascript/example_code/rekognition/estimate-age-example/src/estimate-age.js b/javascript/example_code/rekognition/estimate-age-example/src/estimate-age.js index 4883ea6558f..24987531236 100644 --- a/javascript/example_code/rekognition/estimate-age-example/src/estimate-age.js +++ b/javascript/example_code/rekognition/estimate-age-example/src/estimate-age.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with AWS SDK for JavaScript version 2 (v2). This example is in the Amazon Rekognition Developer Guide' at https://docs.aws.amazon.com/rekognition/latest/dg/image-bytes-javascript.html. @@ -12,47 +14,48 @@ Inputs : - REGION */ -//snippet-start:[rekognition.JavaScript.alternative.detect_faces_v2] +// snippet-start:[rekognition.JavaScript.alternative.detect_faces_v2] function ProcessImage() { - AnonLog(); - var control = document.getElementById("fileToUpload"); - var file = control.files[0]; - - // Load base64 encoded image for display. - var reader = new FileReader(); - reader.onload = (function (theFile) { - return function (e) { - //Call Rekognition - AWS.region = "REGION"; - var rekognition = new AWS.Rekognition(); - var params = { - Image: { - Bytes: e.target.result - }, - Attributes: [ - 'ALL', - ] - }; - rekognition.detectFaces(params, function (err, data) { - if (err) console.log(err, err.stack); // an error occurred - else { - var table = "

"; - // show each face and build out estimated age table - for (var i = 0; i < data.FaceDetails.length; i++) { - table += ''; - } - table += "
LowHigh
' + data.FaceDetails[i].AgeRange.Low + - '' + data.FaceDetails[i].AgeRange.High + '
"; - document.getElementById("opResult").innerHTML = table; - } - }); + AnonLog(); + var control = document.getElementById("fileToUpload"); + var file = control.files[0]; - }; - })(file); - reader.readAsArrayBuffer(file); + // Load base64 encoded image for display. + var reader = new FileReader(); + reader.onload = (function (theFile) { + return function (e) { + //Call Rekognition + AWS.region = "REGION"; + var rekognition = new AWS.Rekognition(); + var params = { + Image: { + Bytes: e.target.result, + }, + Attributes: ["ALL"], + }; + rekognition.detectFaces(params, function (err, data) { + if (err) console.log(err, err.stack); // an error occurred + else { + var table = ""; + // show each face and build out estimated age table + for (var i = 0; i < data.FaceDetails.length; i++) { + table += + ""; + } + table += "
LowHigh
" + + data.FaceDetails[i].AgeRange.Low + + "" + + data.FaceDetails[i].AgeRange.High + + "
"; + document.getElementById("opResult").innerHTML = table; + } + }); + }; + })(file); + reader.readAsArrayBuffer(file); } -//snippet-end:[rekognition.JavaScript.alternative.detect_faces_v2] +// snippet-end:[rekognition.JavaScript.alternative.detect_faces_v2] //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.) diff --git a/javascript/example_code/s3/s3.js b/javascript/example_code/s3/s3.js index b4e08c17e49..efe55447895 100644 --- a/javascript/example_code/s3/s3.js +++ b/javascript/example_code/s3/s3.js @@ -1,106 +1,84 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -// snippet-sourcedescription:[s3.js demonstrates how to list, create, and delete a bucket in Amazon S3.] -// snippet-service:[s3] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-keyword:[listBuckets] -// snippet-keyword:[createBucket] -// snippet-keyword:[deleteBucket] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2017-01-24] -// snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + // snippet-start:[s3.javascript.bucket_operations.list_create_delete] if (process.argv.length < 4) { - console.log('Usage: node s3.js \n' + - 'Example: node s3.js my-test-bucket us-east-2'); - process.exit(1); - } - - var AWS = require('aws-sdk'); // To set the AWS credentials and region. - var async = require('async'); // To call AWS operations asynchronously. + console.log( + "Usage: node s3.js \n" + + "Example: node s3.js my-test-bucket us-east-2" + ); + process.exit(1); +} + +var AWS = require("aws-sdk"); // To set the AWS credentials and region. +var async = require("async"); // To call AWS operations asynchronously. + +AWS.config.update({ + region: region, +}); + +var s3 = new AWS.S3({ apiVersion: "2006-03-01" }); +var bucket_name = process.argv[2]; +var region = process.argv[3]; + +var create_bucket_params = { + Bucket: bucket_name, + CreateBucketConfiguration: { + LocationConstraint: region, + }, +}; + +var delete_bucket_params = { Bucket: bucket_name }; + +// List all of your available buckets in this AWS Region. +function listMyBuckets(callback) { + s3.listBuckets(function (err, data) { + if (err) { + } else { + console.log("My buckets now are:\n"); + + for (var i = 0; i < data.Buckets.length; i++) { + console.log(data.Buckets[i].Name); + } + } - AWS.config.update({ - region: region + callback(err); }); +} - var s3 = new AWS.S3({apiVersion: '2006-03-01'}); - var bucket_name = process.argv[2]; - var region = process.argv[3]; +// Create a bucket in this AWS Region. +function createMyBucket(callback) { + console.log("\nCreating a bucket named " + bucket_name + "...\n"); - var create_bucket_params = { - Bucket: bucket_name, - CreateBucketConfiguration: { - LocationConstraint: region + s3.createBucket(create_bucket_params, function (err, data) { + if (err) { + console.log(err.code + ": " + err.message); } - }; - - var delete_bucket_params = {Bucket: bucket_name}; - - // List all of your available buckets in this AWS Region. - function listMyBuckets(callback) { - s3.listBuckets(function(err, data) { - if (err) { - - } else { - console.log("My buckets now are:\n"); - - for (var i = 0; i < data.Buckets.length; i++) { - console.log(data.Buckets[i].Name); - } - } - callback(err); - }); - } - - // Create a bucket in this AWS Region. - function createMyBucket(callback) { - console.log('\nCreating a bucket named ' + bucket_name + '...\n'); - - s3.createBucket(create_bucket_params, function(err, data) { - if (err) { - console.log(err.code + ": " + err.message); - } - - callback(err); - }); - } + callback(err); + }); +} - // Delete the bucket you just created. - function deleteMyBucket(callback) { - console.log('\nDeleting the bucket named ' + bucket_name + '...\n'); +// Delete the bucket you just created. +function deleteMyBucket(callback) { + console.log("\nDeleting the bucket named " + bucket_name + "...\n"); - s3.deleteBucket(delete_bucket_params, function(err, data) { - if (err) { - console.log(err.code + ": " + err.message); - } + s3.deleteBucket(delete_bucket_params, function (err, data) { + if (err) { + console.log(err.code + ": " + err.message); + } - callback(err); - }); - } - - // Call the AWS operations in the following order. - async.series([ - listMyBuckets, - createMyBucket, - listMyBuckets, - deleteMyBucket, - listMyBuckets - ]); - // snippet-end:[s3.javascript.bucket_operations.list_create_delete] + callback(err); + }); +} + +// Call the AWS operations in the following order. +async.series([ + listMyBuckets, + createMyBucket, + listMyBuckets, + deleteMyBucket, + listMyBuckets, +]); +// snippet-end:[s3.javascript.bucket_operations.list_create_delete] diff --git a/javascript/example_code/s3/s3_PhotoViewer.js b/javascript/example_code/s3/s3_PhotoViewer.js index cc82a67edef..55a5df811e8 100644 --- a/javascript/example_code/s3/s3_PhotoViewer.js +++ b/javascript/example_code/s3/s3_PhotoViewer.js @@ -1,28 +1,5 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[s3_PhotoViewer.js demonstrates how to allow viewing of photos in albums stored in an Amazon S3 bucket.] -// snippet-service:[s3] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon S3] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-05-07] -// snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS JAVASCRIPT SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-photos-view.html @@ -36,31 +13,30 @@ // **DO THIS**: // Replace BUCKET_NAME with the bucket name. // -var albumBucketName = 'BUCKET_NAME'; +var albumBucketName = "BUCKET_NAME"; // **DO THIS**: // Replace this block of code with the sample code located at: // Cognito -- Manage Identity Pools -- [identity_pool_name] -- Sample Code -- JavaScript // // Initialize the Amazon Cognito credentials provider -AWS.config.region = 'REGION'; // Region +AWS.config.region = "REGION"; // Region AWS.config.credentials = new AWS.CognitoIdentityCredentials({ - IdentityPoolId: 'IDENTITY_POOL_ID', + IdentityPoolId: "IDENTITY_POOL_ID", }); // Create a new service object var s3 = new AWS.S3({ - apiVersion: '2006-03-01', - params: {Bucket: albumBucketName} + apiVersion: "2006-03-01", + params: { Bucket: albumBucketName }, }); // A utility function to create HTML. function getHtml(template) { - return template.join('\n'); + return template.join("\n"); } // snippet-end:[s3.JavaScript.s3_PhotoViewer.config] - // // Functions // @@ -68,34 +44,34 @@ function getHtml(template) { // snippet-start:[s3.JavaScript.s3_PhotoViewer.listAlbums] // List the photo albums that exist in the bucket. function listAlbums() { - s3.listObjects({Delimiter: '/'}, function(err, data) { + s3.listObjects({ Delimiter: "/" }, function (err, data) { if (err) { - return alert('There was an error listing your albums: ' + err.message); + return alert("There was an error listing your albums: " + err.message); } else { - var albums = data.CommonPrefixes.map(function(commonPrefix) { + var albums = data.CommonPrefixes.map(function (commonPrefix) { var prefix = commonPrefix.Prefix; - var albumName = decodeURIComponent(prefix.replace('/', '')); + var albumName = decodeURIComponent(prefix.replace("/", "")); return getHtml([ - '
  • ', - '', - '
  • ' + "
  • ", + '", + "
  • ", ]); }); - var message = albums.length ? - getHtml([ - '

    Click on an album name to view it.

    ', - ]) : - '

    You do not have any albums. Please Create album.'; + var message = albums.length + ? getHtml(["

    Click on an album name to view it.

    "]) + : "

    You do not have any albums. Please Create album."; var htmlTemplate = [ - '

    Albums

    ', + "

    Albums

    ", message, - '
      ', - getHtml(albums), - '
    ', - ] - document.getElementById('viewer').innerHTML = getHtml(htmlTemplate); + "
      ", + getHtml(albums), + "
    ", + ]; + document.getElementById("viewer").innerHTML = getHtml(htmlTemplate); } }); } @@ -104,59 +80,61 @@ function listAlbums() { // snippet-start:[s3.JavaScript.s3_PhotoViewer.viewAlbum] // Show the photos that exist in an album. function viewAlbum(albumName) { - var albumPhotosKey = encodeURIComponent(albumName) + '/'; - s3.listObjects({Prefix: albumPhotosKey}, function(err, data) { + var albumPhotosKey = encodeURIComponent(albumName) + "/"; + s3.listObjects({ Prefix: albumPhotosKey }, function (err, data) { if (err) { - return alert('There was an error viewing your album: ' + err.message); + return alert("There was an error viewing your album: " + err.message); } // 'this' references the AWS.Request instance that represents the response var href = this.request.httpRequest.endpoint.href; - var bucketUrl = href + albumBucketName + '/'; + var bucketUrl = href + albumBucketName + "/"; - var photos = data.Contents.map(function(photo) { + var photos = data.Contents.map(function (photo) { var photoKey = photo.Key; var photoUrl = bucketUrl + encodeURIComponent(photoKey); return getHtml([ - '', - '
    ', - '
    ', - '', - '
    ', - '
    ', - '', - photoKey.replace(albumPhotosKey, ''), - '', - '
    ', - '
    ', + "", + "
    ", + "
    ", + '', + "
    ", + "
    ", + "", + photoKey.replace(albumPhotosKey, ""), + "", + "
    ", + "
    ", ]); }); - var message = photos.length ? - '

    The following photos are present.

    ' : - '

    There are no photos in this album.

    '; + var message = photos.length + ? "

    The following photos are present.

    " + : "

    There are no photos in this album.

    "; var htmlTemplate = [ - '
    ', - '', - '
    ', - '

    ', - 'Album: ' + albumName, - '

    ', + "
    ", + '", + "
    ", + "

    ", + "Album: " + albumName, + "

    ", message, - '
    ', - getHtml(photos), - '
    ', - '

    ', - 'End of Album: ' + albumName, - '

    ', - '
    ', - '', - '
    ', - ] - document.getElementById('viewer').innerHTML = getHtml(htmlTemplate); - document.getElementsByTagName('img')[0].setAttribute('style', 'display:none;'); + "
    ", + getHtml(photos), + "
    ", + "

    ", + "End of Album: " + albumName, + "

    ", + "
    ", + '", + "
    ", + ]; + document.getElementById("viewer").innerHTML = getHtml(htmlTemplate); + document + .getElementsByTagName("img")[0] + .setAttribute("style", "display:none;"); }); } // snippet-end:[s3.JavaScript.s3_PhotoViewer.viewAlbum] diff --git a/javascript/example_code/s3/s3_createbucket.js b/javascript/example_code/s3/s3_createbucket.js index 409927d021d..902e78e3ad6 100755 --- a/javascript/example_code/s3/s3_createbucket.js +++ b/javascript/example_code/s3/s3_createbucket.js @@ -1,46 +1,25 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[s3_createbucket.js demonstrates how to create an Amazon S3 bucket.] -//snippet-service:[s3] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-creating-buckets.html // snippet-start:[s3.JavaScript.buckets.createBucket] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set the region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create S3 service object -s3 = new AWS.S3({apiVersion: '2006-03-01'}); +s3 = new AWS.S3({ apiVersion: "2006-03-01" }); // Create the parameters for calling createBucket var bucketParams = { - Bucket : process.argv[2] + Bucket: process.argv[2], }; // call S3 to create the bucket -s3.createBucket(bucketParams, function(err, data) { +s3.createBucket(bucketParams, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/s3/s3_deletebucket.js b/javascript/example_code/s3/s3_deletebucket.js index 143bc246fb9..590f6534216 100755 --- a/javascript/example_code/s3/s3_deletebucket.js +++ b/javascript/example_code/s3/s3_deletebucket.js @@ -1,46 +1,25 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[s3_deletebucket.js demonstrates how to delete an Amazon S3 bucket.] -//snippet-service:[s3] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-creating-buckets.html // snippet-start:[s3.JavaScript.buckets.deleteBucket] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set the region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create S3 service object -s3 = new AWS.S3({apiVersion: '2006-03-01'}); +s3 = new AWS.S3({ apiVersion: "2006-03-01" }); // Create params for S3.deleteBucket var bucketParams = { - Bucket : 'BUCKET_NAME' + Bucket: "BUCKET_NAME", }; // Call S3 to delete the bucket -s3.deleteBucket(bucketParams, function(err, data) { +s3.deleteBucket(bucketParams, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/s3/s3_deletebucketpolicy.js b/javascript/example_code/s3/s3_deletebucketpolicy.js index 4a8099957ad..7f2778cd4a7 100755 --- a/javascript/example_code/s3/s3_deletebucketpolicy.js +++ b/javascript/example_code/s3/s3_deletebucketpolicy.js @@ -1,42 +1,21 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[s3_deletebucketpolicy.js demonstrates how to delete an Amazon S3 bucket policy.] -//snippet-service:[s3] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-bucket-policies.html // snippet-start:[s3.JavaScript.policy.deleteBucketPolicy] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create S3 service object -s3 = new AWS.S3({apiVersion: '2006-03-01'}); +s3 = new AWS.S3({ apiVersion: "2006-03-01" }); -var bucketParams = {Bucket: process.argv[2]}; +var bucketParams = { Bucket: process.argv[2] }; // call S3 to delete policy for selected bucket -s3.deleteBucketPolicy(bucketParams, function(err, data) { +s3.deleteBucketPolicy(bucketParams, function (err, data) { if (err) { console.log("Error", err); } else if (data) { diff --git a/javascript/example_code/s3/s3_deletebucketwebsite.js b/javascript/example_code/s3/s3_deletebucketwebsite.js index 2963c80c517..03af7e7953a 100755 --- a/javascript/example_code/s3/s3_deletebucketwebsite.js +++ b/javascript/example_code/s3/s3_deletebucketwebsite.js @@ -1,43 +1,22 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[s3_deletebucketwebsite.js demonstrates how to delete the website configuration from an Amazon S3 bucket.] -//snippet-service:[s3] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-static-web-host.html // snippet-start:[s3.JavaScript.website.deleteBucketWebsite] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create S3 service object -s3 = new AWS.S3({apiVersion: '2006-03-01'}); +s3 = new AWS.S3({ apiVersion: "2006-03-01" }); -var bucketParams = {Bucket: process.argv[2]}; +var bucketParams = { Bucket: process.argv[2] }; // call S3 to delete website configuration for selected bucket -s3.deleteBucketWebsite(bucketParams, function(error, data) { +s3.deleteBucketWebsite(bucketParams, function (error, data) { if (error) { console.log("Error", err); } else if (data) { diff --git a/javascript/example_code/s3/s3_get_presignedURL.js b/javascript/example_code/s3/s3_get_presignedURL.js index 31c109f5423..8c518e9264b 100644 --- a/javascript/example_code/s3/s3_get_presignedURL.js +++ b/javascript/example_code/s3/s3_get_presignedURL.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS SAMPLE: This sample is part of the Amazon S3 Developer Guide topic at https://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjectPreSignedURLJavaScriptSDK.html @@ -18,7 +19,7 @@ Running the code: node s3_presignedURLs.js REGION BUCKET_NAME FILE_NAME */ // snippet-start:[s3.JavaScript.get.presignedURL.complete] -const AWS = require('aws-sdk'); +const AWS = require("aws-sdk"); // Set the AWS region const region = process.argv[2]; // REGION AWS.config.update(region); @@ -27,12 +28,12 @@ const s3 = new AWS.S3(); // Set the parameters const myBucket = process.argv[3]; //BUCKET_NAME const myKey = process.argv[4]; // FILE_NAME -const signedUrlExpireSeconds = 60*5; //EXPIRATION +const signedUrlExpireSeconds = 60 * 5; //EXPIRATION -const presignedURL = s3.getSignedUrl('getObject', { - Bucket: myBucket, - Key: myKey, - Expires: signedUrlExpireSeconds -}) -console.log(presignedURL) +const presignedURL = s3.getSignedUrl("getObject", { + Bucket: myBucket, + Key: myKey, + Expires: signedUrlExpireSeconds, +}); +console.log(presignedURL); // snippet-end:[s3.JavaScript.get.presignedURL.complete] diff --git a/javascript/example_code/s3/s3_getbucketacl.js b/javascript/example_code/s3/s3_getbucketacl.js index ca7494a1dad..3acc1c3423c 100755 --- a/javascript/example_code/s3/s3_getbucketacl.js +++ b/javascript/example_code/s3/s3_getbucketacl.js @@ -1,42 +1,21 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[s3_getbucketacl.js demonstrates how to retrieve the access control list of an Amazon S3 bucket.] -//snippet-service:[s3] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-access-permissions.html // snippet-start:[s3.JavaScript.perms.getBucketAcl] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create S3 service object -s3 = new AWS.S3({apiVersion: '2006-03-01'}); +s3 = new AWS.S3({ apiVersion: "2006-03-01" }); -var bucketParams = {Bucket: process.argv[2]}; +var bucketParams = { Bucket: process.argv[2] }; // call S3 to retrieve policy for selected bucket -s3.getBucketAcl(bucketParams, function(err, data) { +s3.getBucketAcl(bucketParams, function (err, data) { if (err) { console.log("Error", err); } else if (data) { diff --git a/javascript/example_code/s3/s3_getbucketpolicy.js b/javascript/example_code/s3/s3_getbucketpolicy.js index 2779ad8fb68..36c29e6c11f 100755 --- a/javascript/example_code/s3/s3_getbucketpolicy.js +++ b/javascript/example_code/s3/s3_getbucketpolicy.js @@ -1,42 +1,21 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[s3_getbucketpolicy.js demonstrates how to retrieve the policy of an Amazon S3 bucket.] -//snippet-service:[s3] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-bucket-policies.html // snippet-start:[s3.JavaScript.policy.getBucketPolicy] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create S3 service object -s3 = new AWS.S3({apiVersion: '2006-03-01'}); +s3 = new AWS.S3({ apiVersion: "2006-03-01" }); -var bucketParams = {Bucket: process.argv[2]}; +var bucketParams = { Bucket: process.argv[2] }; // call S3 to retrieve policy for selected bucket -s3.getBucketPolicy(bucketParams, function(err, data) { +s3.getBucketPolicy(bucketParams, function (err, data) { if (err) { console.log("Error", err); } else if (data) { diff --git a/javascript/example_code/s3/s3_getbucketwebsite.js b/javascript/example_code/s3/s3_getbucketwebsite.js index 9adfc525983..6ecfe31cf30 100755 --- a/javascript/example_code/s3/s3_getbucketwebsite.js +++ b/javascript/example_code/s3/s3_getbucketwebsite.js @@ -1,43 +1,22 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[s3_getbucketwebsite.js demonstrates how to retrieve the website configuration of an Amazon S3 bucket.] -//snippet-service:[s3] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-static-web-host.html // snippet-start:[s3.JavaScript.website.getBucketWebsite] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create S3 service object -s3 = new AWS.S3({apiVersion: '2006-03-01'}); +s3 = new AWS.S3({ apiVersion: "2006-03-01" }); -var bucketParams = {Bucket: process.argv[2]}; +var bucketParams = { Bucket: process.argv[2] }; // call S3 to retrieve the website configuration for selected bucket -s3.getBucketWebsite(bucketParams, function(err, data) { +s3.getBucketWebsite(bucketParams, function (err, data) { if (err) { console.log("Error", err); } else if (data) { diff --git a/javascript/example_code/s3/s3_getcors.js b/javascript/example_code/s3/s3_getcors.js index 4df105054f7..32d4c87f836 100755 --- a/javascript/example_code/s3/s3_getcors.js +++ b/javascript/example_code/s3/s3_getcors.js @@ -1,44 +1,23 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[s3_getcors.js demonstrates how to retrieve the CORS configuration of an Amazon S3 bucket.] -//snippet-service:[s3] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-configuring-buckets.html // snippet-start:[s3.JavaScript.cors.getBucketCors] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create S3 service object -s3 = new AWS.S3({apiVersion: '2006-03-01'}); +s3 = new AWS.S3({ apiVersion: "2006-03-01" }); // Set the parameters for S3.getBucketCors -var bucketParams = {Bucket: process.argv[2]}; +var bucketParams = { Bucket: process.argv[2] }; // call S3 to retrieve CORS configuration for selected bucket -s3.getBucketCors(bucketParams, function(err, data) { +s3.getBucketCors(bucketParams, function (err, data) { if (err) { console.log("Error", err); } else if (data) { diff --git a/javascript/example_code/s3/s3_getsignedURL.js b/javascript/example_code/s3/s3_getsignedURL.js index 6aa44e6feba..d46a4e2e78d 100644 --- a/javascript/example_code/s3/s3_getsignedURL.js +++ b/javascript/example_code/s3/s3_getsignedURL.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS SAMPLE: This sample is part of the Amazon S3 Developer Guide topic at https://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjectPreSignedURLJavaScriptSDK.html @@ -18,7 +19,7 @@ Running the code: node s3_getsignedURL.js REGION BUCKET_NAME FILE_NAME */ // snippet-start:[s3.JavaScript.presignedURL.complete] -const AWS = require('aws-sdk'); +const AWS = require("aws-sdk"); // Set the AWS region const region = process.argv[2]; // REGION AWS.config.update(region); @@ -27,12 +28,12 @@ const s3 = new AWS.S3(); // Set the parameters const myBucket = process.argv[3]; //BUCKET_NAME const myKey = process.argv[4]; // FILE_NAME -const signedUrlExpireSeconds = 60*5; //EXPIRATION +const signedUrlExpireSeconds = 60 * 5; //EXPIRATION -const presignedURL = s3.getSignedUrl('putObject', { - Bucket: myBucket, - Key: myKey, - Expires: signedUrlExpireSeconds -}) -console.log(presignedURL) +const presignedURL = s3.getSignedUrl("putObject", { + Bucket: myBucket, + Key: myKey, + Expires: signedUrlExpireSeconds, +}); +console.log(presignedURL); // snippet-end:[s3.JavaScript.presignedURL.complete] diff --git a/javascript/example_code/s3/s3_listbuckets.js b/javascript/example_code/s3/s3_listbuckets.js index 8e2daa02541..3b59749f4f3 100755 --- a/javascript/example_code/s3/s3_listbuckets.js +++ b/javascript/example_code/s3/s3_listbuckets.js @@ -1,41 +1,20 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[s3_listbuckets.js demonstrates how to list all the buckets in an AWS account.] -//snippet-service:[s3] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-creating-buckets.html // snippet-start:[s3.JavaScript.buckets.listBuckets] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create S3 service object -s3 = new AWS.S3({apiVersion: '2006-03-01'}); +s3 = new AWS.S3({ apiVersion: "2006-03-01" }); // Call S3 to list the buckets -s3.listBuckets(function(err, data) { +s3.listBuckets(function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/s3/s3_listobjects.js b/javascript/example_code/s3/s3_listobjects.js index f122ea0bca3..620b9eddda2 100755 --- a/javascript/example_code/s3/s3_listobjects.js +++ b/javascript/example_code/s3/s3_listobjects.js @@ -1,46 +1,25 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[s3_listobjects.js demonstrates how to list the objects in an Amazon S3 bucket.] -//snippet-service:[s3] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-creating-buckets.html // snippet-start:[s3.JavaScript.buckets.listObjects] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create S3 service object -s3 = new AWS.S3({apiVersion: '2006-03-01'}); +s3 = new AWS.S3({ apiVersion: "2006-03-01" }); // Create the parameters for calling listObjects var bucketParams = { - Bucket : 'BUCKET_NAME', + Bucket: "BUCKET_NAME", }; // Call S3 to obtain a list of the objects in the bucket -s3.listObjects(bucketParams, function(err, data) { +s3.listObjects(bucketParams, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/s3/s3_photoExample.js b/javascript/example_code/s3/s3_photoExample.js index ad748771d36..d5eaa5cb4cc 100644 --- a/javascript/example_code/s3/s3_photoExample.js +++ b/javascript/example_code/s3/s3_photoExample.js @@ -1,26 +1,5 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -//snippet-sourcedescription:[s3_PhotoExample.js demonstrates how to manipulate photos in albums stored in an Amazon S3 bucket.] -//snippet-service:[s3] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-photo-album.html @@ -34,23 +13,23 @@ var IdentityPoolId = "IDENTITY_POOL_ID"; AWS.config.update({ region: bucketRegion, credentials: new AWS.CognitoIdentityCredentials({ - IdentityPoolId: IdentityPoolId - }) + IdentityPoolId: IdentityPoolId, + }), }); var s3 = new AWS.S3({ apiVersion: "2006-03-01", - params: { Bucket: albumBucketName } + params: { Bucket: albumBucketName }, }); // snippet-end:[s3.JavaScript.photoAlbumExample.config] // snippet-start:[s3.JavaScript.photoAlbumExample.listAlbums] function listAlbums() { - s3.listObjects({ Delimiter: "/" }, function(err, data) { + s3.listObjects({ Delimiter: "/" }, function (err, data) { if (err) { return alert("There was an error listing your albums: " + err.message); } else { - var albums = data.CommonPrefixes.map(function(commonPrefix) { + var albums = data.CommonPrefixes.map(function (commonPrefix) { var prefix = commonPrefix.Prefix; var albumName = decodeURIComponent(prefix.replace("/", "")); return getHtml([ @@ -59,13 +38,13 @@ function listAlbums() { "", albumName, "", - "" + "", ]); }); var message = albums.length ? getHtml([ "

    Click on an album name to view it.

    ", - "

    Click on the X to delete the album.

    " + "

    Click on the X to delete the album.

    ", ]) : "

    You do not have any albums. Please Create album."; var htmlTemplate = [ @@ -76,7 +55,7 @@ function listAlbums() { "", "" + "", ]; document.getElementById("app").innerHTML = getHtml(htmlTemplate); } @@ -94,14 +73,14 @@ function createAlbum(albumName) { return alert("Album names cannot contain slashes."); } var albumKey = encodeURIComponent(albumName); - s3.headObject({ Key: albumKey }, function(err, data) { + s3.headObject({ Key: albumKey }, function (err, data) { if (!err) { return alert("Album already exists."); } if (err.code !== "NotFound") { return alert("There was an error creating your album: " + err.message); } - s3.putObject({ Key: albumKey }, function(err, data) { + s3.putObject({ Key: albumKey }, function (err, data) { if (err) { return alert("There was an error creating your album: " + err.message); } @@ -115,7 +94,7 @@ function createAlbum(albumName) { // snippet-start:[s3.JavaScript.photoAlbumExample.viewAlbum] function viewAlbum(albumName) { var albumPhotosKey = encodeURIComponent(albumName) + "/"; - s3.listObjects({ Prefix: albumPhotosKey }, function(err, data) { + s3.listObjects({ Prefix: albumPhotosKey }, function (err, data) { if (err) { return alert("There was an error viewing your album: " + err.message); } @@ -123,7 +102,7 @@ function viewAlbum(albumName) { var href = this.request.httpRequest.endpoint.href; var bucketUrl = href + albumBucketName + "/"; - var photos = data.Contents.map(function(photo) { + var photos = data.Contents.map(function (photo) { var photoKey = photo.Key; var photoUrl = bucketUrl + encodeURIComponent(photoKey); return getHtml([ @@ -143,7 +122,7 @@ function viewAlbum(albumName) { photoKey.replace(albumPhotosKey, ""), "", "", - "" + "", ]); }); var message = photos.length @@ -163,7 +142,7 @@ function viewAlbum(albumName) { "", '" + "", ]; document.getElementById("app").innerHTML = getHtml(htmlTemplate); }); @@ -187,18 +166,18 @@ function addPhoto(albumName) { params: { Bucket: albumBucketName, Key: photoKey, - Body: file - } + Body: file, + }, }); var promise = upload.promise(); promise.then( - function(data) { + function (data) { alert("Successfully uploaded photo."); viewAlbum(albumName); }, - function(err) { + function (err) { return alert("There was an error uploading your photo: ", err.message); } ); @@ -207,7 +186,7 @@ function addPhoto(albumName) { // snippet-start:[s3.JavaScript.photoAlbumExample.deletePhoto] function deletePhoto(albumName, photoKey) { - s3.deleteObject({ Key: photoKey }, function(err, data) { + s3.deleteObject({ Key: photoKey }, function (err, data) { if (err) { return alert("There was an error deleting your photo: ", err.message); } @@ -220,18 +199,18 @@ function deletePhoto(albumName, photoKey) { // snippet-start:[s3.JavaScript.photoAlbumExample.deleteAlbum] function deleteAlbum(albumName) { var albumKey = encodeURIComponent(albumName) + "/"; - s3.listObjects({ Prefix: albumKey }, function(err, data) { + s3.listObjects({ Prefix: albumKey }, function (err, data) { if (err) { return alert("There was an error deleting your album: ", err.message); } - var objects = data.Contents.map(function(object) { + var objects = data.Contents.map(function (object) { return { Key: object.Key }; }); s3.deleteObjects( { - Delete: { Objects: objects, Quiet: true } + Delete: { Objects: objects, Quiet: true }, }, - function(err, data) { + function (err, data) { if (err) { return alert("There was an error deleting your album: ", err.message); } diff --git a/javascript/example_code/s3/s3_presignedURL.js b/javascript/example_code/s3/s3_presignedURL.js index 5c2ddf185ec..1a3d6bc4cd6 100644 --- a/javascript/example_code/s3/s3_presignedURL.js +++ b/javascript/example_code/s3/s3_presignedURL.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS SAMPLE: This sample is part of the Amazon S3 Developer Guide topic at https://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjectPreSignedURLJavaScriptSDK.html @@ -18,7 +19,7 @@ Running the code: node s3_presignedURLs.js */ // snippet-start:[s3.JavaScript.buckets.presignedURL.complete] -const AWS = require('aws-sdk'); +const AWS = require("aws-sdk"); // Set the AWS region const region = "REGION"; // REGION AWS.config.update(region); @@ -27,12 +28,12 @@ const s3 = new AWS.S3(); // Set the parameters const myBucket = "BUCKET_NAME"; //BUCKET_NAME const myKey = "FILE_NAME"; // FILE_NAME -const signedUrlExpireSeconds = 60*5; //EXPIRATION +const signedUrlExpireSeconds = 60 * 5; //EXPIRATION -const presignedURL = s3.getSignedUrl('putObject', { - Bucket: myBucket, - Key: myKey, - Expires: signedUrlExpireSeconds -}) -console.log(presignedURL) +const presignedURL = s3.getSignedUrl("putObject", { + Bucket: myBucket, + Key: myKey, + Expires: signedUrlExpireSeconds, +}); +console.log(presignedURL); // snippet-end:[s3.JavaScript.buckets.presignedURL.complete] diff --git a/javascript/example_code/s3/s3_setbucketpolicy.js b/javascript/example_code/s3/s3_setbucketpolicy.js index a4f415d7431..2d00279f82b 100755 --- a/javascript/example_code/s3/s3_setbucketpolicy.js +++ b/javascript/example_code/s3/s3_setbucketpolicy.js @@ -1,38 +1,17 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[s3_setbucketpolicy.js demonstrates how to set/replace an Amazon S3 bucket policy.] -//snippet-service:[s3] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-bucket-policies.html // snippet-start:[s3.JavaScript.policy.putBucketPolicy] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create S3 service object -s3 = new AWS.S3({apiVersion: '2006-03-01'}); +s3 = new AWS.S3({ apiVersion: "2006-03-01" }); var readOnlyAnonUserPolicy = { Version: "2012-10-17", @@ -41,14 +20,10 @@ var readOnlyAnonUserPolicy = { Sid: "AddPerm", Effect: "Allow", Principal: "*", - Action: [ - "s3:GetObject" - ], - Resource: [ - "" - ] - } - ] + Action: ["s3:GetObject"], + Resource: [""], + }, + ], }; // create selected bucket resource string for bucket policy @@ -56,10 +31,13 @@ var bucketResource = "arn:aws:s3:::" + process.argv[2] + "/*"; readOnlyAnonUserPolicy.Statement[0].Resource[0] = bucketResource; // convert policy JSON into string and assign into params -var bucketPolicyParams = {Bucket: process.argv[2], Policy: JSON.stringify(readOnlyAnonUserPolicy)}; +var bucketPolicyParams = { + Bucket: process.argv[2], + Policy: JSON.stringify(readOnlyAnonUserPolicy), +}; // set the new policy on the selected bucket -s3.putBucketPolicy(bucketPolicyParams, function(err, data) { +s3.putBucketPolicy(bucketPolicyParams, function (err, data) { if (err) { // display error message console.log("Error", err); diff --git a/javascript/example_code/s3/s3_setbucketwebsite.js b/javascript/example_code/s3/s3_setbucketwebsite.js index 872437b9e32..809bcf2def7 100755 --- a/javascript/example_code/s3/s3_setbucketwebsite.js +++ b/javascript/example_code/s3/s3_setbucketwebsite.js @@ -1,50 +1,29 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[s3_setbucketwebsite.js demonstrates how to set the website configuration of an Amazon S3 bucket.] -//snippet-service:[s3] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-static-web-host.html // snippet-start:[s3.JavaScript.website.putBucketWebsite] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create S3 service object -s3 = new AWS.S3({apiVersion: '2006-03-01'}); +s3 = new AWS.S3({ apiVersion: "2006-03-01" }); // Create JSON for putBucketWebsite parameters var staticHostParams = { - Bucket: '', + Bucket: "", WebsiteConfiguration: { ErrorDocument: { - Key: '' + Key: "", }, IndexDocument: { - Suffix: '' + Suffix: "", }, - } + }, }; // Insert specified bucket name and index and error documents into params JSON @@ -54,7 +33,7 @@ staticHostParams.WebsiteConfiguration.IndexDocument.Suffix = process.argv[3]; staticHostParams.WebsiteConfiguration.ErrorDocument.Key = process.argv[4]; // set the new website configuration on the selected bucket -s3.putBucketWebsite(staticHostParams, function(err, data) { +s3.putBucketWebsite(staticHostParams, function (err, data) { if (err) { // display error message console.log("Error", err); diff --git a/javascript/example_code/s3/s3_setcors.js b/javascript/example_code/s3/s3_setcors.js index c5d62f32612..cf1e850be93 100755 --- a/javascript/example_code/s3/s3_setcors.js +++ b/javascript/example_code/s3/s3_setcors.js @@ -1,57 +1,48 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[s3_setcors.js demonstrates how to set the CORS configuration of an Amazon S3 bucket] -//snippet-service:[s3] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-configuring-buckets.html // snippet-start:[s3.JavaScript.cors.putBucketCors] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create S3 service object -s3 = new AWS.S3({apiVersion: '2006-03-01'}); +s3 = new AWS.S3({ apiVersion: "2006-03-01" }); // Create initial parameters JSON for putBucketCors var thisConfig = { - AllowedHeaders:["Authorization"], - AllowedMethods:[], - AllowedOrigins:["*"], - ExposeHeaders:[], - MaxAgeSeconds:3000 + AllowedHeaders: ["Authorization"], + AllowedMethods: [], + AllowedOrigins: ["*"], + ExposeHeaders: [], + MaxAgeSeconds: 3000, }; // Assemble the list of allowed methods based on command line parameters var allowedMethods = []; process.argv.forEach(function (val, index, array) { - if (val.toUpperCase() === "POST") {allowedMethods.push("POST")}; - if (val.toUpperCase() === "GET") {allowedMethods.push("GET")}; - if (val.toUpperCase() === "PUT") {allowedMethods.push("PUT")}; - if (val.toUpperCase() === "PATCH") {allowedMethods.push("PATCH")}; - if (val.toUpperCase() === "DELETE") {allowedMethods.push("DELETE")}; - if (val.toUpperCase() === "HEAD") {allowedMethods.push("HEAD")}; + if (val.toUpperCase() === "POST") { + allowedMethods.push("POST"); + } + if (val.toUpperCase() === "GET") { + allowedMethods.push("GET"); + } + if (val.toUpperCase() === "PUT") { + allowedMethods.push("PUT"); + } + if (val.toUpperCase() === "PATCH") { + allowedMethods.push("PATCH"); + } + if (val.toUpperCase() === "DELETE") { + allowedMethods.push("DELETE"); + } + if (val.toUpperCase() === "HEAD") { + allowedMethods.push("HEAD"); + } }); // Copy the array of allowed methods into the config object @@ -60,10 +51,13 @@ thisConfig.AllowedMethods = allowedMethods; var corsRules = new Array(thisConfig); // Create CORS params -var corsParams = {Bucket: process.argv[2], CORSConfiguration: {CORSRules: corsRules}}; +var corsParams = { + Bucket: process.argv[2], + CORSConfiguration: { CORSRules: corsRules }, +}; // set the new CORS configuration on the selected bucket -s3.putBucketCors(corsParams, function(err, data) { +s3.putBucketCors(corsParams, function (err, data) { if (err) { // display error message console.log("Error", err); diff --git a/javascript/example_code/s3/s3_upload.js b/javascript/example_code/s3/s3_upload.js index 4a71b9abaad..5bdd3c4f84f 100755 --- a/javascript/example_code/s3/s3_upload.js +++ b/javascript/example_code/s3/s3_upload.js @@ -1,58 +1,38 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[s3_upload.js demonstrates how to upload an arbitrarily-sized stream to an Amazon S3 bucket.] -//snippet-service:[s3] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon S3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-creating-buckets.html // snippet-start:[s3.JavaScript.buckets.upload] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create S3 service object -var s3 = new AWS.S3({apiVersion: '2006-03-01'}); +var s3 = new AWS.S3({ apiVersion: "2006-03-01" }); // call S3 to retrieve upload file to specified bucket -var uploadParams = {Bucket: process.argv[2], Key: '', Body: ''}; +var uploadParams = { Bucket: process.argv[2], Key: "", Body: "" }; var file = process.argv[3]; // Configure the file stream and obtain the upload parameters -var fs = require('fs'); +var fs = require("fs"); var fileStream = fs.createReadStream(file); -fileStream.on('error', function(err) { - console.log('File Error', err); +fileStream.on("error", function (err) { + console.log("File Error", err); }); uploadParams.Body = fileStream; -var path = require('path'); +var path = require("path"); uploadParams.Key = path.basename(file); // call S3 to retrieve upload file to specified bucket -s3.upload (uploadParams, function (err, data) { +s3.upload(uploadParams, function (err, data) { if (err) { console.log("Error", err); - } if (data) { + } + if (data) { console.log("Upload Success", data.Location); } }); diff --git a/javascript/example_code/secrets/secrets_getsecretvalue.js b/javascript/example_code/secrets/secrets_getsecretvalue.js index 39baaf45c00..3c5dcbc947b 100644 --- a/javascript/example_code/secrets/secrets_getsecretvalue.js +++ b/javascript/example_code/secrets/secrets_getsecretvalue.js @@ -1,27 +1,5 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[secrets_getsecretvalue.js demonstrates how to retrieve a secret from AWS Secrets Manager.] -//snippet-service:[secretsmanager] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Secrets Manager] -// snippet-keyword:[GetSecretValue] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[9/25/18] -//snippet-sourceauthor:[AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the AWS Secrets Manager. // In this sample we only handle the specific exceptions for the 'GetSecretValue' API. @@ -30,55 +8,54 @@ // snippet-start:[secretsmanager.JavaScript.secrets.GetSecretValue] // Load the AWS SDK -var AWS = require('aws-sdk'), - region = "<<{{MyRegionName}}>>", - secretName = "<<{{MySecretName}}>>", - secret, - decodedBinarySecret; +var AWS = require("aws-sdk"), + region = "<<{{MyRegionName}}>>", + secretName = "<<{{MySecretName}}>>", + secret, + decodedBinarySecret; // Create a Secrets Manager client var client = new AWS.SecretsManager({ - region: region + region: region, }); // In this sample we only handle the specific exceptions for the 'GetSecretValue' API. // See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html // We rethrow the exception by default. -client.getSecretValue({SecretId: secretName}, function(err, data) { - if (err) { - if (err.code === 'DecryptionFailureException') - // Secrets Manager can't decrypt the protected secret text using the provided KMS key. - // Deal with the exception here, and/or rethrow at your discretion. - throw err; - else if (err.code === 'InternalServiceErrorException') - // An error occurred on the server side. - // Deal with the exception here, and/or rethrow at your discretion. - throw err; - else if (err.code === 'InvalidParameterException') - // You provided an invalid value for a parameter. - // Deal with the exception here, and/or rethrow at your discretion. - throw err; - else if (err.code === 'InvalidRequestException') - // You provided a parameter value that is not valid for the current state of the resource. - // Deal with the exception here, and/or rethrow at your discretion. - throw err; - else if (err.code === 'ResourceNotFoundException') - // We can't find the resource that you asked for. - // Deal with the exception here, and/or rethrow at your discretion. - throw err; +client.getSecretValue({ SecretId: secretName }, function (err, data) { + if (err) { + if (err.code === "DecryptionFailureException") + // Secrets Manager can't decrypt the protected secret text using the provided KMS key. + // Deal with the exception here, and/or rethrow at your discretion. + throw err; + else if (err.code === "InternalServiceErrorException") + // An error occurred on the server side. + // Deal with the exception here, and/or rethrow at your discretion. + throw err; + else if (err.code === "InvalidParameterException") + // You provided an invalid value for a parameter. + // Deal with the exception here, and/or rethrow at your discretion. + throw err; + else if (err.code === "InvalidRequestException") + // You provided a parameter value that is not valid for the current state of the resource. + // Deal with the exception here, and/or rethrow at your discretion. + throw err; + else if (err.code === "ResourceNotFoundException") + // We can't find the resource that you asked for. + // Deal with the exception here, and/or rethrow at your discretion. + throw err; + } else { + // Decrypts secret using the associated KMS CMK. + // Depending on whether the secret is a string or binary, one of these fields will be populated. + if ("SecretString" in data) { + secret = data.SecretString; + } else { + let buff = new Buffer(data.SecretBinary, "base64"); + decodedBinarySecret = buff.toString("ascii"); } - else { - // Decrypts secret using the associated KMS CMK. - // Depending on whether the secret is a string or binary, one of these fields will be populated. - if ('SecretString' in data) { - secret = data.SecretString; - } else { - let buff = new Buffer(data.SecretBinary, 'base64'); - decodedBinarySecret = buff.toString('ascii'); - } - } - - // Your code goes here. + } + + // Your code goes here. }); // snippet-end:[secretsmanager.JavaScript.secrets.GetSecretValue] diff --git a/javascript/example_code/ses/ses_clonereceiptruleset.js b/javascript/example_code/ses/ses_clonereceiptruleset.js index 28c87cee4e1..885d0741bfe 100644 --- a/javascript/example_code/ses/ses_clonereceiptruleset.js +++ b/javascript/example_code/ses/ses_clonereceiptruleset.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with AWS SDK for JavaScript version 2 (v2) Purpose: @@ -10,26 +11,27 @@ ses_clonereceiptruleset.js demonstrates how to clone an Amazon Simple Email Serv // snippet-start:[ses.JavaScript.filters.cloneReceiptRuleSet] // Load the AWS SDK for Node.js. -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set the AWS Region. -AWS.config.update({ region: 'REGION' }); +AWS.config.update({ region: "REGION" }); // Create cloneReceiptRuleSet parameters. var params = { - OriginalRuleSetName: "RULE_SET_TO_CLONE", - RuleSetName: "RULE_SET_TO_CREATE" + OriginalRuleSetName: "RULE_SET_TO_CLONE", + RuleSetName: "RULE_SET_TO_CREATE", }; - // Create the promise and SES service object. -var sendPromise = new AWS.SES({ apiVersion: '2010-12-01' }).cloneReceiptRuleSet(params).promise(); +var sendPromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .cloneReceiptRuleSet(params) + .promise(); // Handle promise's fulfilled/rejected states. -sendPromise.then( - function (data) { - console.log(data); - }).catch( - function (err) { - console.error(err, err.stack); - }); +sendPromise + .then(function (data) { + console.log(data); + }) + .catch(function (err) { + console.error(err, err.stack); + }); // snippet-end:[ses.JavaScript.filters.cloneReceiptRuleSet] diff --git a/javascript/example_code/ses/ses_createreceiptfilter.js b/javascript/example_code/ses/ses_createreceiptfilter.js index dacdead1663..c783a277fc8 100755 --- a/javascript/example_code/ses/ses_createreceiptfilter.js +++ b/javascript/example_code/ses/ses_createreceiptfilter.js @@ -1,58 +1,37 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[ses_createreceiptfilter.js demonstrates how to create an Amazon SES IP address filter.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Email Service] -//snippet-service:[ses] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-ip-filters.html // snippet-start:[ses.JavaScript.filters.createReceiptFilter] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create createReceiptFilter params var params = { - Filter: { - IpFilter: { - Cidr: "IP_ADDRESS_OR_RANGE", - Policy: "Allow" | "Block" + Filter: { + IpFilter: { + Cidr: "IP_ADDRESS_OR_RANGE", + Policy: "Allow" | "Block", + }, + Name: "NAME", }, - Name: "NAME" - } }; - // Create the promise and SES service object -var sendPromise = new AWS.SES({apiVersion: '2010-12-01'}).createReceiptFilter(params).promise(); +var sendPromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .createReceiptFilter(params) + .promise(); // Handle promise's fulfilled/rejected states -sendPromise.then( - function(data) { +sendPromise + .then(function (data) { console.log(data); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[ses.JavaScript.filters.createReceiptFilter] diff --git a/javascript/example_code/ses/ses_createreceiptrule.js b/javascript/example_code/ses/ses_createreceiptrule.js index 45670b6911b..056823ff350 100755 --- a/javascript/example_code/ses/ses_createreceiptrule.js +++ b/javascript/example_code/ses/ses_createreceiptrule.js @@ -1,70 +1,49 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[ses_createreceiptrule.js demonstrates how to create an Amazon SES receipt rule.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Email Service] -//snippet-service:[ses] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-receipt-rules.html - // snippet-start:[ses.JavaScript.rules.createReceiptRule] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); -// Create createReceiptRule params +// Create createReceiptRule params var params = { - Rule: { - Actions: [ - { - S3Action: { - BucketName: "S3_BUCKET_NAME", - ObjectKeyPrefix: "email" - } - } - ], + Rule: { + Actions: [ + { + S3Action: { + BucketName: "S3_BUCKET_NAME", + ObjectKeyPrefix: "email", + }, + }, + ], Recipients: [ - 'DOMAIN | EMAIL_ADDRESS', + "DOMAIN | EMAIL_ADDRESS", /* more items */ ], - Enabled: true | false, - Name: "RULE_NAME", - ScanEnabled: true | false, - TlsPolicy: "Optional" - }, - RuleSetName: "RULE_SET_NAME" + Enabled: true | false, + Name: "RULE_NAME", + ScanEnabled: true | false, + TlsPolicy: "Optional", + }, + RuleSetName: "RULE_SET_NAME", }; // Create the promise and SES service object -var newRulePromise = new AWS.SES({apiVersion: '2010-12-01'}).createReceiptRule(params).promise(); +var newRulePromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .createReceiptRule(params) + .promise(); // Handle promise's fulfilled/rejected states -newRulePromise.then( - function(data) { +newRulePromise + .then(function (data) { console.log("Rule created"); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[ses.JavaScript.rules.createReceiptRule] diff --git a/javascript/example_code/ses/ses_createreceiptruleset.js b/javascript/example_code/ses/ses_createreceiptruleset.js index f836b6cff97..72b9c32d790 100755 --- a/javascript/example_code/ses/ses_createreceiptruleset.js +++ b/javascript/example_code/ses/ses_createreceiptruleset.js @@ -1,46 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[ses_createreceiptruleset.js demonstrates how to create an empty Amazon SES rule set.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Email Service] -//snippet-service:[ses] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-receipt-rules.html // snippet-start:[ses.JavaScript.rules.createReceiptRuleSet] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the promise and SES service object -var newRulePromise = new AWS.SES({apiVersion: '2010-12-01'}).createReceiptRuleSet({RuleSetName: "NAME"}).promise(); +var newRulePromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .createReceiptRuleSet({ RuleSetName: "NAME" }) + .promise(); // Handle promise's fulfilled/rejected states -newRulePromise.then( - function(data) { +newRulePromise + .then(function (data) { console.log(data); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[ses.JavaScript.rules.createReceiptRuleSet] diff --git a/javascript/example_code/ses/ses_createtemplate.js b/javascript/example_code/ses/ses_createtemplate.js index a7758e7104e..91494a3d670 100755 --- a/javascript/example_code/ses/ses_createtemplate.js +++ b/javascript/example_code/ses/ses_createtemplate.js @@ -1,56 +1,36 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[ses_createtemplate.js demonstrates how to create an Amazon SES email template.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Email Service] -//snippet-service:[ses] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-creating-template.html // snippet-start:[ses.JavaScript.templates.createTemplate] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create createTemplate params var params = { - Template: { - TemplateName: 'TEMPLATE_NAME', /* required */ - HtmlPart: 'HTML_CONTENT', - SubjectPart: 'SUBJECT_LINE', - TextPart: 'TEXT_CONTENT' - } + Template: { + TemplateName: "TEMPLATE_NAME" /* required */, + HtmlPart: "HTML_CONTENT", + SubjectPart: "SUBJECT_LINE", + TextPart: "TEXT_CONTENT", + }, }; // Create the promise and SES service object -var templatePromise = new AWS.SES({apiVersion: '2010-12-01'}).createTemplate(params).promise(); +var templatePromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .createTemplate(params) + .promise(); // Handle promise's fulfilled/rejected states -templatePromise.then( - function(data) { +templatePromise + .then(function (data) { console.log(data); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[ses.JavaScript.templates.createTemplate] diff --git a/javascript/example_code/ses/ses_deleteidentity.js b/javascript/example_code/ses/ses_deleteidentity.js index b30ef4dc404..651436fef88 100755 --- a/javascript/example_code/ses/ses_deleteidentity.js +++ b/javascript/example_code/ses/ses_deleteidentity.js @@ -1,46 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[ses_deleteidentity.js demonstrates how to delete an Amazon SES identity.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Email Service] -//snippet-service:[ses] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-managing-identities.html // snippet-start:[ses.JavaScript.identities.deleteIdentity] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set region +AWS.config.update({ region: "REGION" }); // Create the promise and SES service object -var deletePromise = new AWS.SES({apiVersion: '2010-12-01'}).deleteIdentity({Identity: "DOMAIN_NAME"}).promise(); +var deletePromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .deleteIdentity({ Identity: "DOMAIN_NAME" }) + .promise(); // Handle promise's fulfilled/rejected states -deletePromise.then( - function(data) { +deletePromise + .then(function (data) { console.log("Identity Deleted"); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[ses.JavaScript.identities.deleteIdentity] diff --git a/javascript/example_code/ses/ses_deletereceiptfilter.js b/javascript/example_code/ses/ses_deletereceiptfilter.js index f307940a706..8354ba182f2 100755 --- a/javascript/example_code/ses/ses_deletereceiptfilter.js +++ b/javascript/example_code/ses/ses_deletereceiptfilter.js @@ -1,46 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[ses_deletereceiptfilter.js demonstrates how to delete an Amazon SES IP address filter.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Email Service] -//snippet-service:[ses] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-ip-filters.html // snippet-start:[ses.JavaScript.filters.deleteReceiptFilter] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the promise and SES service object -var sendPromise = new AWS.SES({apiVersion: '2010-12-01'}).deleteReceiptFilter({FilterName: "NAME"}).promise(); +var sendPromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .deleteReceiptFilter({ FilterName: "NAME" }) + .promise(); // Handle promise's fulfilled/rejected states -sendPromise.then( - function(data) { +sendPromise + .then(function (data) { console.log("IP Filter deleted"); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[ses.JavaScript.filters.deleteReceiptFilter] diff --git a/javascript/example_code/ses/ses_deletereceiptrule.js b/javascript/example_code/ses/ses_deletereceiptrule.js index 438f6b86741..ed0c92fc3b5 100755 --- a/javascript/example_code/ses/ses_deletereceiptrule.js +++ b/javascript/example_code/ses/ses_deletereceiptrule.js @@ -1,52 +1,32 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[ses_deletereceiptrule.js demonstrates how to delete an Amazon SES receipt rule.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Email Service] -//snippet-service:[ses] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-receipt-rules.html // snippet-start:[ses.JavaScript.rules.deleteReceiptRule] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create deleteReceiptRule params var params = { - RuleName: 'RULE_NAME', /* required */ - RuleSetName: 'RULE_SET_NAME' /* required */ + RuleName: "RULE_NAME" /* required */, + RuleSetName: "RULE_SET_NAME" /* required */, }; // Create the promise and SES service object -var newRulePromise = new AWS.SES({apiVersion: '2010-12-01'}).deleteReceiptRule(params).promise(); +var newRulePromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .deleteReceiptRule(params) + .promise(); // Handle promise's fulfilled/rejected states -newRulePromise.then( - function(data) { +newRulePromise + .then(function (data) { console.log("Receipt Rule Deleted"); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[ses.JavaScript.rules.deleteReceiptRule] diff --git a/javascript/example_code/ses/ses_deletereceiptruleset.js b/javascript/example_code/ses/ses_deletereceiptruleset.js index b0c917c0477..8ad75dc39ef 100755 --- a/javascript/example_code/ses/ses_deletereceiptruleset.js +++ b/javascript/example_code/ses/ses_deletereceiptruleset.js @@ -1,46 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[ses_deletereceiptruleset.js demonstrates how to delete an Amazon SES rule set.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Email Service] -//snippet-service:[ses] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-receipt-rules.html // snippet-start:[ses.JavaScript.rules.deleteReceiptRuleSet] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the promise and SES service object -var newRulePromise = new AWS.SES({apiVersion: '2010-12-01'}).deleteReceiptRuleSet({RuleSetName: "NAME"}).promise(); +var newRulePromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .deleteReceiptRuleSet({ RuleSetName: "NAME" }) + .promise(); // Handle promise's fulfilled/rejected states -newRulePromise.then( - function(data) { +newRulePromise + .then(function (data) { console.log(data); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[ses.JavaScript.rules.deleteReceiptRuleSet] diff --git a/javascript/example_code/ses/ses_deletetemplate.js b/javascript/example_code/ses/ses_deletetemplate.js index d011ea2c2de..e392abbeee0 100755 --- a/javascript/example_code/ses/ses_deletetemplate.js +++ b/javascript/example_code/ses/ses_deletetemplate.js @@ -1,46 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[ses_deletetemplate.js demonstrates how to delete an Amazon SES email template.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Email Service] -//snippet-service:[ses] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-creating-template.html // snippet-start:[ses.JavaScript.templates.deleteTemplate] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the promise and SES service object -var templatePromise = new AWS.SES({apiVersion: '2010-12-01'}).deleteTemplate({TemplateName: 'TEMPLATE_NAME'}).promise(); +var templatePromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .deleteTemplate({ TemplateName: "TEMPLATE_NAME" }) + .promise(); // Handle promise's fulfilled/rejected states -templatePromise.then( - function(data) { +templatePromise + .then(function (data) { console.log("Template Deleted"); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[ses.JavaScript.templates.deleteTemplate] diff --git a/javascript/example_code/ses/ses_gettemplate.js b/javascript/example_code/ses/ses_gettemplate.js index 4066996c285..e805434876c 100755 --- a/javascript/example_code/ses/ses_gettemplate.js +++ b/javascript/example_code/ses/ses_gettemplate.js @@ -1,46 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[ses_gettemplate.js demonstrates how to retrieve an Amazon SES email template.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Email Service] -//snippet-service:[ses] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-creating-template.html // snippet-start:[ses.JavaScript.templates.getTemplate] - // Load the AWS SDK for Node.js. -var AWS = require('aws-sdk'); +// Load the AWS SDK for Node.js. +var AWS = require("aws-sdk"); // Set the AWS Region. -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create the promise and Amazon Simple Email Service (Amazon SES) service object. -var templatePromise = new AWS.SES({apiVersion: '2010-12-01'}).getTemplate({TemplateName: 'TEMPLATE_NAME'}).promise(); +var templatePromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .getTemplate({ TemplateName: "TEMPLATE_NAME" }) + .promise(); // Handle promise's fulfilled/rejected states -templatePromise.then( - function(data) { +templatePromise + .then(function (data) { console.log(data.Template.SubjectPart); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[ses.JavaScript.templates.getTemplate] diff --git a/javascript/example_code/ses/ses_listidentities.js b/javascript/example_code/ses/ses_listidentities.js index 02f8d2c4587..8d1c7ab619d 100755 --- a/javascript/example_code/ses/ses_listidentities.js +++ b/javascript/example_code/ses/ses_listidentities.js @@ -1,52 +1,32 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[ses_listidentities.js demonstrates how to list all the identities for an AWS account.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Email Service] -//snippet-service:[ses] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-managing-identities.html // snippet-start:[ses.JavaScript.identities.listIdentities] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set region +AWS.config.update({ region: "REGION" }); -// Create listIdentities params +// Create listIdentities params var params = { - IdentityType: "Domain", - MaxItems: 10 + IdentityType: "Domain", + MaxItems: 10, }; // Create the promise and SES service object -var listIDsPromise = new AWS.SES({apiVersion: '2010-12-01'}).listIdentities(params).promise(); +var listIDsPromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .listIdentities(params) + .promise(); // Handle promise's fulfilled/rejected states -listIDsPromise.then( - function(data) { +listIDsPromise + .then(function (data) { console.log(data.Identities); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[ses.JavaScript.identities.listIdentities] diff --git a/javascript/example_code/ses/ses_listreceiptfilters.js b/javascript/example_code/ses/ses_listreceiptfilters.js index b5c3f534e14..4a0180b9920 100755 --- a/javascript/example_code/ses/ses_listreceiptfilters.js +++ b/javascript/example_code/ses/ses_listreceiptfilters.js @@ -1,46 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[ses_listreceiptfilters.js demonstrates how to list the Amazon SES IP filters for an AWS account.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Email Service] -//snippet-service:[ses] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-ip-filters.html // snippet-start:[ses.JavaScript.filters.listReceiptFilters] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the promise and SES service object -var sendPromise = new AWS.SES({apiVersion: '2010-12-01'}).listReceiptFilters({}).promise(); +var sendPromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .listReceiptFilters({}) + .promise(); // Handle promise's fulfilled/rejected states -sendPromise.then( - function(data) { +sendPromise + .then(function (data) { console.log(data.Filters); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[ses.JavaScript.filters.listReceiptFilters] diff --git a/javascript/example_code/ses/ses_listreceiptrulesets.js b/javascript/example_code/ses/ses_listreceiptrulesets.js index fb924b021ab..998d62f84fe 100644 --- a/javascript/example_code/ses/ses_listreceiptrulesets.js +++ b/javascript/example_code/ses/ses_listreceiptrulesets.js @@ -1,7 +1,7 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 - +/* ABOUT THIS NODE.JS EXAMPLE: This example works with AWS SDK for JavaScript version 2 (v2). Purpose: @@ -11,25 +11,26 @@ ses_listreceiptrulesets.js demonstrates how to list Amazon Simple Email Service // snippet-start:[ses.JavaScript.filters.listReceiptRuleSets] // Load the AWS SDK for Node.js. -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set the AWS Region. -AWS.config.update({ region: 'REGION' }); +AWS.config.update({ region: "REGION" }); // Create listReceiptRuleSets parameters. var params = { - NextToken: "" + NextToken: "", }; - // Create the promise and SES service object. -var sendPromise = new AWS.SES({ apiVersion: '2010-12-01' }).listReceiptRuleSets(params).promise(); +var sendPromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .listReceiptRuleSets(params) + .promise(); // Handle promise's fulfilled/rejected states. -sendPromise.then( - function (data) { - console.log(data); - }).catch( - function (err) { - console.error(err, err.stack); - }); +sendPromise + .then(function (data) { + console.log(data); + }) + .catch(function (err) { + console.error(err, err.stack); + }); // snippet-end:[ses.JavaScript.filters.listReceiptRuleSets] diff --git a/javascript/example_code/ses/ses_listtemplates.js b/javascript/example_code/ses/ses_listtemplates.js index c2e5f34caca..3e20efd3e99 100755 --- a/javascript/example_code/ses/ses_listtemplates.js +++ b/javascript/example_code/ses/ses_listtemplates.js @@ -1,46 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[ses_listtemplates.js demonstrates how to list the available Amazon SES email templates.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Email Service] -//snippet-service:[ses] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-creating-template.html // snippet-start:[ses.JavaScript.templates.listTemplates] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the promise and SES service object -var templatePromise = new AWS.SES({apiVersion: '2010-12-01'}).listTemplates({MaxItems: ITEMS_COUNT}).promise(); +var templatePromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .listTemplates({ MaxItems: ITEMS_COUNT }) + .promise(); // Handle promise's fulfilled/rejected states -templatePromise.then( - function(data) { +templatePromise + .then(function (data) { console.log(data); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[ses.JavaScript.templates.listTemplates] diff --git a/javascript/example_code/ses/ses_sendbulktemplatedemail.js b/javascript/example_code/ses/ses_sendbulktemplatedemail.js index 0f20077d924..2affdbec2e9 100755 --- a/javascript/example_code/ses/ses_sendbulktemplatedemail.js +++ b/javascript/example_code/ses/ses_sendbulktemplatedemail.js @@ -1,73 +1,52 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[ses_sendbulktemplatedemail.js demonstrates how to compose an Amazon SES templated email for multiple destinations and queue it for sending.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Email Service] -//snippet-service:[ses] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide//ses-examples-sending-email.html // snippet-start:[ses.JavaScript.email.sendBulkTemplatedEmail] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); -// Create sendBulkTemplatedEmail params +// Create sendBulkTemplatedEmail params var params = { - Destinations: [ /* required */ + Destinations: [ + /* required */ { - Destination: { /* required */ + Destination: { + /* required */ CcAddresses: [ - 'EMAIL_ADDRESS', + "EMAIL_ADDRESS", /* more items */ ], ToAddresses: [ - 'EMAIL_ADDRESS', - 'EMAIL_ADDRESS' + "EMAIL_ADDRESS", + "EMAIL_ADDRESS", /* more items */ - ] + ], }, - ReplacementTemplateData: '{ \"REPLACEMENT_TAG_NAME\":\"REPLACEMENT_VALUE\" }' - }, + ReplacementTemplateData: '{ "REPLACEMENT_TAG_NAME":"REPLACEMENT_VALUE" }', + }, ], - Source: 'EMAIL_ADDRESS', /* required */ - Template: 'TEMPLATE_NAME', /* required */ - DefaultTemplateData: '{ \"REPLACEMENT_TAG_NAME\":\"REPLACEMENT_VALUE\" }', - ReplyToAddresses: [ - 'EMAIL_ADDRESS' - ] + Source: "EMAIL_ADDRESS" /* required */, + Template: "TEMPLATE_NAME" /* required */, + DefaultTemplateData: '{ "REPLACEMENT_TAG_NAME":"REPLACEMENT_VALUE" }', + ReplyToAddresses: ["EMAIL_ADDRESS"], }; - // Create the promise and SES service object -var sendPromise = new AWS.SES({apiVersion: '2010-12-01'}).sendBulkTemplatedEmail(params).promise(); +var sendPromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .sendBulkTemplatedEmail(params) + .promise(); // Handle promise's fulfilled/rejected states -sendPromise.then( - function(data) { +sendPromise + .then(function (data) { console.log(data); - }).catch( - function(err) { + }) + .catch(function (err) { console.log(err, err.stack); }); // snippet-end:[ses.JavaScript.email.sendBulkTemplatedEmail] diff --git a/javascript/example_code/ses/ses_sendemail.js b/javascript/example_code/ses/ses_sendemail.js index 5cf6b1d9594..d6290850990 100755 --- a/javascript/example_code/ses/ses_sendemail.js +++ b/javascript/example_code/ses/ses_sendemail.js @@ -1,81 +1,64 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[ses_sendemail.js demonstrates how to compose an Amazon SES email and queue it for sending.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Email Service] -//snippet-service:[ses] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide//ses-examples-sending-email.html // snippet-start:[ses.JavaScript.email.sendEmail] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); -// Create sendEmail params +// Create sendEmail params var params = { - Destination: { /* required */ + Destination: { + /* required */ CcAddresses: [ - 'EMAIL_ADDRESS', + "EMAIL_ADDRESS", /* more items */ ], ToAddresses: [ - 'EMAIL_ADDRESS', + "EMAIL_ADDRESS", /* more items */ - ] + ], }, - Message: { /* required */ - Body: { /* required */ + Message: { + /* required */ + Body: { + /* required */ Html: { - Charset: "UTF-8", - Data: "HTML_FORMAT_BODY" + Charset: "UTF-8", + Data: "HTML_FORMAT_BODY", }, Text: { - Charset: "UTF-8", - Data: "TEXT_FORMAT_BODY" - } - }, - Subject: { - Charset: 'UTF-8', - Data: 'Test email' - } + Charset: "UTF-8", + Data: "TEXT_FORMAT_BODY", + }, }, - Source: 'SENDER_EMAIL_ADDRESS', /* required */ + Subject: { + Charset: "UTF-8", + Data: "Test email", + }, + }, + Source: "SENDER_EMAIL_ADDRESS" /* required */, ReplyToAddresses: [ - 'EMAIL_ADDRESS', + "EMAIL_ADDRESS", /* more items */ ], }; // Create the promise and SES service object -var sendPromise = new AWS.SES({apiVersion: '2010-12-01'}).sendEmail(params).promise(); +var sendPromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .sendEmail(params) + .promise(); // Handle promise's fulfilled/rejected states -sendPromise.then( - function(data) { +sendPromise + .then(function (data) { console.log(data.MessageId); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[ses.JavaScript.email.sendEmail] diff --git a/javascript/example_code/ses/ses_sendemailsmtp.js b/javascript/example_code/ses/ses_sendemailsmtp.js index 08a680d6bf7..1699dc8fa70 100644 --- a/javascript/example_code/ses/ses_sendemailsmtp.js +++ b/javascript/example_code/ses/ses_sendemailsmtp.js @@ -1,27 +1,6 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// snippet-sourcedescription:[ses_send_email_smtp demonstrates how to send a transactional email message by using the Amazon SES SMTP interface and the Nodemailer module.] -// snippet-service:[Amazon SES] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Amazon Simple Email Service] -// snippet-keyword:[Code Sample] -// snippet-keyword:[n/a] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2020-06-17] -// snippet-sourceauthor:[AWS] // snippet-start:[ses.javascript.ses_send_email_smtp.complete] /* This code uses callbacks to handle asynchronous function responses. @@ -92,8 +71,7 @@ var body_html = ` var tag0 = "key0=value0"; var tag1 = "key1=value1"; -async function main(){ - +async function main() { // Create the SMTP transport. let transporter = nodemailer.createTransport({ host: smtpEndpoint, @@ -101,8 +79,8 @@ async function main(){ secure: false, // true for 465, false for other ports auth: { user: smtpUsername, - pass: smtpPassword - } + pass: smtpPassword, + }, }); // Specify the fields in the email. @@ -116,14 +94,14 @@ async function main(){ html: body_html, // Custom headers for configuration set and message tags. headers: { - 'X-SES-CONFIGURATION-SET': configurationSet, - 'X-SES-MESSAGE-TAGS': tag0, - 'X-SES-MESSAGE-TAGS': tag1 - } + "X-SES-CONFIGURATION-SET": configurationSet, + "X-SES-MESSAGE-TAGS": tag0, + "X-SES-MESSAGE-TAGS": tag1, + }, }; // Send the email. - let info = await transporter.sendMail(mailOptions) + let info = await transporter.sendMail(mailOptions); console.log("Message sent! Message ID: ", info.messageId); } diff --git a/javascript/example_code/ses/ses_sendtemplatedemail.js b/javascript/example_code/ses/ses_sendtemplatedemail.js index bd69f33444a..ddc91bb93ec 100755 --- a/javascript/example_code/ses/ses_sendtemplatedemail.js +++ b/javascript/example_code/ses/ses_sendtemplatedemail.js @@ -1,67 +1,45 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[ses_sendtemplatedemail.js demonstrates how to compose an Amazon SES templated email and queue it for sending.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Email Service] -//snippet-service:[ses] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide//ses-examples-sending-email.html // snippet-start:[ses.JavaScript.email.sendTemplatedEmail] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); -// Create sendTemplatedEmail params +// Create sendTemplatedEmail params var params = { - Destination: { /* required */ + Destination: { + /* required */ CcAddresses: [ - 'EMAIL_ADDRESS', + "EMAIL_ADDRESS", /* more CC email addresses */ ], ToAddresses: [ - 'EMAIL_ADDRESS', + "EMAIL_ADDRESS", /* more To email addresses */ - ] + ], }, - Source: 'EMAIL_ADDRESS', /* required */ - Template: 'TEMPLATE_NAME', /* required */ - TemplateData: '{ \"REPLACEMENT_TAG_NAME\":\"REPLACEMENT_VALUE\" }', /* required */ - ReplyToAddresses: [ - 'EMAIL_ADDRESS' - ], + Source: "EMAIL_ADDRESS" /* required */, + Template: "TEMPLATE_NAME" /* required */, + TemplateData: '{ "REPLACEMENT_TAG_NAME":"REPLACEMENT_VALUE" }' /* required */, + ReplyToAddresses: ["EMAIL_ADDRESS"], }; - // Create the promise and SES service object -var sendPromise = new AWS.SES({apiVersion: '2010-12-01'}).sendTemplatedEmail(params).promise(); +var sendPromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .sendTemplatedEmail(params) + .promise(); // Handle promise's fulfilled/rejected states -sendPromise.then( - function(data) { +sendPromise + .then(function (data) { console.log(data); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[ses.JavaScript.email.sendTemplatedEmail] diff --git a/javascript/example_code/ses/ses_updatetemplate.js b/javascript/example_code/ses/ses_updatetemplate.js index e47f99f77b6..b97d8567231 100755 --- a/javascript/example_code/ses/ses_updatetemplate.js +++ b/javascript/example_code/ses/ses_updatetemplate.js @@ -1,56 +1,36 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[ses_updatetemplate.js demonstrates how to update an Amazon SES email template.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Email Service] -//snippet-service:[ses] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-creating-template.html // snippet-start:[ses.JavaScript.templates.updateTemplate] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); -// Create updateTemplate parameters +// Create updateTemplate parameters var params = { - Template: { - TemplateName: 'TEMPLATE_NAME', /* required */ - HtmlPart: 'HTML_CONTENT', - SubjectPart: 'SUBJECT_LINE', - TextPart: 'TEXT_CONTENT' - } + Template: { + TemplateName: "TEMPLATE_NAME" /* required */, + HtmlPart: "HTML_CONTENT", + SubjectPart: "SUBJECT_LINE", + TextPart: "TEXT_CONTENT", + }, }; // Create the promise and SES service object -var templatePromise = new AWS.SES({apiVersion: '2010-12-01'}).updateTemplate(params).promise(); +var templatePromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .updateTemplate(params) + .promise(); // Handle promise's fulfilled/rejected states -templatePromise.then( - function(data) { +templatePromise + .then(function (data) { console.log("Template Updated"); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[ses.JavaScript.templates.updateTemplate] diff --git a/javascript/example_code/ses/ses_verifydomainidentity.js b/javascript/example_code/ses/ses_verifydomainidentity.js index e7e67d9f7da..ecba3adf0bd 100755 --- a/javascript/example_code/ses/ses_verifydomainidentity.js +++ b/javascript/example_code/ses/ses_verifydomainidentity.js @@ -1,46 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[ses_verifydomainidentity.js demonstrates how to add a domain to the list of Amazon SES identities and attempts to verify it.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Email Service] -//snippet-service:[ses] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-managing-identities.html // snippet-start:[ses.JavaScript.identities.verifyDomainIdentity] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set region +AWS.config.update({ region: "REGION" }); // Create the promise and SES service object -var verifyDomainPromise = new AWS.SES({apiVersion: '2010-12-01'}).verifyDomainIdentity({Domain: "DOMAIN_NAME"}).promise(); +var verifyDomainPromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .verifyDomainIdentity({ Domain: "DOMAIN_NAME" }) + .promise(); // Handle promise's fulfilled/rejected states -verifyDomainPromise.then( - function(data) { +verifyDomainPromise + .then(function (data) { console.log("Verification Token: " + data.VerificationToken); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[ses.JavaScript.identities.verifyDomainIdentity] diff --git a/javascript/example_code/ses/ses_verifyemailidentity.js b/javascript/example_code/ses/ses_verifyemailidentity.js index 16b15f57e8e..71b8e5c1f63 100755 --- a/javascript/example_code/ses/ses_verifyemailidentity.js +++ b/javascript/example_code/ses/ses_verifyemailidentity.js @@ -1,46 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - */ - -//snippet-sourcedescription:[ses_verifyemailidentity.js demonstrates how to send an Amazon SES verification email.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Email Service] -//snippet-service:[ses] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/ses-examples-managing-identities.html // snippet-start:[ses.JavaScript.identities.verifyEmailIdentity] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set region +AWS.config.update({ region: "REGION" }); // Create promise and SES service object -var verifyEmailPromise = new AWS.SES({apiVersion: '2010-12-01'}).verifyEmailIdentity({EmailAddress: "ADDRESS@DOMAIN.EXT"}).promise(); +var verifyEmailPromise = new AWS.SES({ apiVersion: "2010-12-01" }) + .verifyEmailIdentity({ EmailAddress: "ADDRESS@DOMAIN.EXT" }) + .promise(); // Handle promise's fulfilled/rejected states -verifyEmailPromise.then( - function(data) { +verifyEmailPromise + .then(function (data) { console.log("Email verification initiated"); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[ses.JavaScript.identities.verifyEmailIdentity] diff --git a/javascript/example_code/sns/sns_checkphoneoptout.js b/javascript/example_code/sns/sns_checkphoneoptout.js index 791e486525c..4a6b82b7bc1 100755 --- a/javascript/example_code/sns/sns_checkphoneoptout.js +++ b/javascript/example_code/sns/sns_checkphoneoptout.js @@ -1,45 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sns_checkphoneoptout.js demonstrates how to determine whether a phone number has opted out of receiving Amazon SMS messages.] -//snippet-service:[sns] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Notification Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide//sns-examples-sending-sms.html // snippet-start:[sns.JavaScript.SMS.checkIfPhoneNumberIsOptedOut] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create promise and SNS service object -var phonenumPromise = new AWS.SNS({apiVersion: '2010-03-31'}).checkIfPhoneNumberIsOptedOut({phoneNumber: 'PHONE_NUMBER'}).promise(); +var phonenumPromise = new AWS.SNS({ apiVersion: "2010-03-31" }) + .checkIfPhoneNumberIsOptedOut({ phoneNumber: "PHONE_NUMBER" }) + .promise(); // Handle promise's fulfilled/rejected states -phonenumPromise.then( - function(data) { +phonenumPromise + .then(function (data) { console.log("Phone Opt Out is " + data.isOptedOut); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[sns.JavaScript.SMS.checkIfPhoneNumberIsOptedOut] diff --git a/javascript/example_code/sns/sns_createtopic.js b/javascript/example_code/sns/sns_createtopic.js index a49d47c5406..a07ccc6d9b1 100755 --- a/javascript/example_code/sns/sns_createtopic.js +++ b/javascript/example_code/sns/sns_createtopic.js @@ -1,45 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sns_createtopic.js demonstrates how to create an Amazon SNS topic to which notifications can be published.] -//snippet-service:[sns] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Notification Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-managing-topics.html // snippet-start:[sns.JavaScript.topics.createTopic] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create promise and SNS service object -var createTopicPromise = new AWS.SNS({apiVersion: '2010-03-31'}).createTopic({Name: "TOPIC_NAME"}).promise(); +var createTopicPromise = new AWS.SNS({ apiVersion: "2010-03-31" }) + .createTopic({ Name: "TOPIC_NAME" }) + .promise(); // Handle promise's fulfilled/rejected states -createTopicPromise.then( - function(data) { +createTopicPromise + .then(function (data) { console.log("Topic ARN is " + data.TopicArn); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[sns.JavaScript.topics.createTopic] diff --git a/javascript/example_code/sns/sns_deletetopic.js b/javascript/example_code/sns/sns_deletetopic.js index f511a3fc617..8074a34be67 100755 --- a/javascript/example_code/sns/sns_deletetopic.js +++ b/javascript/example_code/sns/sns_deletetopic.js @@ -1,45 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sns_deletetopic.js demonstrates how to delete an Amazon SNS topic and all its subscriptions.] -//snippet-service:[sns] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Notification Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-managing-topics.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-managing-topics.html // snippet-start:[sns.JavaScript.topics.deleteTopic] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create promise and SNS service object -var deleteTopicPromise = new AWS.SNS({apiVersion: '2010-03-31'}).deleteTopic({TopicArn: 'TOPIC_ARN'}).promise(); +var deleteTopicPromise = new AWS.SNS({ apiVersion: "2010-03-31" }) + .deleteTopic({ TopicArn: "TOPIC_ARN" }) + .promise(); // Handle promise's fulfilled/rejected states -deleteTopicPromise.then( - function(data) { +deleteTopicPromise + .then(function (data) { console.log("Topic Deleted"); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[sns.JavaScript.topics.deleteTopic] diff --git a/javascript/example_code/sns/sns_getsmstype.js b/javascript/example_code/sns/sns_getsmstype.js index 2ff32757487..a26c6199518 100755 --- a/javascript/example_code/sns/sns_getsmstype.js +++ b/javascript/example_code/sns/sns_getsmstype.js @@ -1,54 +1,35 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sns_getsmstype.js demonstrates how to retrieve the settings for sending Amazon SMS messages.] -//snippet-service:[sns] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Notification Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide//sns-examples-sending-sms.html // snippet-start:[sns.JavaScript.SMS.getSMSAttributes] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create SMS Attribute parameter you want to get var params = { attributes: [ - 'DefaultSMSType', - 'ATTRIBUTE_NAME' + "DefaultSMSType", + "ATTRIBUTE_NAME", /* more items */ - ] + ], }; // Create promise and SNS service object -var getSMSTypePromise = new AWS.SNS({apiVersion: '2010-03-31'}).getSMSAttributes(params).promise(); +var getSMSTypePromise = new AWS.SNS({ apiVersion: "2010-03-31" }) + .getSMSAttributes(params) + .promise(); // Handle promise's fulfilled/rejected states -getSMSTypePromise.then( - function(data) { +getSMSTypePromise + .then(function (data) { console.log(data); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[sns.JavaScript.SMS.getSMSAttributes] diff --git a/javascript/example_code/sns/sns_gettopicattributes.js b/javascript/example_code/sns/sns_gettopicattributes.js index 8d299014799..af0e7b373dd 100755 --- a/javascript/example_code/sns/sns_gettopicattributes.js +++ b/javascript/example_code/sns/sns_gettopicattributes.js @@ -1,46 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sns_gettopicattributes.js demonstrates how to retrieve the properties of an Amazon SNS topic.] -//snippet-service:[sns] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Notification Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-managing-topics.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-managing-topics.html // snippet-start:[sns.JavaScript.topics.getTopicAttributes] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set region -AWS.config.update({region: 'REGION'}); - +AWS.config.update({ region: "REGION" }); // Create promise and SNS service object -var getTopicAttribsPromise = new AWS.SNS({apiVersion: '2010-03-31'}).getTopicAttributes({TopicArn: 'TOPIC_ARN'}).promise(); +var getTopicAttribsPromise = new AWS.SNS({ apiVersion: "2010-03-31" }) + .getTopicAttributes({ TopicArn: "TOPIC_ARN" }) + .promise(); // Handle promise's fulfilled/rejected states -getTopicAttribsPromise.then( - function(data) { +getTopicAttribsPromise + .then(function (data) { console.log(data); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[sns.JavaScript.topics.getTopicAttributes] diff --git a/javascript/example_code/sns/sns_listnumbersoptedout.js b/javascript/example_code/sns/sns_listnumbersoptedout.js index a1164f27dab..ad5c1159e33 100755 --- a/javascript/example_code/sns/sns_listnumbersoptedout.js +++ b/javascript/example_code/sns/sns_listnumbersoptedout.js @@ -1,46 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sns_listnumbersoptedout.js demonstrates how to retrieve a list of phone numbers that have opted out of receiving Amazon SMS messages.] -//snippet-service:[sns] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Notification Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide//sns-examples-sending-sms.html // snippet-start:[sns.JavaScript.SMS.listPhoneNumbersOptedOut] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create promise and SNS service object -var phonelistPromise = new AWS.SNS({apiVersion: '2010-03-31'}).listPhoneNumbersOptedOut({}).promise(); +var phonelistPromise = new AWS.SNS({ apiVersion: "2010-03-31" }) + .listPhoneNumbersOptedOut({}) + .promise(); // Handle promise's fulfilled/rejected states - phonelistPromise.then( - function(data) { - console.log(data); - }).catch( - function(err) { - console.error(err, err.stack); - } - ); +phonelistPromise + .then(function (data) { + console.log(data); + }) + .catch(function (err) { + console.error(err, err.stack); + }); // snippet-end:[sns.JavaScript.SMS.listPhoneNumbersOptedOut] diff --git a/javascript/example_code/sns/sns_listsubscriptions.js b/javascript/example_code/sns/sns_listsubscriptions.js index 0cd025eb1b0..a4f05128ae6 100755 --- a/javascript/example_code/sns/sns_listsubscriptions.js +++ b/javascript/example_code/sns/sns_listsubscriptions.js @@ -1,50 +1,30 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sns_listsubscriptions.js demonstrates how to retrieve a list of Amazon SNS subscriptions.] -//snippet-service:[sns] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Notification Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-subscribing-unubscribing-topics.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-subscribing-unubscribing-topics.html // snippet-start:[sns.JavaScript.subscriptions.listSubscriptionsByTopic] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); const params = { - TopicArn : 'TOPIC_ARN' -} + TopicArn: "TOPIC_ARN", +}; // Create promise and SNS service object -var subslistPromise = new AWS.SNS({apiVersion: '2010-03-31'}).listSubscriptionsByTopic(params).promise(); +var subslistPromise = new AWS.SNS({ apiVersion: "2010-03-31" }) + .listSubscriptionsByTopic(params) + .promise(); // Handle promise's fulfilled/rejected states - subslistPromise.then( - function(data) { - console.log(data); - }).catch( - function(err) { - console.error(err, err.stack); - } - ); +subslistPromise + .then(function (data) { + console.log(data); + }) + .catch(function (err) { + console.error(err, err.stack); + }); // snippet-end:[sns.JavaScript.subscriptions.listSubscriptionsByTopic] diff --git a/javascript/example_code/sns/sns_listtopics.js b/javascript/example_code/sns/sns_listtopics.js index 89163ea73d2..c667a2fe08a 100755 --- a/javascript/example_code/sns/sns_listtopics.js +++ b/javascript/example_code/sns/sns_listtopics.js @@ -1,45 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sns_listtopics.js demonstrates how to retrieve a list of Amazon SNS topics.] -//snippet-service:[sns] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Notification Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-managing-topics.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-managing-topics.html // snippet-start:[sns.JavaScript.topics.listTopics] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create promise and SNS service object -var listTopicsPromise = new AWS.SNS({apiVersion: '2010-03-31'}).listTopics({}).promise(); +var listTopicsPromise = new AWS.SNS({ apiVersion: "2010-03-31" }) + .listTopics({}) + .promise(); // Handle promise's fulfilled/rejected states -listTopicsPromise.then( - function(data) { +listTopicsPromise + .then(function (data) { console.log(data.Topics); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[sns.JavaScript.topics.listTopics] diff --git a/javascript/example_code/sns/sns_publishsms.js b/javascript/example_code/sns/sns_publishsms.js index 6dfba34662a..aa447eb167f 100755 --- a/javascript/example_code/sns/sns_publishsms.js +++ b/javascript/example_code/sns/sns_publishsms.js @@ -1,51 +1,32 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sns_publishsms.js demonstrates how to use Amazon SNS to send an SMS text message to a phone number.] -//snippet-service:[sns] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Notification Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide//sns-examples-sending-sms.html // snippet-start:[sns.JavaScript.SMS.publish] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create publish parameters var params = { - Message: 'TEXT_MESSAGE', /* required */ - PhoneNumber: 'E.164_PHONE_NUMBER', + Message: "TEXT_MESSAGE" /* required */, + PhoneNumber: "E.164_PHONE_NUMBER", }; // Create promise and SNS service object -var publishTextPromise = new AWS.SNS({apiVersion: '2010-03-31'}).publish(params).promise(); +var publishTextPromise = new AWS.SNS({ apiVersion: "2010-03-31" }) + .publish(params) + .promise(); // Handle promise's fulfilled/rejected states -publishTextPromise.then( - function(data) { +publishTextPromise + .then(function (data) { console.log("MessageID is " + data.MessageId); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[sns.JavaScript.SMS.publish] diff --git a/javascript/example_code/sns/sns_publishtotopic.js b/javascript/example_code/sns/sns_publishtotopic.js index b62e34e4745..087122264bc 100755 --- a/javascript/example_code/sns/sns_publishtotopic.js +++ b/javascript/example_code/sns/sns_publishtotopic.js @@ -1,52 +1,35 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sns_publishtotopic.js demonstrates how to send a message to an Amazon SNS topic.] -//snippet-service:[sns] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Notification Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-publishing-messages.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-publishing-messages.html // snippet-start:[sns.JavaScript.topics.publishMessages] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create publish parameters var params = { - Message: 'MESSAGE_TEXT', /* required */ - TopicArn: 'TOPIC_ARN' + Message: "MESSAGE_TEXT" /* required */, + TopicArn: "TOPIC_ARN", }; // Create promise and SNS service object -var publishTextPromise = new AWS.SNS({apiVersion: '2010-03-31'}).publish(params).promise(); +var publishTextPromise = new AWS.SNS({ apiVersion: "2010-03-31" }) + .publish(params) + .promise(); // Handle promise's fulfilled/rejected states -publishTextPromise.then( - function(data) { - console.log(`Message ${params.Message} sent to the topic ${params.TopicArn}`); +publishTextPromise + .then(function (data) { + console.log( + `Message ${params.Message} sent to the topic ${params.TopicArn}` + ); console.log("MessageID is " + data.MessageId); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[sns.JavaScript.topics.publishMessages] diff --git a/javascript/example_code/sns/sns_setsmstype.js b/javascript/example_code/sns/sns_setsmstype.js index 40ab17a1a97..9e8c1cf5f15 100755 --- a/javascript/example_code/sns/sns_setsmstype.js +++ b/javascript/example_code/sns/sns_setsmstype.js @@ -1,53 +1,35 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sns_setsmstype.js demonstrates how to use Amazon SNS to set default SMS attributes.] -//snippet-service:[sns] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Notification Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide//sns-examples-sending-sms.html // snippet-start:[sns.JavaScript.SMS.setSMSAttributes] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create SMS Attribute parameters var params = { - attributes: { /* required */ - 'DefaultSMSType': 'Transactional', /* highest reliability */ + attributes: { + /* required */ + DefaultSMSType: "Transactional" /* highest reliability */, //'DefaultSMSType': 'Promotional' /* lowest cost */ - } + }, }; // Create promise and SNS service object -var setSMSTypePromise = new AWS.SNS({apiVersion: '2010-03-31'}).setSMSAttributes(params).promise(); +var setSMSTypePromise = new AWS.SNS({ apiVersion: "2010-03-31" }) + .setSMSAttributes(params) + .promise(); // Handle promise's fulfilled/rejected states -setSMSTypePromise.then( - function(data) { +setSMSTypePromise + .then(function (data) { console.log(data); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[sns.JavaScript.SMS.setSMSAttributes] diff --git a/javascript/example_code/sns/sns_settopicattributes.js b/javascript/example_code/sns/sns_settopicattributes.js index f5020c8768d..62e412ddb75 100755 --- a/javascript/example_code/sns/sns_settopicattributes.js +++ b/javascript/example_code/sns/sns_settopicattributes.js @@ -1,52 +1,33 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sns_settopicattributes.js demonstrates how to set the attributes of an Amazon SNS topic.] -//snippet-service:[sns] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Notification Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-managing-topics.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-managing-topics.html // snippet-start:[sns.JavaScript.topics.setTopicAttributes] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create setTopicAttributes parameters var params = { - AttributeName: 'ATTRIBUTE_NAME', /* required */ - TopicArn: 'TOPIC_ARN', /* required */ - AttributeValue: 'NEW_ATTRIBUTE_VALUE' + AttributeName: "ATTRIBUTE_NAME" /* required */, + TopicArn: "TOPIC_ARN" /* required */, + AttributeValue: "NEW_ATTRIBUTE_VALUE", }; // Create promise and SNS service object -var setTopicAttribsPromise = new AWS.SNS({apiVersion: '2010-03-31'}).setTopicAttributes(params).promise(); +var setTopicAttribsPromise = new AWS.SNS({ apiVersion: "2010-03-31" }) + .setTopicAttributes(params) + .promise(); // Handle promise's fulfilled/rejected states -setTopicAttribsPromise.then( - function(data) { +setTopicAttribsPromise + .then(function (data) { console.log(data); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[sns.JavaScript.topics.setTopicAttributes] diff --git a/javascript/example_code/sns/sns_subscribeapp.js b/javascript/example_code/sns/sns_subscribeapp.js index f2a0b3fac9f..7f9e180c519 100755 --- a/javascript/example_code/sns/sns_subscribeapp.js +++ b/javascript/example_code/sns/sns_subscribeapp.js @@ -1,52 +1,33 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sns_subscribeapp.js demonstrates how to initiate a subscription to an Amazon SNS topic with delivery to a mobile app.] -//snippet-service:[sns] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Notification Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-subscribing-unubscribing-topics.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-subscribing-unubscribing-topics.html // snippet-start:[sns.JavaScript.subscriptions.subscribeApp] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create subscribe/email parameters var params = { - Protocol: 'application', /* required */ - TopicArn: 'TOPIC_ARN', /* required */ - Endpoint: 'MOBILE_ENDPOINT_ARN' + Protocol: "application" /* required */, + TopicArn: "TOPIC_ARN" /* required */, + Endpoint: "MOBILE_ENDPOINT_ARN", }; // Create promise and SNS service object -var subscribePromise = new AWS.SNS({apiVersion: '2010-03-31'}).subscribe(params).promise(); +var subscribePromise = new AWS.SNS({ apiVersion: "2010-03-31" }) + .subscribe(params) + .promise(); // Handle promise's fulfilled/rejected states -subscribePromise.then( - function(data) { +subscribePromise + .then(function (data) { console.log("Subscription ARN is " + data.SubscriptionArn); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[sns.JavaScript.subscriptions.subscribeApp] diff --git a/javascript/example_code/sns/sns_subscribeemail.js b/javascript/example_code/sns/sns_subscribeemail.js index 95cff978b23..32e9b03a005 100755 --- a/javascript/example_code/sns/sns_subscribeemail.js +++ b/javascript/example_code/sns/sns_subscribeemail.js @@ -1,52 +1,33 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sns_subscribeemail.js demonstrates how to initiate a subscription to an Amazon SNS topic with delivery to an email address.] -//snippet-service:[sns] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Notification Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-subscribing-unubscribing-topics.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-subscribing-unubscribing-topics.html // snippet-start:[sns.JavaScript.subscriptions.subscribeEmail] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create subscribe/email parameters var params = { - Protocol: 'EMAIL', /* required */ - TopicArn: 'TOPIC_ARN', /* required */ - Endpoint: 'EMAIL_ADDRESS' + Protocol: "EMAIL" /* required */, + TopicArn: "TOPIC_ARN" /* required */, + Endpoint: "EMAIL_ADDRESS", }; // Create promise and SNS service object -var subscribePromise = new AWS.SNS({apiVersion: '2010-03-31'}).subscribe(params).promise(); +var subscribePromise = new AWS.SNS({ apiVersion: "2010-03-31" }) + .subscribe(params) + .promise(); // Handle promise's fulfilled/rejected states -subscribePromise.then( - function(data) { +subscribePromise + .then(function (data) { console.log("Subscription ARN is " + data.SubscriptionArn); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[sns.JavaScript.subscriptions.subscribeEmail] diff --git a/javascript/example_code/sns/sns_subscribelambda.js b/javascript/example_code/sns/sns_subscribelambda.js index 65a1b3f6ff1..249c6b45263 100755 --- a/javascript/example_code/sns/sns_subscribelambda.js +++ b/javascript/example_code/sns/sns_subscribelambda.js @@ -1,52 +1,33 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sns_subscribelambda.js demonstrates how to initiate a subscription to an Amazon SNS topic with delivery to an AWS Lambda function.] -//snippet-service:[sns] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Notification Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-subscribing-unubscribing-topics.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-subscribing-unubscribing-topics.html // snippet-start:[sns.JavaScript.subscriptions.subscribeLambda] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create subscribe/email parameters var params = { - Protocol: 'lambda', /* required */ - TopicArn: 'TOPIC_ARN', /* required */ - Endpoint: 'LAMBDA_FUNCTION_ARN' + Protocol: "lambda" /* required */, + TopicArn: "TOPIC_ARN" /* required */, + Endpoint: "LAMBDA_FUNCTION_ARN", }; // Create promise and SNS service object -var subscribePromise = new AWS.SNS({apiVersion: '2010-03-31'}).subscribe(params).promise(); +var subscribePromise = new AWS.SNS({ apiVersion: "2010-03-31" }) + .subscribe(params) + .promise(); // Handle promise's fulfilled/rejected states -subscribePromise.then( - function(data) { +subscribePromise + .then(function (data) { console.log("Subscription ARN is " + data.SubscriptionArn); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[sns.JavaScript.subscriptions.subscribeLambda] diff --git a/javascript/example_code/sns/sns_unsubscribe.js b/javascript/example_code/sns/sns_unsubscribe.js index 8fca16566ad..dbe2773ae90 100755 --- a/javascript/example_code/sns/sns_unsubscribe.js +++ b/javascript/example_code/sns/sns_unsubscribe.js @@ -1,45 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sns_unsubscribe.js demonstrates how to delete a subscription to an Amazon SNS topic.] -//snippet-service:[sns] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Notification Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at -// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-subscribing-unubscribing-topics.html +// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-subscribing-unubscribing-topics.html // snippet-start:[sns.JavaScript.subscriptions.unsubscribe] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create promise and SNS service object -var subscribePromise = new AWS.SNS({apiVersion: '2010-03-31'}).unsubscribe({SubscriptionArn : TOPIC_SUBSCRIPTION_ARN}).promise(); +var subscribePromise = new AWS.SNS({ apiVersion: "2010-03-31" }) + .unsubscribe({ SubscriptionArn: TOPIC_SUBSCRIPTION_ARN }) + .promise(); // Handle promise's fulfilled/rejected states -subscribePromise.then( - function(data) { +subscribePromise + .then(function (data) { console.log(data); - }).catch( - function(err) { + }) + .catch(function (err) { console.error(err, err.stack); }); // snippet-end:[sns.JavaScript.subscriptions.unsubscribe] diff --git a/javascript/example_code/sqs/sqs_changingvisibility.js b/javascript/example_code/sqs/sqs_changingvisibility.js index 249e0bd833d..4bf0b9b4f6d 100755 --- a/javascript/example_code/sqs/sqs_changingvisibility.js +++ b/javascript/example_code/sqs/sqs_changingvisibility.js @@ -1,69 +1,48 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ - -// snippet-sourcedescription:[sqs_changingvisibility.js demonstrates how to change the visibility timeout of a message in an Amazon SQS queue.] -// snippet-service:[sqs] -// snippet-keyword:[JavaScript] -// snippet-sourcesyntax:[javascript] -// snippet-keyword:[Code Sample] -// snippet-keyword:[Amazon Simple Queue Service] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[2019-10-10] -// snippet-sourceauthor:[Doug-AWS] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-managing-visibility-timeout.html // snippet-start:[sqs.JavaScript.visibility.receiveMessage] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk') +var AWS = require("aws-sdk"); // Set the region to us-west-2 -AWS.config.update({ region: 'us-west-2' }) +AWS.config.update({ region: "us-west-2" }); // Create the SQS service object -var sqs = new AWS.SQS({ apiVersion: '2012-11-05' }) +var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); -var queueURL = 'https://sqs.REGION.amazonaws.com/ACCOUNT-ID/QUEUE-NAME' +var queueURL = "https://sqs.REGION.amazonaws.com/ACCOUNT-ID/QUEUE-NAME"; var params = { - AttributeNames: ['SentTimestamp'], + AttributeNames: ["SentTimestamp"], MaxNumberOfMessages: 1, - MessageAttributeNames: ['All'], - QueueUrl: queueURL -} + MessageAttributeNames: ["All"], + QueueUrl: queueURL, +}; sqs.receiveMessage(params, function (err, data) { if (err) { - console.log('Receive Error', err) + console.log("Receive Error", err); } else { // Make sure we have a message if (data.Messages != null) { var visibilityParams = { QueueUrl: queueURL, ReceiptHandle: data.Messages[0].ReceiptHandle, - VisibilityTimeout: 20 // 20 second timeout - } + VisibilityTimeout: 20, // 20 second timeout + }; sqs.changeMessageVisibility(visibilityParams, function (err, data) { if (err) { - console.log('Delete Error', err) + console.log("Delete Error", err); } else { - console.log('Timeout Changed', data) + console.log("Timeout Changed", data); } - }) + }); } else { - console.log('No messages to change') + console.log("No messages to change"); } } -}) +}); // snippet-end:[sqs.JavaScript.visibility.receiveMessage] diff --git a/javascript/example_code/sqs/sqs_createqueue.js b/javascript/example_code/sqs/sqs_createqueue.js index 1119d21c9d8..3080b1a5f8a 100755 --- a/javascript/example_code/sqs/sqs_createqueue.js +++ b/javascript/example_code/sqs/sqs_createqueue.js @@ -1,48 +1,27 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sqs_createqueue.js demonstrates how to create an Amazon SQS standard queue.] -//snippet-service:[sqs] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Queue Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-using-queues.html // snippet-start:[sqs.JavaScript.queues.createQueue] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create an SQS service object -var sqs = new AWS.SQS({apiVersion: '2012-11-05'}); +var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var params = { - QueueName: 'SQS_QUEUE_NAME', + QueueName: "SQS_QUEUE_NAME", Attributes: { - 'DelaySeconds': '60', - 'MessageRetentionPeriod': '86400' - } + DelaySeconds: "60", + MessageRetentionPeriod: "86400", + }, }; -sqs.createQueue(params, function(err, data) { +sqs.createQueue(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/sqs/sqs_deadletterqueue.js b/javascript/example_code/sqs/sqs_deadletterqueue.js index a75a80aa786..a6600bb1c6e 100755 --- a/javascript/example_code/sqs/sqs_deadletterqueue.js +++ b/javascript/example_code/sqs/sqs_deadletterqueue.js @@ -1,47 +1,27 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sqs_deadletterqueue.js demonstrates how to enable the dead-letter functionality of an Amazon SQS queue.] -//snippet-service:[sqs] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Queue Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-dead-letter-queues.html // snippet-start:[sqs.JavaScript.deadLetter.setQueueAttributes] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the SQS service object -var sqs = new AWS.SQS({apiVersion: '2012-11-05'}); +var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var params = { - Attributes: { - "RedrivePolicy": "{\"deadLetterTargetArn\":\"DEAD_LETTER_QUEUE_ARN\",\"maxReceiveCount\":\"10\"}", - }, - QueueUrl: "SOURCE_QUEUE_URL" + Attributes: { + RedrivePolicy: + '{"deadLetterTargetArn":"DEAD_LETTER_QUEUE_ARN","maxReceiveCount":"10"}', + }, + QueueUrl: "SOURCE_QUEUE_URL", }; -sqs.setQueueAttributes(params, function(err, data) { +sqs.setQueueAttributes(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/sqs/sqs_deletequeue.js b/javascript/example_code/sqs/sqs_deletequeue.js index a52509033d2..fe295724f37 100755 --- a/javascript/example_code/sqs/sqs_deletequeue.js +++ b/javascript/example_code/sqs/sqs_deletequeue.js @@ -1,45 +1,23 @@ - -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sqs_deletequeue.js demonstrates how to delete an Amazon SQS queue.] -//snippet-service:[sqs] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Queue Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-using-queues.html // snippet-start:[sqs.JavaScript.queues.deleteQueue] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set the region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create an SQS service object -var sqs = new AWS.SQS({apiVersion: '2012-11-05'}); +var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var params = { - QueueUrl: 'SQS_QUEUE_URL' - }; + QueueUrl: "SQS_QUEUE_URL", +}; -sqs.deleteQueue(params, function(err, data) { +sqs.deleteQueue(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/sqs/sqs_getqueueurl.js b/javascript/example_code/sqs/sqs_getqueueurl.js index 7e1277df4ad..d713668f921 100755 --- a/javascript/example_code/sqs/sqs_getqueueurl.js +++ b/javascript/example_code/sqs/sqs_getqueueurl.js @@ -1,44 +1,23 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sqs_getqueueurl.js demonstrates how to retrieve the URL of an Amazon SQS queue.] -//snippet-service:[sqs] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Queue Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-using-queues.html // snippet-start:[sqs.JavaScript.queues.getQueueUrl] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create an SQS service object -var sqs = new AWS.SQS({apiVersion: '2012-11-05'}); +var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var params = { - QueueName: 'SQS_QUEUE_NAME' + QueueName: "SQS_QUEUE_NAME", }; -sqs.getQueueUrl(params, function(err, data) { +sqs.getQueueUrl(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/sqs/sqs_listqueues.js b/javascript/example_code/sqs/sqs_listqueues.js index 7e3dcf6233b..bce56c6a2f7 100755 --- a/javascript/example_code/sqs/sqs_listqueues.js +++ b/javascript/example_code/sqs/sqs_listqueues.js @@ -1,42 +1,21 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sqs_listqueues.js demonstrates how to retrieve a list of Amazon SQS queues for an AWS account.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Queue Service] -//snippet-service:[sqs] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-using-queues.html // snippet-start:[sqs.JavaScript.queues.listQueues] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create an SQS service object -var sqs = new AWS.SQS({apiVersion: '2012-11-05'}); +var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var params = {}; -sqs.listQueues(params, function(err, data) { +sqs.listQueues(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/sqs/sqs_longpolling_createqueue.js b/javascript/example_code/sqs/sqs_longpolling_createqueue.js index a78ef3c3013..6fc1ef5e781 100755 --- a/javascript/example_code/sqs/sqs_longpolling_createqueue.js +++ b/javascript/example_code/sqs/sqs_longpolling_createqueue.js @@ -1,47 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sqs_longpolling_createqueue.js demonstrates how to create an Amazon SQS queue that waits for a message to arrive.] -//snippet-service:[sqs] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Queue Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-enable-long-polling.html // snippet-start:[sqs.JavaScript.longPoll.createQueue] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the SQS service object -var sqs = new AWS.SQS({apiVersion: '2012-11-05'}); +var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var params = { - QueueName: 'SQS_QUEUE_NAME', + QueueName: "SQS_QUEUE_NAME", Attributes: { - 'ReceiveMessageWaitTimeSeconds': '20', - } + ReceiveMessageWaitTimeSeconds: "20", + }, }; -sqs.createQueue(params, function(err, data) { +sqs.createQueue(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/sqs/sqs_longpolling_existingqueue.js b/javascript/example_code/sqs/sqs_longpolling_existingqueue.js index 9965574dc36..048cab082d8 100755 --- a/javascript/example_code/sqs/sqs_longpolling_existingqueue.js +++ b/javascript/example_code/sqs/sqs_longpolling_existingqueue.js @@ -1,47 +1,26 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sqs_longpolling_existingqueue.js demonstrates how to change the amount of time an Amazon SQS queue waits for a message to arrive.] -//snippet-service:[sqs] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Queue Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-enable-long-polling.html // snippet-start:[sqs.JavaScript.longPoll.setQueueAttributes] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the SQS service object -var sqs = new AWS.SQS({apiVersion: '2012-11-05'}); +var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var params = { - Attributes: { - "ReceiveMessageWaitTimeSeconds": "20", - }, - QueueUrl: "SQS_QUEUE_URL" + Attributes: { + ReceiveMessageWaitTimeSeconds: "20", + }, + QueueUrl: "SQS_QUEUE_URL", }; -sqs.setQueueAttributes(params, function(err, data) { +sqs.setQueueAttributes(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/sqs/sqs_longpolling_receivemessage.js b/javascript/example_code/sqs/sqs_longpolling_receivemessage.js index cded48e5ed2..39e836a301f 100755 --- a/javascript/example_code/sqs/sqs_longpolling_receivemessage.js +++ b/javascript/example_code/sqs/sqs_longpolling_receivemessage.js @@ -1,54 +1,29 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sqs_longpolling_receivemessage.js demonstrates how to retrieve messages from an Amazon SQS queue using long-poll support.] -//snippet-service:[sqs] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Queue Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-enable-long-polling.html // snippet-start:[sqs.JavaScript.longPoll.receiveMessage] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create the SQS service object -var sqs = new AWS.SQS({apiVersion: '2012-11-05'}); +var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var queueURL = "SQS_QUEUE_URL"; var params = { - AttributeNames: [ - "SentTimestamp" - ], - MaxNumberOfMessages: 1, - MessageAttributeNames: [ - "All" - ], - QueueUrl: queueURL, - WaitTimeSeconds: 20 + AttributeNames: ["SentTimestamp"], + MaxNumberOfMessages: 1, + MessageAttributeNames: ["All"], + QueueUrl: queueURL, + WaitTimeSeconds: 20, }; -sqs.receiveMessage(params, function(err, data) { +sqs.receiveMessage(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/sqs/sqs_receivemessage.js b/javascript/example_code/sqs/sqs_receivemessage.js index db549bb3391..556b182ad14 100755 --- a/javascript/example_code/sqs/sqs_receivemessage.js +++ b/javascript/example_code/sqs/sqs_receivemessage.js @@ -1,63 +1,38 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sqs_receivemessage.js demonstrates how to receive and delete a message from an Amazon SQS queue.] -//snippet-service:[sqs] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Queue Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-send-receive-messages.html // snippet-start:[sqs.JavaScript.messages.receiveMessage] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); +var AWS = require("aws-sdk"); // Set the region -AWS.config.update({region: 'REGION'}); +AWS.config.update({ region: "REGION" }); // Create an SQS service object -var sqs = new AWS.SQS({apiVersion: '2012-11-05'}); +var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var queueURL = "SQS_QUEUE_URL"; var params = { - AttributeNames: [ - "SentTimestamp" - ], - MaxNumberOfMessages: 10, - MessageAttributeNames: [ - "All" - ], - QueueUrl: queueURL, - VisibilityTimeout: 20, - WaitTimeSeconds: 0 + AttributeNames: ["SentTimestamp"], + MaxNumberOfMessages: 10, + MessageAttributeNames: ["All"], + QueueUrl: queueURL, + VisibilityTimeout: 20, + WaitTimeSeconds: 0, }; -sqs.receiveMessage(params, function(err, data) { +sqs.receiveMessage(params, function (err, data) { if (err) { console.log("Receive Error", err); } else if (data.Messages) { var deleteParams = { QueueUrl: queueURL, - ReceiptHandle: data.Messages[0].ReceiptHandle + ReceiptHandle: data.Messages[0].ReceiptHandle, }; - sqs.deleteMessage(deleteParams, function(err, data) { + sqs.deleteMessage(deleteParams, function (err, data) { if (err) { console.log("Delete Error", err); } else { diff --git a/javascript/example_code/sqs/sqs_sendmessage.js b/javascript/example_code/sqs/sqs_sendmessage.js index c63cbd458e1..f69150301c6 100755 --- a/javascript/example_code/sqs/sqs_sendmessage.js +++ b/javascript/example_code/sqs/sqs_sendmessage.js @@ -1,63 +1,43 @@ -/** - * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * This file is 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/ - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - * CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. -*/ - -//snippet-sourcedescription:[sqs_sendmessage.js demonstrates how to deliver a message to an Amazon SQS queue.] -//snippet-service:[sqs] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon Simple Queue Service] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-06-02] -//snippet-sourceauthor:[AWS-JSDG] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-send-receive-messages.html // snippet-start:[sqs.JavaScript.messages.sendMessage] // Load the AWS SDK for Node.js -var AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); +var AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); // Create an SQS service object -var sqs = new AWS.SQS({apiVersion: '2012-11-05'}); +var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var params = { - // Remove DelaySeconds parameter and value for FIFO queues + // Remove DelaySeconds parameter and value for FIFO queues DelaySeconds: 10, MessageAttributes: { - "Title": { + Title: { DataType: "String", - StringValue: "The Whistler" + StringValue: "The Whistler", }, - "Author": { + Author: { DataType: "String", - StringValue: "John Grisham" + StringValue: "John Grisham", }, - "WeeksOn": { + WeeksOn: { DataType: "Number", - StringValue: "6" - } + StringValue: "6", + }, }, - MessageBody: "Information about current NY Times fiction bestseller for week of 12/11/2016.", + MessageBody: + "Information about current NY Times fiction bestseller for week of 12/11/2016.", // MessageDeduplicationId: "TheWhistler", // Required for FIFO queues // MessageGroupId: "Group1", // Required for FIFO queues - QueueUrl: "SQS_QUEUE_URL" + QueueUrl: "SQS_QUEUE_URL", }; -sqs.sendMessage(params, function(err, data) { +sqs.sendMessage(params, function (err, data) { if (err) { console.log("Error", err); } else { diff --git a/javascript/example_code/sts/sts_assumerole.js b/javascript/example_code/sts/sts_assumerole.js index f517aa9f1f1..5e3fba48bbb 100644 --- a/javascript/example_code/sts/sts_assumerole.js +++ b/javascript/example_code/sts/sts_assumerole.js @@ -1,60 +1,50 @@ - -//snippet-sourcedescription:[sts_assumerole.js demonstrates how to use STS to assume an IAM Role.] -//snippet-keyword:[JavaScript] -//snippet-sourcesyntax:[javascript] -//snippet-keyword:[Code Sample] -//snippet-keyword:[AWS Security Token Service (STS)] -//snippet-service:[sts] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2018-11-12] -//snippet-sourceauthor:[walkerk1980] - - -// Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// Licensed under the Apache-2.0 License on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND. +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sts-examples-policies.html // snippet-start:[sts.JavaScript.assumeRole] // Load the AWS SDK for Node.js -const AWS = require('aws-sdk'); -// Set the region -AWS.config.update({region: 'REGION'}); - -var roleToAssume = {RoleArn: 'arn:aws:iam::123456789012:role/RoleName', - RoleSessionName: 'session1', - DurationSeconds: 900,}; +const AWS = require("aws-sdk"); +// Set the region +AWS.config.update({ region: "REGION" }); + +var roleToAssume = { + RoleArn: "arn:aws:iam::123456789012:role/RoleName", + RoleSessionName: "session1", + DurationSeconds: 900, +}; var roleCreds; -// Create the STS service object -var sts = new AWS.STS({apiVersion: '2011-06-15'}); +// Create the STS service object +var sts = new AWS.STS({ apiVersion: "2011-06-15" }); //Assume Role -sts.assumeRole(roleToAssume, function(err, data) { - if (err) console.log(err, err.stack); - else{ - roleCreds = {accessKeyId: data.Credentials.AccessKeyId, - secretAccessKey: data.Credentials.SecretAccessKey, - sessionToken: data.Credentials.SessionToken}; - stsGetCallerIdentity(roleCreds); - } +sts.assumeRole(roleToAssume, function (err, data) { + if (err) console.log(err, err.stack); + else { + roleCreds = { + accessKeyId: data.Credentials.AccessKeyId, + secretAccessKey: data.Credentials.SecretAccessKey, + sessionToken: data.Credentials.SessionToken, + }; + stsGetCallerIdentity(roleCreds); + } }); //Get Arn of current identity function stsGetCallerIdentity(creds) { - var stsParams = {credentials: creds }; - // Create STS service object - var sts = new AWS.STS(stsParams); - - sts.getCallerIdentity({}, function(err, data) { - if (err) { - console.log(err, err.stack); - } - else { - console.log(data.Arn); - } - }); + var stsParams = { credentials: creds }; + // Create STS service object + var sts = new AWS.STS(stsParams); + + sts.getCallerIdentity({}, function (err, data) { + if (err) { + console.log(err, err.stack); + } else { + console.log(data.Arn); + } + }); } // snippet-end:[sts.JavaScript.assumeRole] - diff --git a/javascript/example_code/textract/detect_document_text.js b/javascript/example_code/textract/detect_document_text.js index 670e4553d43..60142b2cec8 100644 --- a/javascript/example_code/textract/detect_document_text.js +++ b/javascript/example_code/textract/detect_document_text.js @@ -1,21 +1,23 @@ -/*Example showing processing a document on local machine.*/ - -const aws = require('aws-sdk'); -/*Initializing Textract from AWS SDK JS*/ -const textract = new aws.Textract({ apiVersion: "2018-06-27" }); -/*File system package for importing images and converting the image data to ByteArray */ -const fs = require('fs'); - -exports.handler = async(event, context) => { - let textractParams = { - Document: { - Bytes: fs.readFileSync("simple-document-image.jpg") - }, - }; - try { - let response = await textract.detectDocumentText(textractParams).promise(); - console.log(JSON.stringify(response),null,2) - }catch(e){ - console.log("Error: ",e) - } +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/*Example showing processing a document on local machine.*/ + +const aws = require('aws-sdk'); +/*Initializing Textract from AWS SDK JS*/ +const textract = new aws.Textract({ apiVersion: "2018-06-27" }); +/*File system package for importing images and converting the image data to ByteArray */ +const fs = require('fs'); + +exports.handler = async(event, context) => { + let textractParams = { + Document: { + Bytes: fs.readFileSync("simple-document-image.jpg") + }, + }; + try { + let response = await textract.detectDocumentText(textractParams).promise(); + console.log(JSON.stringify(response),null,2) + }catch(e){ + console.log("Error: ",e) + } } \ No newline at end of file diff --git a/javascriptv3/example_code/cloudwatch-events/actions/put-events.js b/javascriptv3/example_code/cloudwatch-events/actions/put-events.js index d8b44ba77d6..56b8fc16ea6 100644 --- a/javascriptv3/example_code/cloudwatch-events/actions/put-events.js +++ b/javascriptv3/example_code/cloudwatch-events/actions/put-events.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.cloudwatchlogs.actions.PutEvents] import { PutEventsCommand } from "@aws-sdk/client-cloudwatch-events"; diff --git a/javascriptv3/example_code/cloudwatch-events/actions/put-rule.js b/javascriptv3/example_code/cloudwatch-events/actions/put-rule.js index c38e4088b1c..26df2be2778 100644 --- a/javascriptv3/example_code/cloudwatch-events/actions/put-rule.js +++ b/javascriptv3/example_code/cloudwatch-events/actions/put-rule.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.cloudwatchlogs.actions.PutRule] import { PutRuleCommand } from "@aws-sdk/client-cloudwatch-events"; diff --git a/javascriptv3/example_code/cloudwatch-events/actions/put-targets.js b/javascriptv3/example_code/cloudwatch-events/actions/put-targets.js index 9e794ff7922..0438ba94d75 100644 --- a/javascriptv3/example_code/cloudwatch-events/actions/put-targets.js +++ b/javascriptv3/example_code/cloudwatch-events/actions/put-targets.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.cloudwatchlogs.actions.PutTargets] import { PutTargetsCommand } from "@aws-sdk/client-cloudwatch-events"; diff --git a/javascriptv3/example_code/cloudwatch-events/libs/client.js b/javascriptv3/example_code/cloudwatch-events/libs/client.js index f1c4b3e133d..ba35b6984fb 100644 --- a/javascriptv3/example_code/cloudwatch-events/libs/client.js +++ b/javascriptv3/example_code/cloudwatch-events/libs/client.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.cloudwatchevents.client] import { CloudWatchEventsClient } from "@aws-sdk/client-cloudwatch-events"; diff --git a/javascriptv3/example_code/cloudwatch-events/tests/cloudwatch-events.integration.test.js b/javascriptv3/example_code/cloudwatch-events/tests/cloudwatch-events.integration.test.js index feba43ee2d9..4309df2f4f2 100644 --- a/javascriptv3/example_code/cloudwatch-events/tests/cloudwatch-events.integration.test.js +++ b/javascriptv3/example_code/cloudwatch-events/tests/cloudwatch-events.integration.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, beforeAll, afterAll } from "vitest"; import { diff --git a/javascriptv3/example_code/cloudwatch-logs/actions/create-log-group.js b/javascriptv3/example_code/cloudwatch-logs/actions/create-log-group.js index 89ce19bb537..315753916fd 100644 --- a/javascriptv3/example_code/cloudwatch-logs/actions/create-log-group.js +++ b/javascriptv3/example_code/cloudwatch-logs/actions/create-log-group.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.cloudwatchlogs.actions.CreateLogGroup] import { CreateLogGroupCommand } from "@aws-sdk/client-cloudwatch-logs"; diff --git a/javascriptv3/example_code/cloudwatch-logs/actions/delete-log-group.js b/javascriptv3/example_code/cloudwatch-logs/actions/delete-log-group.js index 3e1e9651757..3dd230ea3e8 100644 --- a/javascriptv3/example_code/cloudwatch-logs/actions/delete-log-group.js +++ b/javascriptv3/example_code/cloudwatch-logs/actions/delete-log-group.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.cloudwatchlogs.actions.DeleteLogGroup] import { DeleteLogGroupCommand } from "@aws-sdk/client-cloudwatch-logs"; diff --git a/javascriptv3/example_code/cloudwatch-logs/actions/delete-subscription-filter.js b/javascriptv3/example_code/cloudwatch-logs/actions/delete-subscription-filter.js index 697d583561b..0aae567c8f7 100644 --- a/javascriptv3/example_code/cloudwatch-logs/actions/delete-subscription-filter.js +++ b/javascriptv3/example_code/cloudwatch-logs/actions/delete-subscription-filter.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.cloudwatchlogs.actions.DeleteSubscriptionFilter] import { DeleteSubscriptionFilterCommand } from "@aws-sdk/client-cloudwatch-logs"; diff --git a/javascriptv3/example_code/cloudwatch-logs/actions/describe-log-groups.js b/javascriptv3/example_code/cloudwatch-logs/actions/describe-log-groups.js index ed69979547d..c0606dfd1a1 100644 --- a/javascriptv3/example_code/cloudwatch-logs/actions/describe-log-groups.js +++ b/javascriptv3/example_code/cloudwatch-logs/actions/describe-log-groups.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/cloudwatch-logs/actions/describe-subscription-filters.js b/javascriptv3/example_code/cloudwatch-logs/actions/describe-subscription-filters.js index d355568ed7e..bbca096c3cb 100644 --- a/javascriptv3/example_code/cloudwatch-logs/actions/describe-subscription-filters.js +++ b/javascriptv3/example_code/cloudwatch-logs/actions/describe-subscription-filters.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.cloudwatchlogs.actions.DescribeSubscriptionFilters] import { DescribeSubscriptionFiltersCommand } from "@aws-sdk/client-cloudwatch-logs"; diff --git a/javascriptv3/example_code/cloudwatch-logs/actions/put-subscription-filter.js b/javascriptv3/example_code/cloudwatch-logs/actions/put-subscription-filter.js index f5567805033..9931862f627 100644 --- a/javascriptv3/example_code/cloudwatch-logs/actions/put-subscription-filter.js +++ b/javascriptv3/example_code/cloudwatch-logs/actions/put-subscription-filter.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.cloudwatchlogs.actions.PutSubscriptionFilter] import { PutSubscriptionFilterCommand } from "@aws-sdk/client-cloudwatch-logs"; diff --git a/javascriptv3/example_code/cloudwatch-logs/libs/client.js b/javascriptv3/example_code/cloudwatch-logs/libs/client.js index e7022ff1b43..e05aea04207 100644 --- a/javascriptv3/example_code/cloudwatch-logs/libs/client.js +++ b/javascriptv3/example_code/cloudwatch-logs/libs/client.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cloudwatch.JavaScript.logs.createclientv3] import { CloudWatchLogsClient } from "@aws-sdk/client-cloudwatch-logs"; diff --git a/javascriptv3/example_code/cloudwatch-logs/libs/constants.js b/javascriptv3/example_code/cloudwatch-logs/libs/constants.js index 3c9631df0c9..8da55826863 100644 --- a/javascriptv3/example_code/cloudwatch-logs/libs/constants.js +++ b/javascriptv3/example_code/cloudwatch-logs/libs/constants.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 export const LAMBDA_EXECUTION_POLICY = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"; diff --git a/javascriptv3/example_code/cloudwatch-logs/libs/iam-helper.js b/javascriptv3/example_code/cloudwatch-logs/libs/iam-helper.js index 7916b05cd0e..edb4f709b28 100644 --- a/javascriptv3/example_code/cloudwatch-logs/libs/iam-helper.js +++ b/javascriptv3/example_code/cloudwatch-logs/libs/iam-helper.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { AttachRolePolicyCommand, CreateRoleCommand, diff --git a/javascriptv3/example_code/cloudwatch-logs/libs/lambda-helper.js b/javascriptv3/example_code/cloudwatch-logs/libs/lambda-helper.js index 67672705160..00e878e3fb5 100644 --- a/javascriptv3/example_code/cloudwatch-logs/libs/lambda-helper.js +++ b/javascriptv3/example_code/cloudwatch-logs/libs/lambda-helper.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { readFileSync } from "fs"; import { diff --git a/javascriptv3/example_code/cloudwatch-logs/scenarios/large-query/cloud-watch-query.js b/javascriptv3/example_code/cloudwatch-logs/scenarios/large-query/cloud-watch-query.js index 521c3c28795..a27e5d3f896 100644 --- a/javascriptv3/example_code/cloudwatch-logs/scenarios/large-query/cloud-watch-query.js +++ b/javascriptv3/example_code/cloudwatch-logs/scenarios/large-query/cloud-watch-query.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { StartQueryCommand, GetQueryResultsCommand, diff --git a/javascriptv3/example_code/cloudwatch-logs/scenarios/large-query/index.js b/javascriptv3/example_code/cloudwatch-logs/scenarios/large-query/index.js index 36cdefdc689..c22f0326e51 100644 --- a/javascriptv3/example_code/cloudwatch-logs/scenarios/large-query/index.js +++ b/javascriptv3/example_code/cloudwatch-logs/scenarios/large-query/index.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { CloudWatchLogsClient } from "@aws-sdk/client-cloudwatch-logs"; import { CloudWatchQuery } from "./cloud-watch-query.js"; diff --git a/javascriptv3/example_code/cloudwatch-logs/scenarios/large-query/scouts/python/cloud-watch-query.py b/javascriptv3/example_code/cloudwatch-logs/scenarios/large-query/scouts/python/cloud-watch-query.py index ea867c4bdee..9fda83c457a 100644 --- a/javascriptv3/example_code/cloudwatch-logs/scenarios/large-query/scouts/python/cloud-watch-query.py +++ b/javascriptv3/example_code/cloudwatch-logs/scenarios/large-query/scouts/python/cloud-watch-query.py @@ -1,3 +1,5 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 import boto3 from botocore.config import Config from datetime import datetime, timedelta diff --git a/javascriptv3/example_code/cloudwatch-logs/scenarios/large-query/scouts/rust/cloud-watch-query.rs b/javascriptv3/example_code/cloudwatch-logs/scenarios/large-query/scouts/rust/cloud-watch-query.rs index 3b61cb8fb58..dc09d615894 100644 --- a/javascriptv3/example_code/cloudwatch-logs/scenarios/large-query/scouts/rust/cloud-watch-query.rs +++ b/javascriptv3/example_code/cloudwatch-logs/scenarios/large-query/scouts/rust/cloud-watch-query.rs @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 use aws_config::SdkConfig; use aws_sdk_cloudwatchlogs::{Client, Error, GetQueryResultsRequest, StartQueryRequest}; use std::time::{Duration, SystemTime}; diff --git a/javascriptv3/example_code/cloudwatch-logs/tests/cloudwatch-logs.integration.test.js b/javascriptv3/example_code/cloudwatch-logs/tests/cloudwatch-logs.integration.test.js index ab42b54dc00..5845c7951d4 100644 --- a/javascriptv3/example_code/cloudwatch-logs/tests/cloudwatch-logs.integration.test.js +++ b/javascriptv3/example_code/cloudwatch-logs/tests/cloudwatch-logs.integration.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { DescribeSubscriptionFiltersCommand } from "@aws-sdk/client-cloudwatch-logs"; import { LambdaClient, waitUntilFunctionUpdated } from "@aws-sdk/client-lambda"; diff --git a/javascriptv3/example_code/cloudwatch-logs/tests/cloudwatch-query.unit.test.js b/javascriptv3/example_code/cloudwatch-logs/tests/cloudwatch-query.unit.test.js index b23d2ec9647..ec6ab3fdcc8 100644 --- a/javascriptv3/example_code/cloudwatch-logs/tests/cloudwatch-query.unit.test.js +++ b/javascriptv3/example_code/cloudwatch-logs/tests/cloudwatch-query.unit.test.js @@ -1,3 +1,8 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + import { describe, it, vi, expect } from "vitest"; import { CloudWatchQuery } from "../scenarios/large-query/cloud-watch-query.js"; import { diff --git a/javascriptv3/example_code/cloudwatch-logs/vite.config.js b/javascriptv3/example_code/cloudwatch-logs/vite.config.js index 5e6e3f48986..a602c3bdcfe 100644 --- a/javascriptv3/example_code/cloudwatch-logs/vite.config.js +++ b/javascriptv3/example_code/cloudwatch-logs/vite.config.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { defineConfig } from "vitest/config"; diff --git a/javascriptv3/example_code/cloudwatch/actions/delete-alarms.js b/javascriptv3/example_code/cloudwatch/actions/delete-alarms.js index b2c8a3f0158..ab48bc48932 100644 --- a/javascriptv3/example_code/cloudwatch/actions/delete-alarms.js +++ b/javascriptv3/example_code/cloudwatch/actions/delete-alarms.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.cloudwatch.actions.DeleteAlarms] import { DeleteAlarmsCommand } from "@aws-sdk/client-cloudwatch"; diff --git a/javascriptv3/example_code/cloudwatch/actions/describe-alarms.js b/javascriptv3/example_code/cloudwatch/actions/describe-alarms.js index 67147741f0a..db3d4826466 100644 --- a/javascriptv3/example_code/cloudwatch/actions/describe-alarms.js +++ b/javascriptv3/example_code/cloudwatch/actions/describe-alarms.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.cloudwatch.actions.DescribeAlarms] import { DescribeAlarmsCommand } from "@aws-sdk/client-cloudwatch"; diff --git a/javascriptv3/example_code/cloudwatch/actions/disable-alarm-actions.js b/javascriptv3/example_code/cloudwatch/actions/disable-alarm-actions.js index 670f2038179..ffd20e920bd 100644 --- a/javascriptv3/example_code/cloudwatch/actions/disable-alarm-actions.js +++ b/javascriptv3/example_code/cloudwatch/actions/disable-alarm-actions.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.cloudwatch.actions.DisableAlarmActions] import { DisableAlarmActionsCommand } from "@aws-sdk/client-cloudwatch"; diff --git a/javascriptv3/example_code/cloudwatch/actions/enable-alarm-actions.js b/javascriptv3/example_code/cloudwatch/actions/enable-alarm-actions.js index b713044b949..1ffb85c424e 100644 --- a/javascriptv3/example_code/cloudwatch/actions/enable-alarm-actions.js +++ b/javascriptv3/example_code/cloudwatch/actions/enable-alarm-actions.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.cloudwatch.actions.EnableAlarmActions] import { EnableAlarmActionsCommand } from "@aws-sdk/client-cloudwatch"; diff --git a/javascriptv3/example_code/cloudwatch/actions/list-metrics.js b/javascriptv3/example_code/cloudwatch/actions/list-metrics.js index 6cc8e3b4f88..a0674040bdf 100644 --- a/javascriptv3/example_code/cloudwatch/actions/list-metrics.js +++ b/javascriptv3/example_code/cloudwatch/actions/list-metrics.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.cloudwatch.actions.ListMetrics] import { ListMetricsCommand } from "@aws-sdk/client-cloudwatch"; diff --git a/javascriptv3/example_code/cloudwatch/actions/put-metric-alarm.js b/javascriptv3/example_code/cloudwatch/actions/put-metric-alarm.js index 847ee72615c..110ec454bba 100644 --- a/javascriptv3/example_code/cloudwatch/actions/put-metric-alarm.js +++ b/javascriptv3/example_code/cloudwatch/actions/put-metric-alarm.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.cloudwatch.actions.PutMetricAlarm] import { PutMetricAlarmCommand } from "@aws-sdk/client-cloudwatch"; diff --git a/javascriptv3/example_code/cloudwatch/actions/put-metric-data.js b/javascriptv3/example_code/cloudwatch/actions/put-metric-data.js index fbfb5293a1a..70f5e712172 100644 --- a/javascriptv3/example_code/cloudwatch/actions/put-metric-data.js +++ b/javascriptv3/example_code/cloudwatch/actions/put-metric-data.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.cloudwatch.actions.PutMetricData] import { PutMetricDataCommand } from "@aws-sdk/client-cloudwatch"; diff --git a/javascriptv3/example_code/cloudwatch/libs/client.js b/javascriptv3/example_code/cloudwatch/libs/client.js index 1af3ebbba39..f2bcd56c2ed 100644 --- a/javascriptv3/example_code/cloudwatch/libs/client.js +++ b/javascriptv3/example_code/cloudwatch/libs/client.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.cloudwatch.client] import { CloudWatchClient } from "@aws-sdk/client-cloudwatch"; diff --git a/javascriptv3/example_code/cloudwatch/libs/cloudwatch-helper.js b/javascriptv3/example_code/cloudwatch/libs/cloudwatch-helper.js index 70fea48f26b..1807ee90628 100644 --- a/javascriptv3/example_code/cloudwatch/libs/cloudwatch-helper.js +++ b/javascriptv3/example_code/cloudwatch/libs/cloudwatch-helper.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { DeleteAlarmsCommand, diff --git a/javascriptv3/example_code/cloudwatch/libs/ec2-helper.js b/javascriptv3/example_code/cloudwatch/libs/ec2-helper.js index 093005e0804..ce6b296ff3c 100644 --- a/javascriptv3/example_code/cloudwatch/libs/ec2-helper.js +++ b/javascriptv3/example_code/cloudwatch/libs/ec2-helper.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { EC2Client, RunInstancesCommand, diff --git a/javascriptv3/example_code/cloudwatch/tests/delete-alarms.integration.test.js b/javascriptv3/example_code/cloudwatch/tests/delete-alarms.integration.test.js index 789e1da2c24..8cc19168189 100644 --- a/javascriptv3/example_code/cloudwatch/tests/delete-alarms.integration.test.js +++ b/javascriptv3/example_code/cloudwatch/tests/delete-alarms.integration.test.js @@ -1,12 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ - -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, beforeAll, afterAll } from "vitest"; import { diff --git a/javascriptv3/example_code/cloudwatch/tests/describe-alarms.integration.test.js b/javascriptv3/example_code/cloudwatch/tests/describe-alarms.integration.test.js index a49adc5ce50..75be6c7a3f1 100644 --- a/javascriptv3/example_code/cloudwatch/tests/describe-alarms.integration.test.js +++ b/javascriptv3/example_code/cloudwatch/tests/describe-alarms.integration.test.js @@ -1,12 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ - -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, beforeAll, afterAll } from "vitest"; import { createAlarm, deleteAlarms } from "../libs/cloudwatch-helper.js"; diff --git a/javascriptv3/example_code/cloudwatch/tests/disable-alarm-actions.integration.test.js b/javascriptv3/example_code/cloudwatch/tests/disable-alarm-actions.integration.test.js index 90deeeaf2c7..7dc2c4a5652 100644 --- a/javascriptv3/example_code/cloudwatch/tests/disable-alarm-actions.integration.test.js +++ b/javascriptv3/example_code/cloudwatch/tests/disable-alarm-actions.integration.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, beforeAll, afterAll } from "vitest"; import { diff --git a/javascriptv3/example_code/cloudwatch/tests/enable-alarm-actions.integration.test.js b/javascriptv3/example_code/cloudwatch/tests/enable-alarm-actions.integration.test.js index 85868af8649..c727eda6368 100644 --- a/javascriptv3/example_code/cloudwatch/tests/enable-alarm-actions.integration.test.js +++ b/javascriptv3/example_code/cloudwatch/tests/enable-alarm-actions.integration.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, beforeAll, afterAll } from "vitest"; import { diff --git a/javascriptv3/example_code/cloudwatch/tests/list-metrics.integration.test.js b/javascriptv3/example_code/cloudwatch/tests/list-metrics.integration.test.js index 33a8973cce7..f5de814ebc6 100644 --- a/javascriptv3/example_code/cloudwatch/tests/list-metrics.integration.test.js +++ b/javascriptv3/example_code/cloudwatch/tests/list-metrics.integration.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { main as listMetrics } from "../actions/list-metrics.js"; diff --git a/javascriptv3/example_code/cloudwatch/tests/put-metric-alarm.integration.test.js b/javascriptv3/example_code/cloudwatch/tests/put-metric-alarm.integration.test.js index 315b57c0b1e..bd5fbb3b28e 100644 --- a/javascriptv3/example_code/cloudwatch/tests/put-metric-alarm.integration.test.js +++ b/javascriptv3/example_code/cloudwatch/tests/put-metric-alarm.integration.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, beforeAll, afterAll } from "vitest"; import { deleteAlarms, describeAlarm } from "../libs/cloudwatch-helper.js"; diff --git a/javascriptv3/example_code/cloudwatch/tests/put-metric-data.integration.test.js b/javascriptv3/example_code/cloudwatch/tests/put-metric-data.integration.test.js index a7976cf5855..e1e16cbd898 100644 --- a/javascriptv3/example_code/cloudwatch/tests/put-metric-data.integration.test.js +++ b/javascriptv3/example_code/cloudwatch/tests/put-metric-data.integration.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { v4 as uuidv4 } from "uuid"; import { getMetricData } from "../libs/cloudwatch-helper.js"; diff --git a/javascriptv3/example_code/cloudwatch/vite.config.js b/javascriptv3/example_code/cloudwatch/vite.config.js index 136c7f3eadc..cd73173f292 100644 --- a/javascriptv3/example_code/cloudwatch/vite.config.js +++ b/javascriptv3/example_code/cloudwatch/vite.config.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { defineConfig } from "vitest/config"; diff --git a/javascriptv3/example_code/codebuild/actions/create-project.js b/javascriptv3/example_code/codebuild/actions/create-project.js index 4a04c21716b..8c3f5a433a2 100644 --- a/javascriptv3/example_code/codebuild/actions/create-project.js +++ b/javascriptv3/example_code/codebuild/actions/create-project.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/codebuild/client.js b/javascriptv3/example_code/codebuild/client.js index f5e4ed2f8aa..e4b3a2d3cc5 100644 --- a/javascriptv3/example_code/codebuild/client.js +++ b/javascriptv3/example_code/codebuild/client.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.codebuild.client] import { CodeBuildClient } from "@aws-sdk/client-codebuild"; diff --git a/javascriptv3/example_code/codebuild/tests/create-project.integration.test.js b/javascriptv3/example_code/codebuild/tests/create-project.integration.test.js index 858943fdb95..b8a2e404573 100644 --- a/javascriptv3/example_code/codebuild/tests/create-project.integration.test.js +++ b/javascriptv3/example_code/codebuild/tests/create-project.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, beforeAll, afterAll } from "vitest"; import { S3Client, CreateBucketCommand } from "@aws-sdk/client-s3"; import { DeleteBucketCommand } from "@aws-sdk/client-s3"; diff --git a/javascriptv3/example_code/codecommit/src/MyCodeCommitFunction.js b/javascriptv3/example_code/codecommit/src/MyCodeCommitFunction.js index 9f1ad301ebf..9b6ff3d2ad0 100644 --- a/javascriptv3/example_code/codecommit/src/MyCodeCommitFunction.js +++ b/javascriptv3/example_code/codecommit/src/MyCodeCommitFunction.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[codecommit.nodejs.MyCodeCommitFunction_js.complete] import { diff --git a/javascriptv3/example_code/codecommit/src/createBranch.js b/javascriptv3/example_code/codecommit/src/createBranch.js index cb39bc7cc75..326fa0d3990 100644 --- a/javascriptv3/example_code/codecommit/src/createBranch.js +++ b/javascriptv3/example_code/codecommit/src/createBranch.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. For information about how AWS CodeCommit works, see https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html. diff --git a/javascriptv3/example_code/codecommit/src/createCommit.js b/javascriptv3/example_code/codecommit/src/createCommit.js index a3e152c5932..82a06ff5c6b 100644 --- a/javascriptv3/example_code/codecommit/src/createCommit.js +++ b/javascriptv3/example_code/codecommit/src/createCommit.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. For information about how AWS CodeCommit works, see https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html. diff --git a/javascriptv3/example_code/codecommit/src/createPullRequest.js b/javascriptv3/example_code/codecommit/src/createPullRequest.js index ad26e6e6462..36b5934444e 100644 --- a/javascriptv3/example_code/codecommit/src/createPullRequest.js +++ b/javascriptv3/example_code/codecommit/src/createPullRequest.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. For information about how AWS CodeCommit works, see https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html. diff --git a/javascriptv3/example_code/codecommit/src/createRepository.js b/javascriptv3/example_code/codecommit/src/createRepository.js index 5233a7d85d2..73da3a102c8 100644 --- a/javascriptv3/example_code/codecommit/src/createRepository.js +++ b/javascriptv3/example_code/codecommit/src/createRepository.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. For information about how AWS CodeCommit works, see https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html. diff --git a/javascriptv3/example_code/codecommit/src/deleteBranch.js b/javascriptv3/example_code/codecommit/src/deleteBranch.js index a65a61020a2..9e59bd0d335 100644 --- a/javascriptv3/example_code/codecommit/src/deleteBranch.js +++ b/javascriptv3/example_code/codecommit/src/deleteBranch.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. For information about how AWS CodeCommit works, see https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html. diff --git a/javascriptv3/example_code/codecommit/src/deleteRepository.js b/javascriptv3/example_code/codecommit/src/deleteRepository.js index ce8a6a60a62..e5f571bc154 100644 --- a/javascriptv3/example_code/codecommit/src/deleteRepository.js +++ b/javascriptv3/example_code/codecommit/src/deleteRepository.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. For information about how AWS CodeCommit works, see https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html. diff --git a/javascriptv3/example_code/codecommit/src/describePullRequestEvents.js b/javascriptv3/example_code/codecommit/src/describePullRequestEvents.js index bef10647421..20a103ce5bc 100644 --- a/javascriptv3/example_code/codecommit/src/describePullRequestEvents.js +++ b/javascriptv3/example_code/codecommit/src/describePullRequestEvents.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. For information about how AWS CodeCommit works, see https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html. diff --git a/javascriptv3/example_code/codecommit/src/getMergeOptions.js b/javascriptv3/example_code/codecommit/src/getMergeOptions.js index 7140c96bb0f..960328649df 100644 --- a/javascriptv3/example_code/codecommit/src/getMergeOptions.js +++ b/javascriptv3/example_code/codecommit/src/getMergeOptions.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. For information about how AWS CodeCommit works, see https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html. diff --git a/javascriptv3/example_code/codecommit/src/getPullRequest.js b/javascriptv3/example_code/codecommit/src/getPullRequest.js index 97dbf16bb09..9e4c0437266 100644 --- a/javascriptv3/example_code/codecommit/src/getPullRequest.js +++ b/javascriptv3/example_code/codecommit/src/getPullRequest.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. For information about how AWS CodeCommit works, see https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html. diff --git a/javascriptv3/example_code/codecommit/src/getRepository.js b/javascriptv3/example_code/codecommit/src/getRepository.js index 052292cadc3..ef55e18a727 100644 --- a/javascriptv3/example_code/codecommit/src/getRepository.js +++ b/javascriptv3/example_code/codecommit/src/getRepository.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. For information about how AWS CodeCommit works, see https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html. diff --git a/javascriptv3/example_code/codecommit/src/libs/codeCommitClient.js b/javascriptv3/example_code/codecommit/src/libs/codeCommitClient.js index 7cfb691444c..6cfd1a15cef 100644 --- a/javascriptv3/example_code/codecommit/src/libs/codeCommitClient.js +++ b/javascriptv3/example_code/codecommit/src/libs/codeCommitClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/codecommit/src/listRepositories.js b/javascriptv3/example_code/codecommit/src/listRepositories.js index f1b132b2be1..7d6801c1465 100644 --- a/javascriptv3/example_code/codecommit/src/listRepositories.js +++ b/javascriptv3/example_code/codecommit/src/listRepositories.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. For information about how AWS CodeCommit works, see https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html. diff --git a/javascriptv3/example_code/codecommit/src/mergeBranches.js b/javascriptv3/example_code/codecommit/src/mergeBranches.js index 48a982062f0..6cbd4a623ec 100644 --- a/javascriptv3/example_code/codecommit/src/mergeBranches.js +++ b/javascriptv3/example_code/codecommit/src/mergeBranches.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. For information about how AWS CodeCommit works, see https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html. diff --git a/javascriptv3/example_code/codecommit/tests/createBranch.unit.test.js b/javascriptv3/example_code/codecommit/tests/createBranch.unit.test.js index 27137a61da2..62b142b2b72 100644 --- a/javascriptv3/example_code/codecommit/tests/createBranch.unit.test.js +++ b/javascriptv3/example_code/codecommit/tests/createBranch.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { main, params } from "../src/createBranch"; diff --git a/javascriptv3/example_code/codecommit/tests/createCommit.unit.test.js b/javascriptv3/example_code/codecommit/tests/createCommit.unit.test.js index 3fa4933f913..a90876c909a 100644 --- a/javascriptv3/example_code/codecommit/tests/createCommit.unit.test.js +++ b/javascriptv3/example_code/codecommit/tests/createCommit.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { main, getBranchParams } from "../src/createCommit"; diff --git a/javascriptv3/example_code/codecommit/tests/createPullRequest.unit.test.js b/javascriptv3/example_code/codecommit/tests/createPullRequest.unit.test.js index 388bc3e058c..6349e15fe0a 100644 --- a/javascriptv3/example_code/codecommit/tests/createPullRequest.unit.test.js +++ b/javascriptv3/example_code/codecommit/tests/createPullRequest.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { main, params } from "../src/createPullRequest"; diff --git a/javascriptv3/example_code/codecommit/tests/createRepository.unit.test.js b/javascriptv3/example_code/codecommit/tests/createRepository.unit.test.js index ddcf7838b46..e4f6f2e96e0 100644 --- a/javascriptv3/example_code/codecommit/tests/createRepository.unit.test.js +++ b/javascriptv3/example_code/codecommit/tests/createRepository.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { main, params } from "../src/createRepository"; diff --git a/javascriptv3/example_code/codecommit/tests/deleteBranch.unit.test.js b/javascriptv3/example_code/codecommit/tests/deleteBranch.unit.test.js index be0da166e62..1b38511882c 100644 --- a/javascriptv3/example_code/codecommit/tests/deleteBranch.unit.test.js +++ b/javascriptv3/example_code/codecommit/tests/deleteBranch.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { main, params } from "../src/deleteBranch"; diff --git a/javascriptv3/example_code/codecommit/tests/deleteRepository.unit.test.js b/javascriptv3/example_code/codecommit/tests/deleteRepository.unit.test.js index 4ebfddcc2ac..f988d7f2964 100644 --- a/javascriptv3/example_code/codecommit/tests/deleteRepository.unit.test.js +++ b/javascriptv3/example_code/codecommit/tests/deleteRepository.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { main, params } from "../src/deleteRepository"; diff --git a/javascriptv3/example_code/codecommit/tests/describePullRequestEvents.unit.test.js b/javascriptv3/example_code/codecommit/tests/describePullRequestEvents.unit.test.js index 4adb027101c..300e02227a5 100644 --- a/javascriptv3/example_code/codecommit/tests/describePullRequestEvents.unit.test.js +++ b/javascriptv3/example_code/codecommit/tests/describePullRequestEvents.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { main, params } from "../src/describePullRequestEvents"; diff --git a/javascriptv3/example_code/codecommit/tests/getMergeOptions.unit.test.js b/javascriptv3/example_code/codecommit/tests/getMergeOptions.unit.test.js index c1f43275b34..b8b21772f47 100644 --- a/javascriptv3/example_code/codecommit/tests/getMergeOptions.unit.test.js +++ b/javascriptv3/example_code/codecommit/tests/getMergeOptions.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { main, params } from "../src/getMergeOptions"; diff --git a/javascriptv3/example_code/codecommit/tests/getPullRequest.unit.test.js b/javascriptv3/example_code/codecommit/tests/getPullRequest.unit.test.js index 62025e430ff..e6759343986 100644 --- a/javascriptv3/example_code/codecommit/tests/getPullRequest.unit.test.js +++ b/javascriptv3/example_code/codecommit/tests/getPullRequest.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { main, params } from "../src/getPullRequest"; diff --git a/javascriptv3/example_code/codecommit/tests/getRepository.unit.test.js b/javascriptv3/example_code/codecommit/tests/getRepository.unit.test.js index 2eddd884ef7..8aa20e8904b 100644 --- a/javascriptv3/example_code/codecommit/tests/getRepository.unit.test.js +++ b/javascriptv3/example_code/codecommit/tests/getRepository.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { main, params } from "../src/getRepository"; diff --git a/javascriptv3/example_code/codecommit/tests/listRepositories.unit.test.js b/javascriptv3/example_code/codecommit/tests/listRepositories.unit.test.js index 64b06cb93e5..4bc07a1a18b 100644 --- a/javascriptv3/example_code/codecommit/tests/listRepositories.unit.test.js +++ b/javascriptv3/example_code/codecommit/tests/listRepositories.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { main, params } from "../src/listRepositories"; diff --git a/javascriptv3/example_code/codecommit/tests/mergeBranches.unit.test.js b/javascriptv3/example_code/codecommit/tests/mergeBranches.unit.test.js index 98797db8012..d48268c4e7c 100644 --- a/javascriptv3/example_code/codecommit/tests/mergeBranches.unit.test.js +++ b/javascriptv3/example_code/codecommit/tests/mergeBranches.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { main, params } from "../src/mergeBranches"; diff --git a/javascriptv3/example_code/codepipeline/MyCodePipelineFunction.js b/javascriptv3/example_code/codepipeline/MyCodePipelineFunction.js index 7c5e0ab8e04..0185caa08aa 100644 --- a/javascriptv3/example_code/codepipeline/MyCodePipelineFunction.js +++ b/javascriptv3/example_code/codepipeline/MyCodePipelineFunction.js @@ -1,24 +1,7 @@ -// Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -// -// This file is 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/ -// -// This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -// CONDITIONS OF ANY KIND, either express or implied. See the License for the -// specific language governing permissions and limitations under the License. +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + -// snippet-sourcedescription:[MyCodePipelineFunction.js demonstrates how to use an AWS Lambda function to invoke a Lambda event in CodePipeline.] -// snippet-service:[codepipeline] -// snippet-keyword:[Javascript] -// snippet-keyword:[AWS CodePipeline] -// snippet-keyword:[Code Sample] -// snippet-keyword:[Invoke] -// snippet-sourcetype:[full-example] -// snippet-sourceauthor:[AWS] -// snippet-sourcedate:[2016-03-07] // snippet-start:[codepipeline.javascript.MyCodePipelineFunction.complete] var assert = require('assert'); diff --git a/javascriptv3/example_code/codepipeline/MyCodePipelineFunction.py b/javascriptv3/example_code/codepipeline/MyCodePipelineFunction.py index a554fb91743..ab6e6ec527c 100644 --- a/javascriptv3/example_code/codepipeline/MyCodePipelineFunction.py +++ b/javascriptv3/example_code/codepipeline/MyCodePipelineFunction.py @@ -1,26 +1,5 @@ -# Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. -# -# This file is 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/ -# -# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR -# CONDITIONS OF ANY KIND, either express or implied. See the License for the -# specific language governing permissions and limitations under the License. - -# snippet-sourcedescription:[MyCodePipelineFunction.py demonstrates how to use an AWS Lambda function to create or update a stack based on a supplied AWS CloudFormation template and Lambda execution role.] -# snippet-service:[codepipeline] -# snippet-keyword:[Python] -# snippet-sourcesyntax:[python] -# snippet-sourcesyntax:[python] -# snippet-keyword:[AWS CodePipeline] -# snippet-keyword:[Code Sample] -# snippet-keyword:[Invoke] -# snippet-sourcetype:[full-example] -# snippet-sourceauthor:[AWS] -# snippet-sourcedate:[2016-03-07] +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 from __future__ import print_function from boto3.session import Session diff --git a/javascriptv3/example_code/cognito-identity-provider/actions/admin-get-user.js b/javascriptv3/example_code/cognito-identity-provider/actions/admin-get-user.js index a563e17440d..f0a7f6ebd49 100644 --- a/javascriptv3/example_code/cognito-identity-provider/actions/admin-get-user.js +++ b/javascriptv3/example_code/cognito-identity-provider/actions/admin-get-user.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { AdminGetUserCommand, diff --git a/javascriptv3/example_code/cognito-identity-provider/actions/admin-initiate-auth.js b/javascriptv3/example_code/cognito-identity-provider/actions/admin-initiate-auth.js index 8a6c18f43cd..85137dd7586 100644 --- a/javascriptv3/example_code/cognito-identity-provider/actions/admin-initiate-auth.js +++ b/javascriptv3/example_code/cognito-identity-provider/actions/admin-initiate-auth.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { AdminInitiateAuthCommand, diff --git a/javascriptv3/example_code/cognito-identity-provider/actions/admin-respond-to-auth-challenge.js b/javascriptv3/example_code/cognito-identity-provider/actions/admin-respond-to-auth-challenge.js index 8842241acdd..332a920153b 100644 --- a/javascriptv3/example_code/cognito-identity-provider/actions/admin-respond-to-auth-challenge.js +++ b/javascriptv3/example_code/cognito-identity-provider/actions/admin-respond-to-auth-challenge.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { CognitoIdentityProviderClient, diff --git a/javascriptv3/example_code/cognito-identity-provider/actions/associate-software-token.js b/javascriptv3/example_code/cognito-identity-provider/actions/associate-software-token.js index e0833088bb8..567a50303a9 100644 --- a/javascriptv3/example_code/cognito-identity-provider/actions/associate-software-token.js +++ b/javascriptv3/example_code/cognito-identity-provider/actions/associate-software-token.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { AssociateSoftwareTokenCommand, diff --git a/javascriptv3/example_code/cognito-identity-provider/actions/confirm-device.js b/javascriptv3/example_code/cognito-identity-provider/actions/confirm-device.js index 3e5a849780a..34941f0086b 100644 --- a/javascriptv3/example_code/cognito-identity-provider/actions/confirm-device.js +++ b/javascriptv3/example_code/cognito-identity-provider/actions/confirm-device.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { CognitoIdentityProviderClient, diff --git a/javascriptv3/example_code/cognito-identity-provider/actions/confirm-sign-up.js b/javascriptv3/example_code/cognito-identity-provider/actions/confirm-sign-up.js index fb5cd1eb6bf..ea7f78bea6d 100644 --- a/javascriptv3/example_code/cognito-identity-provider/actions/confirm-sign-up.js +++ b/javascriptv3/example_code/cognito-identity-provider/actions/confirm-sign-up.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { ConfirmSignUpCommand, diff --git a/javascriptv3/example_code/cognito-identity-provider/actions/create-user-pool-client.js b/javascriptv3/example_code/cognito-identity-provider/actions/create-user-pool-client.js index ee46afa12cd..03eb6338cc1 100644 --- a/javascriptv3/example_code/cognito-identity-provider/actions/create-user-pool-client.js +++ b/javascriptv3/example_code/cognito-identity-provider/actions/create-user-pool-client.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { CreateUserPoolClientCommand, diff --git a/javascriptv3/example_code/cognito-identity-provider/actions/create-user-pool.js b/javascriptv3/example_code/cognito-identity-provider/actions/create-user-pool.js index d6220e1d689..45c7b4be3af 100644 --- a/javascriptv3/example_code/cognito-identity-provider/actions/create-user-pool.js +++ b/javascriptv3/example_code/cognito-identity-provider/actions/create-user-pool.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { CreateUserPoolCommand, diff --git a/javascriptv3/example_code/cognito-identity-provider/actions/delete-user-pool.js b/javascriptv3/example_code/cognito-identity-provider/actions/delete-user-pool.js index 80944f317fc..1bb17d6100e 100644 --- a/javascriptv3/example_code/cognito-identity-provider/actions/delete-user-pool.js +++ b/javascriptv3/example_code/cognito-identity-provider/actions/delete-user-pool.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { DeleteUserPoolCommand, diff --git a/javascriptv3/example_code/cognito-identity-provider/actions/initiate-auth.js b/javascriptv3/example_code/cognito-identity-provider/actions/initiate-auth.js index 8aa6f10e24f..3ccead79e2f 100644 --- a/javascriptv3/example_code/cognito-identity-provider/actions/initiate-auth.js +++ b/javascriptv3/example_code/cognito-identity-provider/actions/initiate-auth.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { AuthFlowType, diff --git a/javascriptv3/example_code/cognito-identity-provider/actions/list-users.js b/javascriptv3/example_code/cognito-identity-provider/actions/list-users.js index 4b14b8af992..6cdea8d0062 100644 --- a/javascriptv3/example_code/cognito-identity-provider/actions/list-users.js +++ b/javascriptv3/example_code/cognito-identity-provider/actions/list-users.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { ListUsersCommand, diff --git a/javascriptv3/example_code/cognito-identity-provider/actions/resend-confirmation-code.js b/javascriptv3/example_code/cognito-identity-provider/actions/resend-confirmation-code.js index 9a862ea78a5..d4d3a56095d 100644 --- a/javascriptv3/example_code/cognito-identity-provider/actions/resend-confirmation-code.js +++ b/javascriptv3/example_code/cognito-identity-provider/actions/resend-confirmation-code.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { ResendConfirmationCodeCommand, diff --git a/javascriptv3/example_code/cognito-identity-provider/actions/respond-to-auth-challenge.js b/javascriptv3/example_code/cognito-identity-provider/actions/respond-to-auth-challenge.js index 7c56c45089c..78ca8de7fc4 100644 --- a/javascriptv3/example_code/cognito-identity-provider/actions/respond-to-auth-challenge.js +++ b/javascriptv3/example_code/cognito-identity-provider/actions/respond-to-auth-challenge.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { ChallengeNameType, diff --git a/javascriptv3/example_code/cognito-identity-provider/actions/set-user-pool-mfa-config.js b/javascriptv3/example_code/cognito-identity-provider/actions/set-user-pool-mfa-config.js index f779fa6f5f2..374f226d7f9 100644 --- a/javascriptv3/example_code/cognito-identity-provider/actions/set-user-pool-mfa-config.js +++ b/javascriptv3/example_code/cognito-identity-provider/actions/set-user-pool-mfa-config.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { SetUserPoolMfaConfigCommand, diff --git a/javascriptv3/example_code/cognito-identity-provider/actions/sign-up.js b/javascriptv3/example_code/cognito-identity-provider/actions/sign-up.js index e5e1184b512..cde70459a64 100644 --- a/javascriptv3/example_code/cognito-identity-provider/actions/sign-up.js +++ b/javascriptv3/example_code/cognito-identity-provider/actions/sign-up.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { SignUpCommand, diff --git a/javascriptv3/example_code/cognito-identity-provider/actions/verify-software-token.js b/javascriptv3/example_code/cognito-identity-provider/actions/verify-software-token.js index d556750079c..ec04e3d2562 100644 --- a/javascriptv3/example_code/cognito-identity-provider/actions/verify-software-token.js +++ b/javascriptv3/example_code/cognito-identity-provider/actions/verify-software-token.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { VerifySoftwareTokenCommand, diff --git a/javascriptv3/example_code/cognito-identity-provider/hello.js b/javascriptv3/example_code/cognito-identity-provider/hello.js index 4e65f94315a..f355e8297c5 100644 --- a/javascriptv3/example_code/cognito-identity-provider/hello.js +++ b/javascriptv3/example_code/cognito-identity-provider/hello.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/admin-get-user-handler.js b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/admin-get-user-handler.js index ecafe6c6824..d88ac040ba3 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/admin-get-user-handler.js +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/admin-get-user-handler.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { getFirstEntry } from "@aws-sdk-examples/libs/utils/util-csv.js"; import { log } from "@aws-sdk-examples/libs/utils/util-log.js"; diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/admin-initiate-auth-handler.js b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/admin-initiate-auth-handler.js index 1c8dc54834d..34d04c2698c 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/admin-initiate-auth-handler.js +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/admin-initiate-auth-handler.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** snippet-start:[javascript.v3.cognito-idp.scenarios.basic.AdminInitiateAuthHandler] **/ import qrcode from "qrcode-terminal"; import { log } from "@aws-sdk-examples/libs/utils/util-log.js"; diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/admin-respond-to-auth-challenge-handler.js b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/admin-respond-to-auth-challenge-handler.js index 1d709649795..fb92b2e3723 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/admin-respond-to-auth-challenge-handler.js +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/admin-respond-to-auth-challenge-handler.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** snippet-start:[javascript.v3.cognito-idp.scenarios.basic.AdminRespondToAuthChallengeHandler] **/ import { log } from "@aws-sdk-examples/libs/utils/util-log.js"; diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/clean-up-handler.js b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/clean-up-handler.js index d3cc73fbb36..efe3f5ce373 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/clean-up-handler.js +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/clean-up-handler.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { deleteFiles } from "@aws-sdk-examples/libs/utils/util-fs.js"; import { log } from "@aws-sdk-examples/libs/utils/util-log.js"; diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/confirm-sign-up-handler.js b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/confirm-sign-up-handler.js index d5ccdd76a7a..41f5ba9153a 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/confirm-sign-up-handler.js +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/confirm-sign-up-handler.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** snippet-start:[javascript.v3.cognito-idp.scenarios.basic.ConfirmSignUpHandler] **/ import { log } from "@aws-sdk-examples/libs/utils/util-log.js"; diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/constants.js b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/constants.js index 520cc49eefc..23a0c772eae 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/constants.js +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/constants.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 const FILE_USER_POOLS = "user-pools"; const NAME_CLIENT = "example-client"; diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/create-user-pool-handler.js b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/create-user-pool-handler.js index b22dce98684..e38b3eb5b33 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/create-user-pool-handler.js +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/create-user-pool-handler.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { log } from "@aws-sdk-examples/libs/utils/util-log.js"; import { getTmp, setTmp } from "@aws-sdk-examples/libs/utils/util-fs.js"; diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/list-users-handler.js b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/list-users-handler.js index 0592cb58455..4283ed8933a 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/list-users-handler.js +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/list-users-handler.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { getFirstEntry } from "@aws-sdk-examples/libs/utils/util-csv.js"; import { log } from "@aws-sdk-examples/libs/utils/util-log.js"; diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/resend-confirmation-code-handler.js b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/resend-confirmation-code-handler.js index e1a02d21646..3db7c42fa42 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/resend-confirmation-code-handler.js +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/resend-confirmation-code-handler.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { getFirstEntry } from "@aws-sdk-examples/libs/utils/util-csv.js"; import { log } from "@aws-sdk-examples/libs/utils/util-log.js"; diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/sign-up-handler.js b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/sign-up-handler.js index f0c868b7dbb..63ba8b334f1 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/sign-up-handler.js +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/sign-up-handler.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** snippet-start:[javascript.v3.cognito-idp.scenarios.basic.SignUpHandler] **/ import { log } from "@aws-sdk-examples/libs/utils/util-log.js"; diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/verify-software-token-handler.js b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/verify-software-token-handler.js index 037616b039d..e486d172925 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/verify-software-token-handler.js +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/command-handlers/verify-software-token-handler.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** snippet-start:[javascript.v3.cognito-idp.scenarios.basic.VerifySoftwareTokenHandler] **/ import { log } from "@aws-sdk-examples/libs/utils/util-log.js"; diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/index.js b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/index.js index 749217f7e29..384272982c5 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/index.js +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/basic/index.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { createInterface } from "readline"; import { stdin as input, stdout as output } from "process"; diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/custom-auth-example.js b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/custom-auth-example.js index 06031dd0731..bf7c92e3df0 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/custom-auth-example.js +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/custom-auth-example.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* Use this script to verify the custom authentication flow Lambda triggers. Several Lambda triggers must be turned on and set up in Amazon Cognito diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/auth-challenge-create.mjs b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/auth-challenge-create.mjs index d5ee11dcd05..1d817c63f00 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/auth-challenge-create.mjs +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/auth-challenge-create.mjs @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-create-auth-challenge.html. diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/auth-challenge-define.mjs b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/auth-challenge-define.mjs index 2511dc1a898..e8f6ed710de 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/auth-challenge-define.mjs +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/auth-challenge-define.mjs @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-define-auth-challenge.html. diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/auth-challenge-verify.mjs b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/auth-challenge-verify.mjs index 21bbd67e743..632038d6050 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/auth-challenge-verify.mjs +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/auth-challenge-verify.mjs @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-verify-auth-challenge-response.html. diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/authentication-post.mjs b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/authentication-post.mjs index d8578dc9631..a28bfe0baf0 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/authentication-post.mjs +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/authentication-post.mjs @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-post-authentication.html. */ diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/authentication-pre.mjs b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/authentication-pre.mjs index 45882a55709..05338fc098a 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/authentication-pre.mjs +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/authentication-pre.mjs @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-authentication.html. */ diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/confirmation-post.mjs b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/confirmation-post.mjs index 0901f2c5f29..98ce79e7ac9 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/confirmation-post.mjs +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/confirmation-post.mjs @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-post-confirmation.html. */ diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/custom-message-admin-create.mjs b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/custom-message-admin-create.mjs index abc944c0062..4722d98f918 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/custom-message-admin-create.mjs +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/custom-message-admin-create.mjs @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-message.html. */ diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/custom-message-sign-up.mjs b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/custom-message-sign-up.mjs index 7a289ddb7b2..8f20e18710e 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/custom-message-sign-up.mjs +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/custom-message-sign-up.mjs @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-custom-message.html. */ diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/migrate-user.mjs b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/migrate-user.mjs index dab1302b2ee..a1a6c12058f 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/migrate-user.mjs +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/migrate-user.mjs @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-migrate-user.html. */ diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/sign-up-pre-auto-confirm-domain.mjs b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/sign-up-pre-auto-confirm-domain.mjs index 0f8ae81f8c3..3e764d2d9c7 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/sign-up-pre-auto-confirm-domain.mjs +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/sign-up-pre-auto-confirm-domain.mjs @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-sign-up.html. */ diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/sign-up-pre-auto-confirm-verify.mjs b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/sign-up-pre-auto-confirm-verify.mjs index dc7d3b0672d..905aa97e22a 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/sign-up-pre-auto-confirm-verify.mjs +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/sign-up-pre-auto-confirm-verify.mjs @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-sign-up.html. */ diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/token-generation-pre-add-suppress-claim.mjs b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/token-generation-pre-add-suppress-claim.mjs index 08decf50fd3..2df02857b33 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/token-generation-pre-add-suppress-claim.mjs +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/token-generation-pre-add-suppress-claim.mjs @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-token-generation.html. */ diff --git a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/token-generation-pre-modify-group.mjs b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/token-generation-pre-modify-group.mjs index 5c6ba19d213..f1c3a160cbc 100644 --- a/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/token-generation-pre-modify-group.mjs +++ b/javascriptv3/example_code/cognito-identity-provider/scenarios/lambda-triggers/functions/token-generation-pre-modify-group.mjs @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-token-generation.html. diff --git a/javascriptv3/example_code/cognito-identity-provider/tests/actions.integration.test.js b/javascriptv3/example_code/cognito-identity-provider/tests/actions.integration.test.js index 387465de428..e45f13ca397 100644 --- a/javascriptv3/example_code/cognito-identity-provider/tests/actions.integration.test.js +++ b/javascriptv3/example_code/cognito-identity-provider/tests/actions.integration.test.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, afterAll } from "vitest"; import { createUserPool } from "../actions/create-user-pool.js"; diff --git a/javascriptv3/example_code/cognito-identity-provider/tests/auth-challenge-create.unit.test.js b/javascriptv3/example_code/cognito-identity-provider/tests/auth-challenge-create.unit.test.js index 89fab2339e4..85505941d48 100644 --- a/javascriptv3/example_code/cognito-identity-provider/tests/auth-challenge-create.unit.test.js +++ b/javascriptv3/example_code/cognito-identity-provider/tests/auth-challenge-create.unit.test.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { handler } from "../scenarios/lambda-triggers/functions/auth-challenge-create.mjs"; diff --git a/javascriptv3/example_code/cognito-identity-provider/tests/auth-challenge-define.unit.test.js b/javascriptv3/example_code/cognito-identity-provider/tests/auth-challenge-define.unit.test.js index 9206aa862f7..7cf9a80339f 100644 --- a/javascriptv3/example_code/cognito-identity-provider/tests/auth-challenge-define.unit.test.js +++ b/javascriptv3/example_code/cognito-identity-provider/tests/auth-challenge-define.unit.test.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { handler } from "../scenarios/lambda-triggers/functions/auth-challenge-define.mjs"; diff --git a/javascriptv3/example_code/cognito-identity-provider/tests/auth-challenge-verify.unit.test.js b/javascriptv3/example_code/cognito-identity-provider/tests/auth-challenge-verify.unit.test.js index 833105ebe7f..e6dad64c925 100644 --- a/javascriptv3/example_code/cognito-identity-provider/tests/auth-challenge-verify.unit.test.js +++ b/javascriptv3/example_code/cognito-identity-provider/tests/auth-challenge-verify.unit.test.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { handler } from "../scenarios/lambda-triggers/functions/auth-challenge-verify.mjs"; diff --git a/javascriptv3/example_code/cognito-identity-provider/tests/authentication-post.unit.test.js b/javascriptv3/example_code/cognito-identity-provider/tests/authentication-post.unit.test.js index 3dbf5bc32b9..2b83b7ee1aa 100644 --- a/javascriptv3/example_code/cognito-identity-provider/tests/authentication-post.unit.test.js +++ b/javascriptv3/example_code/cognito-identity-provider/tests/authentication-post.unit.test.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; diff --git a/javascriptv3/example_code/cognito-identity-provider/tests/authentication-pre.unit.test.js b/javascriptv3/example_code/cognito-identity-provider/tests/authentication-pre.unit.test.js index 7b7ea4df0c2..0a50eaa0302 100644 --- a/javascriptv3/example_code/cognito-identity-provider/tests/authentication-pre.unit.test.js +++ b/javascriptv3/example_code/cognito-identity-provider/tests/authentication-pre.unit.test.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { handler } from "../scenarios/lambda-triggers/functions/authentication-pre.mjs"; diff --git a/javascriptv3/example_code/cognito-identity-provider/tests/confirmation-post.unit.test.js b/javascriptv3/example_code/cognito-identity-provider/tests/confirmation-post.unit.test.js index 725c1eab223..95d234a5093 100644 --- a/javascriptv3/example_code/cognito-identity-provider/tests/confirmation-post.unit.test.js +++ b/javascriptv3/example_code/cognito-identity-provider/tests/confirmation-post.unit.test.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi, beforeAll } from "vitest"; let mockSendFn = vi.fn(async () => {}); diff --git a/javascriptv3/example_code/cognito-identity-provider/tests/custom-message-admin-create.unit.test.js b/javascriptv3/example_code/cognito-identity-provider/tests/custom-message-admin-create.unit.test.js index 1e237db9bee..f58844c5c1f 100644 --- a/javascriptv3/example_code/cognito-identity-provider/tests/custom-message-admin-create.unit.test.js +++ b/javascriptv3/example_code/cognito-identity-provider/tests/custom-message-admin-create.unit.test.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { handler } from "../scenarios/lambda-triggers/functions/custom-message-admin-create.mjs"; diff --git a/javascriptv3/example_code/cognito-identity-provider/tests/custom-message-sign-up.unit.test.js b/javascriptv3/example_code/cognito-identity-provider/tests/custom-message-sign-up.unit.test.js index 8cbdd4fab74..b8a7692b89d 100644 --- a/javascriptv3/example_code/cognito-identity-provider/tests/custom-message-sign-up.unit.test.js +++ b/javascriptv3/example_code/cognito-identity-provider/tests/custom-message-sign-up.unit.test.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { handler } from "../scenarios/lambda-triggers/functions/custom-message-sign-up.mjs"; diff --git a/javascriptv3/example_code/cognito-identity-provider/tests/migrate-user.unit.test.js b/javascriptv3/example_code/cognito-identity-provider/tests/migrate-user.unit.test.js index 74143cda8f4..844b556b94e 100644 --- a/javascriptv3/example_code/cognito-identity-provider/tests/migrate-user.unit.test.js +++ b/javascriptv3/example_code/cognito-identity-provider/tests/migrate-user.unit.test.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { handler } from "../scenarios/lambda-triggers/functions/migrate-user.mjs"; diff --git a/javascriptv3/example_code/cognito-identity-provider/tests/sign-up-pre-auto-confirm-domain.unit.test.js b/javascriptv3/example_code/cognito-identity-provider/tests/sign-up-pre-auto-confirm-domain.unit.test.js index 10e79d70ed9..7d2057aaa51 100644 --- a/javascriptv3/example_code/cognito-identity-provider/tests/sign-up-pre-auto-confirm-domain.unit.test.js +++ b/javascriptv3/example_code/cognito-identity-provider/tests/sign-up-pre-auto-confirm-domain.unit.test.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { handler } from "../scenarios/lambda-triggers/functions/sign-up-pre-auto-confirm-domain.mjs"; diff --git a/javascriptv3/example_code/cognito-identity-provider/tests/sign-up-pre-auto-confirm-verify.unit.test.js b/javascriptv3/example_code/cognito-identity-provider/tests/sign-up-pre-auto-confirm-verify.unit.test.js index 39e52494cfa..fe297e3a02f 100644 --- a/javascriptv3/example_code/cognito-identity-provider/tests/sign-up-pre-auto-confirm-verify.unit.test.js +++ b/javascriptv3/example_code/cognito-identity-provider/tests/sign-up-pre-auto-confirm-verify.unit.test.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { handler } from "../scenarios/lambda-triggers/functions/sign-up-pre-auto-confirm-verify.mjs"; diff --git a/javascriptv3/example_code/cognito-identity-provider/tests/token-generation-pre-add-suppress-claim.unit.test.js b/javascriptv3/example_code/cognito-identity-provider/tests/token-generation-pre-add-suppress-claim.unit.test.js index 6d19be8765c..d2e28f4bc34 100644 --- a/javascriptv3/example_code/cognito-identity-provider/tests/token-generation-pre-add-suppress-claim.unit.test.js +++ b/javascriptv3/example_code/cognito-identity-provider/tests/token-generation-pre-add-suppress-claim.unit.test.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; diff --git a/javascriptv3/example_code/cognito-identity-provider/tests/token-generation-pre-modify-group.unit.test.js b/javascriptv3/example_code/cognito-identity-provider/tests/token-generation-pre-modify-group.unit.test.js index f1f548e41f6..c13f2e2eae0 100644 --- a/javascriptv3/example_code/cognito-identity-provider/tests/token-generation-pre-modify-group.unit.test.js +++ b/javascriptv3/example_code/cognito-identity-provider/tests/token-generation-pre-modify-group.unit.test.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { it, describe, expect } from "vitest"; import { handler } from "../scenarios/lambda-triggers/functions/token-generation-pre-modify-group.mjs"; diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/client.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/client.ts index f0ee2697adf..c856e4c2a6b 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/client.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/client.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { RDSDataClient } from "@aws-sdk/client-rds-data"; import { SESClient } from "@aws-sdk/client-ses"; diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/handlers/get-items-handler.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/handlers/get-items-handler.ts index 721e6b97fb9..7ae6c5c0477 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/handlers/get-items-handler.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/handlers/get-items-handler.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { Handler } from "src/types/handler.js"; import { command as getAllItemsCommand } from "../statement-commands/get-all-items.js"; import { command as getArchivedItemsCommand } from "../statement-commands/get-archived-items.js"; diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/handlers/parse-item.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/handlers/parse-item.ts index 93c8944c101..197233e102b 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/handlers/parse-item.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/handlers/parse-item.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { Item } from "../types/item.js"; const parseItem = (record: DBRecord): Item => { diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/handlers/post-items-handler.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/handlers/post-items-handler.ts index c9b76f010e1..a7248a2c7c6 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/handlers/post-items-handler.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/handlers/post-items-handler.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { v4 as uuidv4 } from "uuid"; import { Handler } from "src/types/handler.js"; import { Item } from "src/types/item.js"; diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/handlers/post-items-report-handler.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/handlers/post-items-report-handler.ts index 09b937e733c..e64deae3174 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/handlers/post-items-report-handler.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/handlers/post-items-report-handler.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { SendRawEmailCommand } from "@aws-sdk/client-ses"; import { createMimeMessage, TextFormat } from "mimetext"; import { format } from "prettier"; diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/handlers/put-items-archive-handler.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/handlers/put-items-archive-handler.ts index d1ac6c046c8..6fce1916336 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/handlers/put-items-archive-handler.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/handlers/put-items-archive-handler.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import type { Handler } from "src/types/handler.js"; import { buildStatementCommand } from "../statement-commands/command-helper.js"; diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/index.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/index.ts index 1a1f6f27dd4..5aa4e000970 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/index.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/index.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import express from "express"; import cors from "cors"; import { rdsDataClient, sesClient } from "./client.js"; diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/middleware/validate-db.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/middleware/validate-db.ts index 0e5d91255b9..7737396b3d4 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/middleware/validate-db.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/middleware/validate-db.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { RequestHandler } from "express"; import { command as createTableCommand } from "../statement-commands/create-table.js"; import { command as getAllItemsCommand } from "../statement-commands/get-all-items.js"; diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/command-helper.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/command-helper.ts index a9f0a1c6239..6ae571f0214 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/command-helper.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/command-helper.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { ExecuteStatementCommand } from "@aws-sdk/client-rds-data"; import env from "../../env.json" assert { type: "json" }; diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/create-table.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/create-table.ts index 84fe4d85d12..6977dd11b41 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/create-table.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/create-table.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { buildStatementCommand } from "./command-helper.js"; const command = buildStatementCommand(` diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/get-active-items.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/get-active-items.ts index 9cdcbbb0394..81b3dd5f889 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/get-active-items.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/get-active-items.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { buildStatementCommand } from "./command-helper.js"; const command = buildStatementCommand("select * from items where archived = 0"); diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/get-all-items.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/get-all-items.ts index d6ea9e27946..2fa7cd6df46 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/get-all-items.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/get-all-items.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { buildStatementCommand } from "./command-helper.js"; const command = buildStatementCommand("select * from items"); diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/get-archived-items.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/get-archived-items.ts index f40909b1e23..232afd4bb18 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/get-archived-items.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/get-archived-items.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { buildStatementCommand } from "./command-helper.js"; const command = buildStatementCommand("select * from items where archived = 1"); diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/types/db-record.d.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/types/db-record.d.ts index ae33fc359ae..06df8f6dad3 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/types/db-record.d.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/types/db-record.d.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 declare type DBRecordValue = Record; declare type DBRecord = DBRecordValue[]; declare type DBRecords = DBRecord[]; diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/types/handler.d.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/types/handler.d.ts index 6794859631b..15912c193bb 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/types/handler.d.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/types/handler.d.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { RequestHandler } from "express"; declare type Handler = { diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/types/item.d.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/types/item.d.ts index 93cd02280c6..3544cd094fb 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/types/item.d.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/types/item.d.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 declare type Item = { /** * A UUID that is generated by the middleware. diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/types/sendable.d.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/types/sendable.d.ts index db5ee386924..810c0ac275b 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/src/types/sendable.d.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/src/types/sendable.d.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 declare interface Sendable { send: (command: any) => Promise } \ No newline at end of file diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/tests/command-helper.unit.test.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/tests/command-helper.unit.test.ts index cd32268da03..61b6c200df4 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/tests/command-helper.unit.test.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/tests/command-helper.unit.test.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { buildStatementCommand } from "../src/statement-commands/command-helper.js"; diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/tests/get-items-handler.unit.test.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/tests/get-items-handler.unit.test.ts index 5a6bb7f239c..dc847d7037a 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/tests/get-items-handler.unit.test.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/tests/get-items-handler.unit.test.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, vi, expect } from "vitest"; import { NextFunction, Request, Response } from "express"; import QueryString from "qs"; diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/tests/parse-item.unit.test.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/tests/parse-item.unit.test.ts index 121f326a631..0e6f14bfbc6 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/tests/parse-item.unit.test.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/tests/parse-item.unit.test.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import type { Item } from "src/types/item.js"; import { parseItem } from "../src/handlers/parse-item.js"; diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/tests/post-items-report-handler.unit.test.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/tests/post-items-report-handler.unit.test.ts index 0beb1f0da2a..bcfd9188645 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/tests/post-items-report-handler.unit.test.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/tests/post-items-report-handler.unit.test.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, expect, it } from "vitest"; import { csvToHtmlTable, diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/tests/validate-db.unit.test.ts b/javascriptv3/example_code/cross-services/aurora-serverless-app/tests/validate-db.unit.test.ts index 78800b9a90a..c8e14aa2940 100644 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/tests/validate-db.unit.test.ts +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/tests/validate-db.unit.test.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; import { NextFunction, Request, Response } from "express"; import { errorCodes, validateDb } from "../src/middleware/validate-db.js"; diff --git a/javascriptv3/example_code/cross-services/aurora-serverless-app/watch.js b/javascriptv3/example_code/cross-services/aurora-serverless-app/watch.js index 2ef395da723..ed386c72bba 100755 --- a/javascriptv3/example_code/cross-services/aurora-serverless-app/watch.js +++ b/javascriptv3/example_code/cross-services/aurora-serverless-app/watch.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { spawn } from "node:child_process"; const format = (data) => data.toString().trim(); diff --git a/javascriptv3/example_code/cross-services/ddb-item-tracker/app.js b/javascriptv3/example_code/cross-services/ddb-item-tracker/app.js index 521f86e5f8c..a1058e140f0 100644 --- a/javascriptv3/example_code/cross-services/ddb-item-tracker/app.js +++ b/javascriptv3/example_code/cross-services/ddb-item-tracker/app.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* Purpose: app.js is the main file in the Amazon DynamoDB Item Tracker example app. It interacts with the Express web framework to execute code. diff --git a/javascriptv3/example_code/cross-services/ddb-item-tracker/public/dynamoAppHelperFiles/create-table.js b/javascriptv3/example_code/cross-services/ddb-item-tracker/public/dynamoAppHelperFiles/create-table.js index a17cfcbb17d..2044479310f 100644 --- a/javascriptv3/example_code/cross-services/ddb-item-tracker/public/dynamoAppHelperFiles/create-table.js +++ b/javascriptv3/example_code/cross-services/ddb-item-tracker/public/dynamoAppHelperFiles/create-table.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cross-service-example-dataupload.html. diff --git a/javascriptv3/example_code/cross-services/ddb-item-tracker/public/js/items.js b/javascriptv3/example_code/cross-services/ddb-item-tracker/public/js/items.js index 6208550a522..76698905aea 100644 --- a/javascriptv3/example_code/cross-services/ddb-item-tracker/public/js/items.js +++ b/javascriptv3/example_code/cross-services/ddb-item-tracker/public/js/items.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cross-service.JavaScript.ddb-item-tracker.items] $(function () { diff --git a/javascriptv3/example_code/cross-services/ddb-item-tracker/public/libs/ddbDocClient.js b/javascriptv3/example_code/cross-services/ddb-item-tracker/public/libs/ddbDocClient.js index 9df0a1cd078..c2ac49f4d7f 100644 --- a/javascriptv3/example_code/cross-services/ddb-item-tracker/public/libs/ddbDocClient.js +++ b/javascriptv3/example_code/cross-services/ddb-item-tracker/public/libs/ddbDocClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/dynamodb-examples.html. diff --git a/javascriptv3/example_code/cross-services/ddb-item-tracker/public/libs/dynamoClient.js b/javascriptv3/example_code/cross-services/ddb-item-tracker/public/libs/dynamoClient.js index 844f5ba1fa2..eb2b82ffcfb 100644 --- a/javascriptv3/example_code/cross-services/ddb-item-tracker/public/libs/dynamoClient.js +++ b/javascriptv3/example_code/cross-services/ddb-item-tracker/public/libs/dynamoClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cross-service-example-dataupload.html. diff --git a/javascriptv3/example_code/cross-services/ddb-item-tracker/public/libs/s3Client.js b/javascriptv3/example_code/cross-services/ddb-item-tracker/public/libs/s3Client.js index 0875c9d90b9..d9b603b9faf 100644 --- a/javascriptv3/example_code/cross-services/ddb-item-tracker/public/libs/s3Client.js +++ b/javascriptv3/example_code/cross-services/ddb-item-tracker/public/libs/s3Client.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cross-service-example-dataupload.html. diff --git a/javascriptv3/example_code/cross-services/ddb-item-tracker/public/libs/sesClient.js b/javascriptv3/example_code/cross-services/ddb-item-tracker/public/libs/sesClient.js index 6a2b5cd903a..fe00f3a1317 100644 --- a/javascriptv3/example_code/cross-services/ddb-item-tracker/public/libs/sesClient.js +++ b/javascriptv3/example_code/cross-services/ddb-item-tracker/public/libs/sesClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cross-service-example-dataupload.html. diff --git a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/AnalyzeSentiment/rollup.config.js b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/AnalyzeSentiment/rollup.config.js index 140ce032682..7eaa025408d 100644 --- a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/AnalyzeSentiment/rollup.config.js +++ b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/AnalyzeSentiment/rollup.config.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { nodeResolve } from "@rollup/plugin-node-resolve"; import commonjs from "@rollup/plugin-commonjs"; diff --git a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/AnalyzeSentiment/src/index.js b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/AnalyzeSentiment/src/index.js index ec04ac946fc..978a3438338 100644 --- a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/AnalyzeSentiment/src/index.js +++ b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/AnalyzeSentiment/src/index.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.sample.fsa.analyze_sentiment] import { diff --git a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/AnalyzeSentiment/tests/analyze-sentiment-handler.unit.test.js b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/AnalyzeSentiment/tests/analyze-sentiment-handler.unit.test.js index 99d436501ea..9c24bfa5828 100644 --- a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/AnalyzeSentiment/tests/analyze-sentiment-handler.unit.test.js +++ b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/AnalyzeSentiment/tests/analyze-sentiment-handler.unit.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; const send = vi.fn(() => Promise.resolve()); diff --git a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/ExtractText/rollup.config.js b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/ExtractText/rollup.config.js index 140ce032682..7eaa025408d 100644 --- a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/ExtractText/rollup.config.js +++ b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/ExtractText/rollup.config.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { nodeResolve } from "@rollup/plugin-node-resolve"; import commonjs from "@rollup/plugin-commonjs"; diff --git a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/ExtractText/src/index.js b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/ExtractText/src/index.js index d94ac7ec4d9..96f5892e83a 100644 --- a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/ExtractText/src/index.js +++ b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/ExtractText/src/index.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.sample.fsa.extract_text] import { diff --git a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/ExtractText/tests/extract-text-handler.unit.test.js b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/ExtractText/tests/extract-text-handler.unit.test.js index b8d061a7488..95c8084b0c9 100644 --- a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/ExtractText/tests/extract-text-handler.unit.test.js +++ b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/ExtractText/tests/extract-text-handler.unit.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; const send = vi.fn(() => Promise.resolve()); diff --git a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/SynthesizeAudio/rollup.config.js b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/SynthesizeAudio/rollup.config.js index 140ce032682..7eaa025408d 100644 --- a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/SynthesizeAudio/rollup.config.js +++ b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/SynthesizeAudio/rollup.config.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { nodeResolve } from "@rollup/plugin-node-resolve"; import commonjs from "@rollup/plugin-commonjs"; diff --git a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/SynthesizeAudio/src/index.js b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/SynthesizeAudio/src/index.js index a74cf23bea9..c9f4e2654d4 100644 --- a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/SynthesizeAudio/src/index.js +++ b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/SynthesizeAudio/src/index.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.sample.fsa.synthesize_audio] import { PollyClient, SynthesizeSpeechCommand } from "@aws-sdk/client-polly"; diff --git a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/SynthesizeAudio/tests/synthesize-audio-handler.unit.test.js b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/SynthesizeAudio/tests/synthesize-audio-handler.unit.test.js index b41eb881374..5a910e3a312 100644 --- a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/SynthesizeAudio/tests/synthesize-audio-handler.unit.test.js +++ b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/SynthesizeAudio/tests/synthesize-audio-handler.unit.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; const send = vi.fn(() => Promise.resolve()); diff --git a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/TranslateText/rollup.config.js b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/TranslateText/rollup.config.js index 140ce032682..7eaa025408d 100644 --- a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/TranslateText/rollup.config.js +++ b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/TranslateText/rollup.config.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { nodeResolve } from "@rollup/plugin-node-resolve"; import commonjs from "@rollup/plugin-commonjs"; diff --git a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/TranslateText/src/index.js b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/TranslateText/src/index.js index de7ed0551b2..4e38282fa4a 100644 --- a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/TranslateText/src/index.js +++ b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/TranslateText/src/index.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.sample.fsa.translate_text] import { diff --git a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/TranslateText/tests/translate-text-handler.unit.test.js b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/TranslateText/tests/translate-text-handler.unit.test.js index ab777bc2771..e4bd8d63b5f 100644 --- a/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/TranslateText/tests/translate-text-handler.unit.test.js +++ b/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer/TranslateText/tests/translate-text-handler.unit.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; const send = vi.fn(() => Promise.resolve()); diff --git a/javascriptv3/example_code/cross-services/lambda-api-gateway/src/helper-functions/lambda-function-setup.js b/javascriptv3/example_code/cross-services/lambda-api-gateway/src/helper-functions/lambda-function-setup.js index 6a08a82079c..52bc3c865e8 100644 --- a/javascriptv3/example_code/cross-services/lambda-api-gateway/src/helper-functions/lambda-function-setup.js +++ b/javascriptv3/example_code/cross-services/lambda-api-gateway/src/helper-functions/lambda-function-setup.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cross-service-example-scan-and-publish-message.html. diff --git a/javascriptv3/example_code/cross-services/lambda-api-gateway/src/helper-functions/populate-table.js b/javascriptv3/example_code/cross-services/lambda-api-gateway/src/helper-functions/populate-table.js index 2e74b102000..ce64a33652a 100644 --- a/javascriptv3/example_code/cross-services/lambda-api-gateway/src/helper-functions/populate-table.js +++ b/javascriptv3/example_code/cross-services/lambda-api-gateway/src/helper-functions/populate-table.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cross-service-example-scan-and-publish-message.html. diff --git a/javascriptv3/example_code/cross-services/lambda-api-gateway/src/libs/dynamoClient.js b/javascriptv3/example_code/cross-services/lambda-api-gateway/src/libs/dynamoClient.js index edd0cd7739e..ad949e49859 100644 --- a/javascriptv3/example_code/cross-services/lambda-api-gateway/src/libs/dynamoClient.js +++ b/javascriptv3/example_code/cross-services/lambda-api-gateway/src/libs/dynamoClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/api-gateway-invoking-lambda-example.html. diff --git a/javascriptv3/example_code/cross-services/lambda-api-gateway/src/libs/lambdaClient.js b/javascriptv3/example_code/cross-services/lambda-api-gateway/src/libs/lambdaClient.js index c3a948f78fe..8fc92ce0092 100644 --- a/javascriptv3/example_code/cross-services/lambda-api-gateway/src/libs/lambdaClient.js +++ b/javascriptv3/example_code/cross-services/lambda-api-gateway/src/libs/lambdaClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/api-gateway-invoking-lambda-example.html. diff --git a/javascriptv3/example_code/cross-services/lambda-api-gateway/src/libs/snsClient.js b/javascriptv3/example_code/cross-services/lambda-api-gateway/src/libs/snsClient.js index 5433a147f4d..c448a4e9619 100644 --- a/javascriptv3/example_code/cross-services/lambda-api-gateway/src/libs/snsClient.js +++ b/javascriptv3/example_code/cross-services/lambda-api-gateway/src/libs/snsClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/api-gateway-invoking-lambda-example.html. diff --git a/javascriptv3/example_code/cross-services/lambda-api-gateway/src/mylamdbafunction.js b/javascriptv3/example_code/cross-services/lambda-api-gateway/src/mylamdbafunction.js index eb9e14b385f..5a1ded4f52c 100644 --- a/javascriptv3/example_code/cross-services/lambda-api-gateway/src/mylamdbafunction.js +++ b/javascriptv3/example_code/cross-services/lambda-api-gateway/src/mylamdbafunction.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cross-service-example-scan-and-publish-message.html. diff --git a/javascriptv3/example_code/cross-services/lambda-for-browser/frontend/src/index.js b/javascriptv3/example_code/cross-services/lambda-for-browser/frontend/src/index.js index aff67631173..0d6d94f9dec 100644 --- a/javascriptv3/example_code/cross-services/lambda-for-browser/frontend/src/index.js +++ b/javascriptv3/example_code/cross-services/lambda-for-browser/frontend/src/index.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/cross-services/lambda-for-browser/frontend/src/lambdaClient.js b/javascriptv3/example_code/cross-services/lambda-for-browser/frontend/src/lambdaClient.js index 908a95820be..de7e3015b34 100644 --- a/javascriptv3/example_code/cross-services/lambda-for-browser/frontend/src/lambdaClient.js +++ b/javascriptv3/example_code/cross-services/lambda-for-browser/frontend/src/lambdaClient.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cross-service.lambda-from-browser.JavaScript.lambdaClient] import { LambdaClient } from "@aws-sdk/client-lambda"; diff --git a/javascriptv3/example_code/cross-services/lambda-for-browser/frontend/webpack.config.js b/javascriptv3/example_code/cross-services/lambda-for-browser/frontend/webpack.config.js index 030e1c8fa23..1990dca0adf 100644 --- a/javascriptv3/example_code/cross-services/lambda-for-browser/frontend/webpack.config.js +++ b/javascriptv3/example_code/cross-services/lambda-for-browser/frontend/webpack.config.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 const config = { mode: "production", }; diff --git a/javascriptv3/example_code/cross-services/lambda-for-browser/lambda/src/ddbClient.js b/javascriptv3/example_code/cross-services/lambda-for-browser/lambda/src/ddbClient.js index 96ff72efc81..5fb794aa463 100644 --- a/javascriptv3/example_code/cross-services/lambda-for-browser/lambda/src/ddbClient.js +++ b/javascriptv3/example_code/cross-services/lambda-for-browser/lambda/src/ddbClient.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cross-service.lambda-from-browser.JavaScript.ddbclient] import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; diff --git a/javascriptv3/example_code/cross-services/lambda-for-browser/lambda/src/ddbDocClient.js b/javascriptv3/example_code/cross-services/lambda-for-browser/lambda/src/ddbDocClient.js index 234765f8eb8..440ed2c8b8e 100644 --- a/javascriptv3/example_code/cross-services/lambda-for-browser/lambda/src/ddbDocClient.js +++ b/javascriptv3/example_code/cross-services/lambda-for-browser/lambda/src/ddbDocClient.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cross-service.lambda-from-browser.JavaScript.ddbDocClient] import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; diff --git a/javascriptv3/example_code/cross-services/lambda-for-browser/lambda/src/index.js b/javascriptv3/example_code/cross-services/lambda-for-browser/lambda/src/index.js index df5a7a42149..8b0a06d8831 100644 --- a/javascriptv3/example_code/cross-services/lambda-for-browser/lambda/src/index.js +++ b/javascriptv3/example_code/cross-services/lambda-for-browser/lambda/src/index.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[cross-service.lambda-from-browser.javascriptv3.lambda] import { PutCommand } from "@aws-sdk/lib-dynamodb"; diff --git a/javascriptv3/example_code/cross-services/lambda-for-browser/lambda/webpack.config.js b/javascriptv3/example_code/cross-services/lambda-for-browser/lambda/webpack.config.js index 83c360cede6..4c07c4c52c6 100644 --- a/javascriptv3/example_code/cross-services/lambda-for-browser/lambda/webpack.config.js +++ b/javascriptv3/example_code/cross-services/lambda-for-browser/lambda/webpack.config.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 const config = { externalsType: "module", mode: "production", diff --git a/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/helper-functions/lambda-function-setup.js b/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/helper-functions/lambda-function-setup.js index 0847f11c0c6..30526b1ac20 100644 --- a/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/helper-functions/lambda-function-setup.js +++ b/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/helper-functions/lambda-function-setup.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/invoke-lambda-functions-with-scheduled-events.html. diff --git a/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/helper-functions/populate-table.js b/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/helper-functions/populate-table.js index 1ac12a5f63b..28dfb85536d 100644 --- a/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/helper-functions/populate-table.js +++ b/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/helper-functions/populate-table.js @@ -1,7 +1,7 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 - +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/invoke-lambda-functions-with-scheduled-events.html. diff --git a/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/libs/dynamoClient.js b/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/libs/dynamoClient.js index 0e7f0de2128..3126bb4d9c3 100644 --- a/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/libs/dynamoClient.js +++ b/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/libs/dynamoClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/api-gateway-invoking-lambda-example.html. diff --git a/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/libs/lambdaClient.js b/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/libs/lambdaClient.js index 3d7c2c3d61d..d54088adc99 100644 --- a/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/libs/lambdaClient.js +++ b/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/libs/lambdaClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/api-gateway-invoking-lambda-example.html. diff --git a/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/libs/snsClient.js b/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/libs/snsClient.js index 50f9bc7d5b0..964a74cdc65 100644 --- a/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/libs/snsClient.js +++ b/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/libs/snsClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/api-gateway-invoking-lambda-example.html. diff --git a/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/mylamdbafunction.js b/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/mylamdbafunction.js index 90fde96e52b..271e4148b52 100644 --- a/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/mylamdbafunction.js +++ b/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/mylamdbafunction.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/invoke-lambda-functions-with-scheduled-events.html. diff --git a/javascriptv3/example_code/cross-services/lambda-step-functions/src/lambda1/getid.js b/javascriptv3/example_code/cross-services/lambda-step-functions/src/lambda1/getid.js index e205db9a0d1..4d431497495 100644 --- a/javascriptv3/example_code/cross-services/lambda-step-functions/src/lambda1/getid.js +++ b/javascriptv3/example_code/cross-services/lambda-step-functions/src/lambda1/getid.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/serverless-workflows-using-step-functions.html. diff --git a/javascriptv3/example_code/cross-services/lambda-step-functions/src/lambda2/additem.js b/javascriptv3/example_code/cross-services/lambda-step-functions/src/lambda2/additem.js index 26951263a4b..d5267e6e6dd 100644 --- a/javascriptv3/example_code/cross-services/lambda-step-functions/src/lambda2/additem.js +++ b/javascriptv3/example_code/cross-services/lambda-step-functions/src/lambda2/additem.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/serverless-workflows-using-step-functions.html. diff --git a/javascriptv3/example_code/cross-services/lambda-step-functions/src/lambda3/sendemail.js b/javascriptv3/example_code/cross-services/lambda-step-functions/src/lambda3/sendemail.js index c2907e98052..62aa3c2e1c4 100644 --- a/javascriptv3/example_code/cross-services/lambda-step-functions/src/lambda3/sendemail.js +++ b/javascriptv3/example_code/cross-services/lambda-step-functions/src/lambda3/sendemail.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/serverless-workflows-using-step-functions.html. diff --git a/javascriptv3/example_code/cross-services/lambda-step-functions/src/libs/dynamoClient.js b/javascriptv3/example_code/cross-services/lambda-step-functions/src/libs/dynamoClient.js index 9810fdb5ecd..bba165579ce 100644 --- a/javascriptv3/example_code/cross-services/lambda-step-functions/src/libs/dynamoClient.js +++ b/javascriptv3/example_code/cross-services/lambda-step-functions/src/libs/dynamoClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/serverless-step-functions-example.html. diff --git a/javascriptv3/example_code/cross-services/lambda-step-functions/src/libs/sesClient.js b/javascriptv3/example_code/cross-services/lambda-step-functions/src/libs/sesClient.js index cfe295b5088..cfc7f5d4db2 100644 --- a/javascriptv3/example_code/cross-services/lambda-step-functions/src/libs/sesClient.js +++ b/javascriptv3/example_code/cross-services/lambda-step-functions/src/libs/sesClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/serverless-step-functions-example.html. diff --git a/javascriptv3/example_code/cross-services/lex-bot/src/index.js b/javascriptv3/example_code/cross-services/lex-bot/src/index.js index cd192f6239b..03d03d6a4df 100644 --- a/javascriptv3/example_code/cross-services/lex-bot/src/index.js +++ b/javascriptv3/example_code/cross-services/lex-bot/src/index.js @@ -1,6 +1,7 @@ -/*Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/lex-bot-example.html. diff --git a/javascriptv3/example_code/cross-services/lex-bot/src/libs/comprehendClient.js b/javascriptv3/example_code/cross-services/lex-bot/src/libs/comprehendClient.js index 075b4469b11..182547c93d3 100644 --- a/javascriptv3/example_code/cross-services/lex-bot/src/libs/comprehendClient.js +++ b/javascriptv3/example_code/cross-services/lex-bot/src/libs/comprehendClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. The example is available here https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/lex-bot-example.html. diff --git a/javascriptv3/example_code/cross-services/lex-bot/src/libs/lexClient.js b/javascriptv3/example_code/cross-services/lex-bot/src/libs/lexClient.js index 3899c9e93a2..65aee0097e5 100644 --- a/javascriptv3/example_code/cross-services/lex-bot/src/libs/lexClient.js +++ b/javascriptv3/example_code/cross-services/lex-bot/src/libs/lexClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. The example is available here https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/lex-bot-example.html. diff --git a/javascriptv3/example_code/cross-services/lex-bot/src/libs/translateClient.js b/javascriptv3/example_code/cross-services/lex-bot/src/libs/translateClient.js index bec56e52f15..4708bbbd602 100644 --- a/javascriptv3/example_code/cross-services/lex-bot/src/libs/translateClient.js +++ b/javascriptv3/example_code/cross-services/lex-bot/src/libs/translateClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. The example is available here https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/lex-bot-example.html. diff --git a/javascriptv3/example_code/cross-services/lex-bot/src/style.css b/javascriptv3/example_code/cross-services/lex-bot/src/style.css index b3739adf5e1..77c4bcf607b 100644 --- a/javascriptv3/example_code/cross-services/lex-bot/src/style.css +++ b/javascriptv3/example_code/cross-services/lex-bot/src/style.css @@ -1,6 +1,7 @@ -/*Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/lex-bot-example.html. diff --git a/javascriptv3/example_code/cross-services/message-app/js/index.js b/javascriptv3/example_code/cross-services/message-app/js/index.js index e1dd577a8d4..c717c706cdf 100644 --- a/javascriptv3/example_code/cross-services/message-app/js/index.js +++ b/javascriptv3/example_code/cross-services/message-app/js/index.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/messaging-app.html. diff --git a/javascriptv3/example_code/cross-services/message-app/js/libs/sqsClient.js b/javascriptv3/example_code/cross-services/message-app/js/libs/sqsClient.js index 217b9533b74..9833d9b6fdf 100644 --- a/javascriptv3/example_code/cross-services/message-app/js/libs/sqsClient.js +++ b/javascriptv3/example_code/cross-services/message-app/js/libs/sqsClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. The example is available here https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/messaging-app.html. diff --git a/javascriptv3/example_code/cross-services/photo-analyzer-ppe/helper_functions/js/upload-objects.js b/javascriptv3/example_code/cross-services/photo-analyzer-ppe/helper_functions/js/upload-objects.js index 25556c284e6..fb578ed4bc4 100644 --- a/javascriptv3/example_code/cross-services/photo-analyzer-ppe/helper_functions/js/upload-objects.js +++ b/javascriptv3/example_code/cross-services/photo-analyzer-ppe/helper_functions/js/upload-objects.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/cross-services/photo-analyzer-ppe/js/index.js b/javascriptv3/example_code/cross-services/photo-analyzer-ppe/js/index.js index 2f61b07632d..4b1f7510f0b 100644 --- a/javascriptv3/example_code/cross-services/photo-analyzer-ppe/js/index.js +++ b/javascriptv3/example_code/cross-services/photo-analyzer-ppe/js/index.js @@ -1,6 +1,7 @@ -/*Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/cross-services/photo-analyzer-ppe/libs/dynamoDBClient.js b/javascriptv3/example_code/cross-services/photo-analyzer-ppe/libs/dynamoDBClient.js index c3299580247..74464fe5424 100644 --- a/javascriptv3/example_code/cross-services/photo-analyzer-ppe/libs/dynamoDBClient.js +++ b/javascriptv3/example_code/cross-services/photo-analyzer-ppe/libs/dynamoDBClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/cross-services/photo-analyzer-ppe/libs/rekognitionClient.js b/javascriptv3/example_code/cross-services/photo-analyzer-ppe/libs/rekognitionClient.js index a3b4e1bde0b..743156cdd87 100644 --- a/javascriptv3/example_code/cross-services/photo-analyzer-ppe/libs/rekognitionClient.js +++ b/javascriptv3/example_code/cross-services/photo-analyzer-ppe/libs/rekognitionClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/cross-services/photo-analyzer-ppe/libs/s3Client.js b/javascriptv3/example_code/cross-services/photo-analyzer-ppe/libs/s3Client.js index 3eaed64616e..98dcd8374f4 100644 --- a/javascriptv3/example_code/cross-services/photo-analyzer-ppe/libs/s3Client.js +++ b/javascriptv3/example_code/cross-services/photo-analyzer-ppe/libs/s3Client.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/cross-services/photo-analyzer-ppe/libs/sesClient.js b/javascriptv3/example_code/cross-services/photo-analyzer-ppe/libs/sesClient.js index eed498d0c87..e4ee0ca6db9 100644 --- a/javascriptv3/example_code/cross-services/photo-analyzer-ppe/libs/sesClient.js +++ b/javascriptv3/example_code/cross-services/photo-analyzer-ppe/libs/sesClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/cross-services/photo-asset-manager/rollup.config.js b/javascriptv3/example_code/cross-services/photo-asset-manager/rollup.config.js index 140ce032682..7eaa025408d 100644 --- a/javascriptv3/example_code/cross-services/photo-asset-manager/rollup.config.js +++ b/javascriptv3/example_code/cross-services/photo-asset-manager/rollup.config.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { nodeResolve } from "@rollup/plugin-node-resolve"; import commonjs from "@rollup/plugin-commonjs"; diff --git a/javascriptv3/example_code/cross-services/photo-asset-manager/src/common.js b/javascriptv3/example_code/cross-services/photo-asset-manager/src/common.js index f4b01b56ee5..45277b5de74 100644 --- a/javascriptv3/example_code/cross-services/photo-asset-manager/src/common.js +++ b/javascriptv3/example_code/cross-services/photo-asset-manager/src/common.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { S3Client, diff --git a/javascriptv3/example_code/cross-services/photo-asset-manager/src/functions/detect-labels.js b/javascriptv3/example_code/cross-services/photo-asset-manager/src/functions/detect-labels.js index 5b5faaa06f9..69a28504f04 100644 --- a/javascriptv3/example_code/cross-services/photo-asset-manager/src/functions/detect-labels.js +++ b/javascriptv3/example_code/cross-services/photo-asset-manager/src/functions/detect-labels.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { RekognitionClient, diff --git a/javascriptv3/example_code/cross-services/photo-asset-manager/src/functions/download.js b/javascriptv3/example_code/cross-services/photo-asset-manager/src/functions/download.js index 48d1ba58076..4b80c303bfe 100644 --- a/javascriptv3/example_code/cross-services/photo-asset-manager/src/functions/download.js +++ b/javascriptv3/example_code/cross-services/photo-asset-manager/src/functions/download.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3"; import { Upload } from "@aws-sdk/lib-storage"; import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; diff --git a/javascriptv3/example_code/cross-services/photo-asset-manager/src/functions/labels.js b/javascriptv3/example_code/cross-services/photo-asset-manager/src/functions/labels.js index 66a48e52c88..c82eafd3782 100644 --- a/javascriptv3/example_code/cross-services/photo-asset-manager/src/functions/labels.js +++ b/javascriptv3/example_code/cross-services/photo-asset-manager/src/functions/labels.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, paginateScan } from "@aws-sdk/lib-dynamodb"; diff --git a/javascriptv3/example_code/cross-services/photo-asset-manager/src/functions/upload.js b/javascriptv3/example_code/cross-services/photo-asset-manager/src/functions/upload.js index ec305995339..36860e66fad 100644 --- a/javascriptv3/example_code/cross-services/photo-asset-manager/src/functions/upload.js +++ b/javascriptv3/example_code/cross-services/photo-asset-manager/src/functions/upload.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { randomUUID } from "node:crypto"; import { diff --git a/javascriptv3/example_code/cross-services/photo-asset-manager/src/index.js b/javascriptv3/example_code/cross-services/photo-asset-manager/src/index.js index 58683131046..876dae1317c 100644 --- a/javascriptv3/example_code/cross-services/photo-asset-manager/src/index.js +++ b/javascriptv3/example_code/cross-services/photo-asset-manager/src/index.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { handler as upload } from "./functions/upload.js"; import { handler as detectLabels } from "./functions/detect-labels.js"; diff --git a/javascriptv3/example_code/cross-services/photo-asset-manager/src/lambda-env.js b/javascriptv3/example_code/cross-services/photo-asset-manager/src/lambda-env.js index 4d8b9aaa375..49e9e69a161 100644 --- a/javascriptv3/example_code/cross-services/photo-asset-manager/src/lambda-env.js +++ b/javascriptv3/example_code/cross-services/photo-asset-manager/src/lambda-env.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * These variables are created by the CDK deployment. diff --git a/javascriptv3/example_code/cross-services/photo-asset-manager/tests/detect-labels-handler.unit.test.js b/javascriptv3/example_code/cross-services/photo-asset-manager/tests/detect-labels-handler.unit.test.js index c58da295a22..9afa3a3a1c3 100644 --- a/javascriptv3/example_code/cross-services/photo-asset-manager/tests/detect-labels-handler.unit.test.js +++ b/javascriptv3/example_code/cross-services/photo-asset-manager/tests/detect-labels-handler.unit.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { getHandler } from "../src/functions/detect-labels.js"; diff --git a/javascriptv3/example_code/cross-services/photo-asset-manager/tests/download.unit.test.js b/javascriptv3/example_code/cross-services/photo-asset-manager/tests/download.unit.test.js index e6d0675d880..d7f38cf5fa8 100644 --- a/javascriptv3/example_code/cross-services/photo-asset-manager/tests/download.unit.test.js +++ b/javascriptv3/example_code/cross-services/photo-asset-manager/tests/download.unit.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; import { describe, beforeEach, afterEach, it, expect, vi } from "vitest"; import { getImageKeysForLabels } from "../src/functions/download.js"; diff --git a/javascriptv3/example_code/cross-services/photo-asset-manager/tests/labels.unit.test.js b/javascriptv3/example_code/cross-services/photo-asset-manager/tests/labels.unit.test.js index 9d055838667..663031a07c4 100644 --- a/javascriptv3/example_code/cross-services/photo-asset-manager/tests/labels.unit.test.js +++ b/javascriptv3/example_code/cross-services/photo-asset-manager/tests/labels.unit.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { getHandler, labelsReducer } from "../src/functions/labels.js"; diff --git a/javascriptv3/example_code/cross-services/photo-asset-manager/tests/upload-handler.unit.test.js b/javascriptv3/example_code/cross-services/photo-asset-manager/tests/upload-handler.unit.test.js index 71889500caa..c5b9db4a7f5 100644 --- a/javascriptv3/example_code/cross-services/photo-asset-manager/tests/upload-handler.unit.test.js +++ b/javascriptv3/example_code/cross-services/photo-asset-manager/tests/upload-handler.unit.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; const { RESPONSE_HEADERS } = await import("../src/common.js"); diff --git a/javascriptv3/example_code/cross-services/photo_analyzer/js/index.js b/javascriptv3/example_code/cross-services/photo_analyzer/js/index.js index c039bd0f0b1..2531719b452 100644 --- a/javascriptv3/example_code/cross-services/photo_analyzer/js/index.js +++ b/javascriptv3/example_code/cross-services/photo_analyzer/js/index.js @@ -1,6 +1,7 @@ -/*Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/cross-services/photo_analyzer/libs/rekognitionClient.js b/javascriptv3/example_code/cross-services/photo_analyzer/libs/rekognitionClient.js index e3a09cfd65c..821d164602e 100644 --- a/javascriptv3/example_code/cross-services/photo_analyzer/libs/rekognitionClient.js +++ b/javascriptv3/example_code/cross-services/photo_analyzer/libs/rekognitionClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/cross-services/photo_analyzer/libs/s3Client.js b/javascriptv3/example_code/cross-services/photo_analyzer/libs/s3Client.js index aa508da8705..bd41fce0a34 100644 --- a/javascriptv3/example_code/cross-services/photo_analyzer/libs/s3Client.js +++ b/javascriptv3/example_code/cross-services/photo_analyzer/libs/s3Client.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/cross-services/photo_analyzer/libs/sesClient.js b/javascriptv3/example_code/cross-services/photo_analyzer/libs/sesClient.js index 462b58ac0e6..94d7fe06b9f 100644 --- a/javascriptv3/example_code/cross-services/photo_analyzer/libs/sesClient.js +++ b/javascriptv3/example_code/cross-services/photo_analyzer/libs/sesClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/cross-services/sns-sample-app/js/index.js b/javascriptv3/example_code/cross-services/sns-sample-app/js/index.js index 601c6901b40..16f4db2a953 100644 --- a/javascriptv3/example_code/cross-services/sns-sample-app/js/index.js +++ b/javascriptv3/example_code/cross-services/sns-sample-app/js/index.js @@ -1,6 +1,7 @@ -/*Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/cross-services/sns-sample-app/libs/snsClient.js b/javascriptv3/example_code/cross-services/sns-sample-app/libs/snsClient.js index 97801882719..f226ad51900 100644 --- a/javascriptv3/example_code/cross-services/sns-sample-app/libs/snsClient.js +++ b/javascriptv3/example_code/cross-services/sns-sample-app/libs/snsClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/cross-services/submit-data-app/src/dynamoApp/add_data.js b/javascriptv3/example_code/cross-services/submit-data-app/src/dynamoApp/add_data.js index 8b85d6f4d85..8652eb76a51 100644 --- a/javascriptv3/example_code/cross-services/submit-data-app/src/dynamoApp/add_data.js +++ b/javascriptv3/example_code/cross-services/submit-data-app/src/dynamoApp/add_data.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cross-service-example-dataupload.html. diff --git a/javascriptv3/example_code/cross-services/submit-data-app/src/dynamoAppHelperFiles/update-table.js b/javascriptv3/example_code/cross-services/submit-data-app/src/dynamoAppHelperFiles/update-table.js index e48d37e1ae0..75492915110 100644 --- a/javascriptv3/example_code/cross-services/submit-data-app/src/dynamoAppHelperFiles/update-table.js +++ b/javascriptv3/example_code/cross-services/submit-data-app/src/dynamoAppHelperFiles/update-table.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cross-service-example-dataupload.html. diff --git a/javascriptv3/example_code/cross-services/submit-data-app/src/libs/dynamoClient.js b/javascriptv3/example_code/cross-services/submit-data-app/src/libs/dynamoClient.js index 94e9e8c3617..43ca4f5a099 100644 --- a/javascriptv3/example_code/cross-services/submit-data-app/src/libs/dynamoClient.js +++ b/javascriptv3/example_code/cross-services/submit-data-app/src/libs/dynamoClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cross-service-example-dataupload.html. diff --git a/javascriptv3/example_code/cross-services/submit-data-app/src/libs/snsClient.js b/javascriptv3/example_code/cross-services/submit-data-app/src/libs/snsClient.js index d4106ba74e5..5a7fcb2227b 100644 --- a/javascriptv3/example_code/cross-services/submit-data-app/src/libs/snsClient.js +++ b/javascriptv3/example_code/cross-services/submit-data-app/src/libs/snsClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cross-service-example-dataupload.html. diff --git a/javascriptv3/example_code/cross-services/textract-react/src/Config.js b/javascriptv3/example_code/cross-services/textract-react/src/Config.js index 154926a399a..a618e28ced2 100644 --- a/javascriptv3/example_code/cross-services/textract-react/src/Config.js +++ b/javascriptv3/example_code/cross-services/textract-react/src/Config.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 export const Config = { ConfigError: "Demo resources not initialized. You must deploy AWS resources and demo elements before running this application. See the README for details.", diff --git a/javascriptv3/example_code/cross-services/transcribe-streaming-app/src/index.js b/javascriptv3/example_code/cross-services/transcribe-streaming-app/src/index.js index 33a6bd00a00..fd741fd849d 100644 --- a/javascriptv3/example_code/cross-services/transcribe-streaming-app/src/index.js +++ b/javascriptv3/example_code/cross-services/transcribe-streaming-app/src/index.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/cross-services/transcribe-streaming-app/src/libs/awsID.js b/javascriptv3/example_code/cross-services/transcribe-streaming-app/src/libs/awsID.js index 863f5b183e0..a893f608ef9 100644 --- a/javascriptv3/example_code/cross-services/transcribe-streaming-app/src/libs/awsID.js +++ b/javascriptv3/example_code/cross-services/transcribe-streaming-app/src/libs/awsID.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/cross-services/transcribe-streaming-app/src/libs/emailClient.js b/javascriptv3/example_code/cross-services/transcribe-streaming-app/src/libs/emailClient.js index 48623dabff7..5d7e5386aaa 100644 --- a/javascriptv3/example_code/cross-services/transcribe-streaming-app/src/libs/emailClient.js +++ b/javascriptv3/example_code/cross-services/transcribe-streaming-app/src/libs/emailClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/cross-services/transcribe-streaming-app/src/libs/transcribeClient.js b/javascriptv3/example_code/cross-services/transcribe-streaming-app/src/libs/transcribeClient.js index fabaa207fcb..16ca2b461dc 100644 --- a/javascriptv3/example_code/cross-services/transcribe-streaming-app/src/libs/transcribeClient.js +++ b/javascriptv3/example_code/cross-services/transcribe-streaming-app/src/libs/transcribeClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/cross-services/transcribe-streaming-app/src/libs/translateClient.js b/javascriptv3/example_code/cross-services/transcribe-streaming-app/src/libs/translateClient.js index 67a43d0879c..f68c2381490 100644 --- a/javascriptv3/example_code/cross-services/transcribe-streaming-app/src/libs/translateClient.js +++ b/javascriptv3/example_code/cross-services/transcribe-streaming-app/src/libs/translateClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/cross-services/transcription-app/src/helper.js b/javascriptv3/example_code/cross-services/transcription-app/src/helper.js index a9c8dacb5c6..f9ddd5a7eeb 100644 --- a/javascriptv3/example_code/cross-services/transcription-app/src/helper.js +++ b/javascriptv3/example_code/cross-services/transcription-app/src/helper.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/transcribe-app.html. diff --git a/javascriptv3/example_code/cross-services/transcription-app/src/index.js b/javascriptv3/example_code/cross-services/transcription-app/src/index.js index 78902dc8033..e16bb76f2c5 100644 --- a/javascriptv3/example_code/cross-services/transcription-app/src/index.js +++ b/javascriptv3/example_code/cross-services/transcription-app/src/index.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/transcribe-app.html. diff --git a/javascriptv3/example_code/cross-services/transcription-app/src/recorder.js b/javascriptv3/example_code/cross-services/transcription-app/src/recorder.js index 99bc5762efb..51bb79841dc 100644 --- a/javascriptv3/example_code/cross-services/transcription-app/src/recorder.js +++ b/javascriptv3/example_code/cross-services/transcription-app/src/recorder.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/transcribe-app.html. diff --git a/javascriptv3/example_code/cross-services/video-analyzer/src/js/index.js b/javascriptv3/example_code/cross-services/video-analyzer/src/js/index.js index 3bc24f6bac1..1b869c36467 100644 --- a/javascriptv3/example_code/cross-services/video-analyzer/src/js/index.js +++ b/javascriptv3/example_code/cross-services/video-analyzer/src/js/index.js @@ -1,6 +1,7 @@ -/*Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/cross-services/video-analyzer/src/libs/rekognitionClient.js b/javascriptv3/example_code/cross-services/video-analyzer/src/libs/rekognitionClient.js index ac6d346ea7b..1bdda5bc7bf 100644 --- a/javascriptv3/example_code/cross-services/video-analyzer/src/libs/rekognitionClient.js +++ b/javascriptv3/example_code/cross-services/video-analyzer/src/libs/rekognitionClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/video-analyzer.html. diff --git a/javascriptv3/example_code/cross-services/video-analyzer/src/libs/s3Client.js b/javascriptv3/example_code/cross-services/video-analyzer/src/libs/s3Client.js index 2d02e753c1d..710ab48bb31 100644 --- a/javascriptv3/example_code/cross-services/video-analyzer/src/libs/s3Client.js +++ b/javascriptv3/example_code/cross-services/video-analyzer/src/libs/s3Client.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/video-analyzer.html. diff --git a/javascriptv3/example_code/cross-services/video-analyzer/src/libs/sesClient.js b/javascriptv3/example_code/cross-services/video-analyzer/src/libs/sesClient.js index 705f140be25..f23b5eb986a 100644 --- a/javascriptv3/example_code/cross-services/video-analyzer/src/libs/sesClient.js +++ b/javascriptv3/example_code/cross-services/video-analyzer/src/libs/sesClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/video-analyzer.html. diff --git a/javascriptv3/example_code/cross-services/wkflw-resilient-service/constants.js b/javascriptv3/example_code/cross-services/wkflw-resilient-service/constants.js index 444b8db29b8..d7b1004738b 100644 --- a/javascriptv3/example_code/cross-services/wkflw-resilient-service/constants.js +++ b/javascriptv3/example_code/cross-services/wkflw-resilient-service/constants.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { resolve, join } from "node:path"; diff --git a/javascriptv3/example_code/cross-services/wkflw-resilient-service/index.js b/javascriptv3/example_code/cross-services/wkflw-resilient-service/index.js index c7246b2ba14..b4656190936 100755 --- a/javascriptv3/example_code/cross-services/wkflw-resilient-service/index.js +++ b/javascriptv3/example_code/cross-services/wkflw-resilient-service/index.js @@ -1,9 +1,9 @@ #!/usr/bin/env node +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { Scenario, diff --git a/javascriptv3/example_code/cross-services/wkflw-resilient-service/shared.js b/javascriptv3/example_code/cross-services/wkflw-resilient-service/shared.js index a8b08431b51..fa6f81822e2 100644 --- a/javascriptv3/example_code/cross-services/wkflw-resilient-service/shared.js +++ b/javascriptv3/example_code/cross-services/wkflw-resilient-service/shared.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { ElasticLoadBalancingV2Client, diff --git a/javascriptv3/example_code/cross-services/wkflw-resilient-service/steps-demo.js b/javascriptv3/example_code/cross-services/wkflw-resilient-service/steps-demo.js index 78b87e866f5..84a8e229991 100644 --- a/javascriptv3/example_code/cross-services/wkflw-resilient-service/steps-demo.js +++ b/javascriptv3/example_code/cross-services/wkflw-resilient-service/steps-demo.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { readFileSync } from "node:fs"; import { join } from "node:path"; diff --git a/javascriptv3/example_code/cross-services/wkflw-resilient-service/steps-deploy.js b/javascriptv3/example_code/cross-services/wkflw-resilient-service/steps-deploy.js index 0c8d7ee91c6..be10e1388e5 100644 --- a/javascriptv3/example_code/cross-services/wkflw-resilient-service/steps-deploy.js +++ b/javascriptv3/example_code/cross-services/wkflw-resilient-service/steps-deploy.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { join } from "node:path"; import { readFileSync, writeFileSync } from "node:fs"; import axios from "axios"; diff --git a/javascriptv3/example_code/cross-services/wkflw-resilient-service/steps-destroy.js b/javascriptv3/example_code/cross-services/wkflw-resilient-service/steps-destroy.js index 139cda127a6..df9689babdf 100644 --- a/javascriptv3/example_code/cross-services/wkflw-resilient-service/steps-destroy.js +++ b/javascriptv3/example_code/cross-services/wkflw-resilient-service/steps-destroy.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { unlinkSync } from "node:fs"; import { DynamoDBClient, DeleteTableCommand } from "@aws-sdk/client-dynamodb"; diff --git a/javascriptv3/example_code/cross-services/wkflw-resilient-service/steps-reset-params.js b/javascriptv3/example_code/cross-services/wkflw-resilient-service/steps-reset-params.js index b4f8dd957aa..9562a5f08be 100644 --- a/javascriptv3/example_code/cross-services/wkflw-resilient-service/steps-reset-params.js +++ b/javascriptv3/example_code/cross-services/wkflw-resilient-service/steps-reset-params.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { ScenarioAction } from "@aws-sdk-examples/libs/scenario/scenario.js"; import { PutParameterCommand, SSMClient } from "@aws-sdk/client-ssm"; diff --git a/javascriptv3/example_code/cross-services/wkflw-resilient-service/tests/wkflw.integration.test.js b/javascriptv3/example_code/cross-services/wkflw-resilient-service/tests/wkflw.integration.test.js index fe7fe1498f6..b0b41bd2bb5 100644 --- a/javascriptv3/example_code/cross-services/wkflw-resilient-service/tests/wkflw.integration.test.js +++ b/javascriptv3/example_code/cross-services/wkflw-resilient-service/tests/wkflw.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it } from "vitest"; import { scenarios } from "../index.js"; diff --git a/javascriptv3/example_code/cross-services/wkflw-resilient-service/vite.config.js b/javascriptv3/example_code/cross-services/wkflw-resilient-service/vite.config.js index d7805bbf6d2..9e3ef6b4ea7 100644 --- a/javascriptv3/example_code/cross-services/wkflw-resilient-service/vite.config.js +++ b/javascriptv3/example_code/cross-services/wkflw-resilient-service/vite.config.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { defineConfig } from "vitest/config"; const TEST_TIMEOUT_IN_MINUTES = 45; diff --git a/javascriptv3/example_code/cross-services/wkflw-topics-queues/TopicsQueuesWkflw.js b/javascriptv3/example_code/cross-services/wkflw-topics-queues/TopicsQueuesWkflw.js index c6b5e3ec508..550a268d3ac 100644 --- a/javascriptv3/example_code/cross-services/wkflw-topics-queues/TopicsQueuesWkflw.js +++ b/javascriptv3/example_code/cross-services/wkflw-topics-queues/TopicsQueuesWkflw.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { CreateQueueCommand, diff --git a/javascriptv3/example_code/cross-services/wkflw-topics-queues/index.js b/javascriptv3/example_code/cross-services/wkflw-topics-queues/index.js index a81fb369669..68b225ca8f6 100644 --- a/javascriptv3/example_code/cross-services/wkflw-topics-queues/index.js +++ b/javascriptv3/example_code/cross-services/wkflw-topics-queues/index.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/cross-services/wkflw-topics-queues/messages.js b/javascriptv3/example_code/cross-services/wkflw-topics-queues/messages.js index 0855ae95f93..6ec4799b8d0 100644 --- a/javascriptv3/example_code/cross-services/wkflw-topics-queues/messages.js +++ b/javascriptv3/example_code/cross-services/wkflw-topics-queues/messages.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.wkflw.topicsandqueues.messages] export const MESSAGES = { diff --git a/javascriptv3/example_code/cross-services/wkflw-topics-queues/tests/TopicsQueuesWkflw.unit.test.js b/javascriptv3/example_code/cross-services/wkflw-topics-queues/tests/TopicsQueuesWkflw.unit.test.js index 43c74258b04..82422514c3b 100644 --- a/javascriptv3/example_code/cross-services/wkflw-topics-queues/tests/TopicsQueuesWkflw.unit.test.js +++ b/javascriptv3/example_code/cross-services/wkflw-topics-queues/tests/TopicsQueuesWkflw.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi, beforeEach } from "vitest"; import { TopicsQueuesWkflw } from "../TopicsQueuesWkflw.js"; diff --git a/javascriptv3/example_code/dynamodb/actions/batch-get-item.js b/javascriptv3/example_code/dynamodb/actions/batch-get-item.js index 81058e86e9c..a573284cc40 100644 --- a/javascriptv3/example_code/dynamodb/actions/batch-get-item.js +++ b/javascriptv3/example_code/dynamodb/actions/batch-get-item.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/batch-write-item.js b/javascriptv3/example_code/dynamodb/actions/batch-write-item.js index f4308751588..21cfc1d74d3 100644 --- a/javascriptv3/example_code/dynamodb/actions/batch-write-item.js +++ b/javascriptv3/example_code/dynamodb/actions/batch-write-item.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/create-table.js b/javascriptv3/example_code/dynamodb/actions/create-table.js index 2907218c02c..8d0d63cbe00 100644 --- a/javascriptv3/example_code/dynamodb/actions/create-table.js +++ b/javascriptv3/example_code/dynamodb/actions/create-table.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/delete-item.js b/javascriptv3/example_code/dynamodb/actions/delete-item.js index 28dac35d2d3..4f351e02285 100644 --- a/javascriptv3/example_code/dynamodb/actions/delete-item.js +++ b/javascriptv3/example_code/dynamodb/actions/delete-item.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/delete-table.js b/javascriptv3/example_code/dynamodb/actions/delete-table.js index 06a6a65be56..8467866249a 100644 --- a/javascriptv3/example_code/dynamodb/actions/delete-table.js +++ b/javascriptv3/example_code/dynamodb/actions/delete-table.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/describe-table.js b/javascriptv3/example_code/dynamodb/actions/describe-table.js index f674448d2e9..b31bd4624a5 100644 --- a/javascriptv3/example_code/dynamodb/actions/describe-table.js +++ b/javascriptv3/example_code/dynamodb/actions/describe-table.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/document-client/batch-get.js b/javascriptv3/example_code/dynamodb/actions/document-client/batch-get.js index c4f4d9dfbda..722105af62a 100644 --- a/javascriptv3/example_code/dynamodb/actions/document-client/batch-get.js +++ b/javascriptv3/example_code/dynamodb/actions/document-client/batch-get.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/document-client/batch-write.js b/javascriptv3/example_code/dynamodb/actions/document-client/batch-write.js index 763f99c3e82..41206d71f9d 100644 --- a/javascriptv3/example_code/dynamodb/actions/document-client/batch-write.js +++ b/javascriptv3/example_code/dynamodb/actions/document-client/batch-write.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/document-client/delete.js b/javascriptv3/example_code/dynamodb/actions/document-client/delete.js index 4f8c1b37fa6..12377a9ac9c 100644 --- a/javascriptv3/example_code/dynamodb/actions/document-client/delete.js +++ b/javascriptv3/example_code/dynamodb/actions/document-client/delete.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/document-client/get.js b/javascriptv3/example_code/dynamodb/actions/document-client/get.js index d212b06a86f..202b86d593b 100644 --- a/javascriptv3/example_code/dynamodb/actions/document-client/get.js +++ b/javascriptv3/example_code/dynamodb/actions/document-client/get.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/document-client/put.js b/javascriptv3/example_code/dynamodb/actions/document-client/put.js index 74084deae02..b9f86a9c014 100644 --- a/javascriptv3/example_code/dynamodb/actions/document-client/put.js +++ b/javascriptv3/example_code/dynamodb/actions/document-client/put.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/document-client/query.js b/javascriptv3/example_code/dynamodb/actions/document-client/query.js index 0c1eaedc12e..f2e04d4b66d 100644 --- a/javascriptv3/example_code/dynamodb/actions/document-client/query.js +++ b/javascriptv3/example_code/dynamodb/actions/document-client/query.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/document-client/scan.js b/javascriptv3/example_code/dynamodb/actions/document-client/scan.js index 0712b92247b..dae0d2f4546 100644 --- a/javascriptv3/example_code/dynamodb/actions/document-client/scan.js +++ b/javascriptv3/example_code/dynamodb/actions/document-client/scan.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/document-client/update.js b/javascriptv3/example_code/dynamodb/actions/document-client/update.js index 0e2461a9057..5c683fe8352 100644 --- a/javascriptv3/example_code/dynamodb/actions/document-client/update.js +++ b/javascriptv3/example_code/dynamodb/actions/document-client/update.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/get-item.js b/javascriptv3/example_code/dynamodb/actions/get-item.js index df007152bcc..13f4c3a4ca0 100644 --- a/javascriptv3/example_code/dynamodb/actions/get-item.js +++ b/javascriptv3/example_code/dynamodb/actions/get-item.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/list-tables.js b/javascriptv3/example_code/dynamodb/actions/list-tables.js index 1515c748ebb..dc47905807e 100644 --- a/javascriptv3/example_code/dynamodb/actions/list-tables.js +++ b/javascriptv3/example_code/dynamodb/actions/list-tables.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/partiql/partiql-batch-delete.js b/javascriptv3/example_code/dynamodb/actions/partiql/partiql-batch-delete.js index 6d7bae45ebd..ca89133ce9c 100644 --- a/javascriptv3/example_code/dynamodb/actions/partiql/partiql-batch-delete.js +++ b/javascriptv3/example_code/dynamodb/actions/partiql/partiql-batch-delete.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/partiql/partiql-batch-get.js b/javascriptv3/example_code/dynamodb/actions/partiql/partiql-batch-get.js index 75409153ebd..f82f4526096 100644 --- a/javascriptv3/example_code/dynamodb/actions/partiql/partiql-batch-get.js +++ b/javascriptv3/example_code/dynamodb/actions/partiql/partiql-batch-get.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/partiql/partiql-batch-put.js b/javascriptv3/example_code/dynamodb/actions/partiql/partiql-batch-put.js index 7088bb9142c..6b57eb747a1 100644 --- a/javascriptv3/example_code/dynamodb/actions/partiql/partiql-batch-put.js +++ b/javascriptv3/example_code/dynamodb/actions/partiql/partiql-batch-put.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/partiql/partiql-batch-update.js b/javascriptv3/example_code/dynamodb/actions/partiql/partiql-batch-update.js index fb367e2ecd2..973666260ba 100644 --- a/javascriptv3/example_code/dynamodb/actions/partiql/partiql-batch-update.js +++ b/javascriptv3/example_code/dynamodb/actions/partiql/partiql-batch-update.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/partiql/partiql-delete.js b/javascriptv3/example_code/dynamodb/actions/partiql/partiql-delete.js index 4212711951e..fbb7af527aa 100644 --- a/javascriptv3/example_code/dynamodb/actions/partiql/partiql-delete.js +++ b/javascriptv3/example_code/dynamodb/actions/partiql/partiql-delete.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/partiql/partiql-get.js b/javascriptv3/example_code/dynamodb/actions/partiql/partiql-get.js index c809a96c3ab..2559a509c99 100644 --- a/javascriptv3/example_code/dynamodb/actions/partiql/partiql-get.js +++ b/javascriptv3/example_code/dynamodb/actions/partiql/partiql-get.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/partiql/partiql-put.js b/javascriptv3/example_code/dynamodb/actions/partiql/partiql-put.js index 19f66d43048..2d3ba406402 100644 --- a/javascriptv3/example_code/dynamodb/actions/partiql/partiql-put.js +++ b/javascriptv3/example_code/dynamodb/actions/partiql/partiql-put.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/partiql/partiql-update.js b/javascriptv3/example_code/dynamodb/actions/partiql/partiql-update.js index d83fba9db35..78a0ec900f5 100644 --- a/javascriptv3/example_code/dynamodb/actions/partiql/partiql-update.js +++ b/javascriptv3/example_code/dynamodb/actions/partiql/partiql-update.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/put-item.js b/javascriptv3/example_code/dynamodb/actions/put-item.js index 253631961cb..4de0d209045 100644 --- a/javascriptv3/example_code/dynamodb/actions/put-item.js +++ b/javascriptv3/example_code/dynamodb/actions/put-item.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/query.js b/javascriptv3/example_code/dynamodb/actions/query.js index 0aed89ccfad..d6a0f9980b4 100644 --- a/javascriptv3/example_code/dynamodb/actions/query.js +++ b/javascriptv3/example_code/dynamodb/actions/query.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/scan.js b/javascriptv3/example_code/dynamodb/actions/scan.js index cba09f0f33e..41c0ce01975 100644 --- a/javascriptv3/example_code/dynamodb/actions/scan.js +++ b/javascriptv3/example_code/dynamodb/actions/scan.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/actions/update-item.js b/javascriptv3/example_code/dynamodb/actions/update-item.js index ff34d6ab465..4c344935d68 100644 --- a/javascriptv3/example_code/dynamodb/actions/update-item.js +++ b/javascriptv3/example_code/dynamodb/actions/update-item.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/client.js b/javascriptv3/example_code/dynamodb/client.js index 72a3a124831..50453c29b90 100644 --- a/javascriptv3/example_code/dynamodb/client.js +++ b/javascriptv3/example_code/dynamodb/client.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[dynamodb.JavaScript.tables.createclientv3] import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; diff --git a/javascriptv3/example_code/dynamodb/doc-client.js b/javascriptv3/example_code/dynamodb/doc-client.js index f2398125589..fc030f887da 100644 --- a/javascriptv3/example_code/dynamodb/doc-client.js +++ b/javascriptv3/example_code/dynamodb/doc-client.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[dynamodb.JavaScript.tables.createdocclientv3] import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; diff --git a/javascriptv3/example_code/dynamodb/hello.js b/javascriptv3/example_code/dynamodb/hello.js index 6c7c76d7fb1..5ed6971560c 100644 --- a/javascriptv3/example_code/dynamodb/hello.js +++ b/javascriptv3/example_code/dynamodb/hello.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/libs/dynamodb-test.utils.js b/javascriptv3/example_code/dynamodb/libs/dynamodb-test.utils.js index 2fff85c13fd..55f9e6de747 100644 --- a/javascriptv3/example_code/dynamodb/libs/dynamodb-test.utils.js +++ b/javascriptv3/example_code/dynamodb/libs/dynamodb-test.utils.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { BillingMode, diff --git a/javascriptv3/example_code/dynamodb/scenarios/basic.js b/javascriptv3/example_code/dynamodb/scenarios/basic.js index 2cc65de41db..fdfba4956e4 100644 --- a/javascriptv3/example_code/dynamodb/scenarios/basic.js +++ b/javascriptv3/example_code/dynamodb/scenarios/basic.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/scenarios/partiql-batch.js b/javascriptv3/example_code/dynamodb/scenarios/partiql-batch.js index 545bdd38663..bee74fba8ef 100644 --- a/javascriptv3/example_code/dynamodb/scenarios/partiql-batch.js +++ b/javascriptv3/example_code/dynamodb/scenarios/partiql-batch.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/scenarios/partiql-single.js b/javascriptv3/example_code/dynamodb/scenarios/partiql-single.js index ae180526e7e..9056ace6f25 100644 --- a/javascriptv3/example_code/dynamodb/scenarios/partiql-single.js +++ b/javascriptv3/example_code/dynamodb/scenarios/partiql-single.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/dynamodb/tests/basic.integration.test.js b/javascriptv3/example_code/dynamodb/tests/basic.integration.test.js index ff7927b8d52..bac87f63c26 100644 --- a/javascriptv3/example_code/dynamodb/tests/basic.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/basic.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it } from "vitest"; import { main } from "../scenarios/basic.js"; diff --git a/javascriptv3/example_code/dynamodb/tests/batch-get-item.integration.test.js b/javascriptv3/example_code/dynamodb/tests/batch-get-item.integration.test.js index b9e6055f670..737000b13d0 100644 --- a/javascriptv3/example_code/dynamodb/tests/batch-get-item.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/batch-get-item.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { main } from "../actions/batch-get-item.js"; diff --git a/javascriptv3/example_code/dynamodb/tests/batch-write-item.integration.test.js b/javascriptv3/example_code/dynamodb/tests/batch-write-item.integration.test.js index 87a746e6c75..052e7d5688b 100644 --- a/javascriptv3/example_code/dynamodb/tests/batch-write-item.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/batch-write-item.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, BatchGetCommand } from "@aws-sdk/lib-dynamodb"; diff --git a/javascriptv3/example_code/dynamodb/tests/create-table.integration.test.js b/javascriptv3/example_code/dynamodb/tests/create-table.integration.test.js index 71613978f54..62ee848155f 100644 --- a/javascriptv3/example_code/dynamodb/tests/create-table.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/create-table.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, afterAll } from "vitest"; import { diff --git a/javascriptv3/example_code/dynamodb/tests/delete-item.integration.test.js b/javascriptv3/example_code/dynamodb/tests/delete-item.integration.test.js index 737f14f4e98..0b08fd4acc1 100644 --- a/javascriptv3/example_code/dynamodb/tests/delete-item.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/delete-item.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, GetCommand } from "@aws-sdk/lib-dynamodb"; diff --git a/javascriptv3/example_code/dynamodb/tests/delete-table.integration.test.js b/javascriptv3/example_code/dynamodb/tests/delete-table.integration.test.js index 2ecdb6ec595..8e0418081e2 100644 --- a/javascriptv3/example_code/dynamodb/tests/delete-table.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/delete-table.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, beforeAll } from "vitest"; import { CreateTableCommand, diff --git a/javascriptv3/example_code/dynamodb/tests/describe-table.integration.test.js b/javascriptv3/example_code/dynamodb/tests/describe-table.integration.test.js index 2ae5b615121..64cdc837560 100644 --- a/javascriptv3/example_code/dynamodb/tests/describe-table.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/describe-table.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { main } from "../actions/describe-table.js"; import { tableSetupTeardown } from "../libs/dynamodb-test.utils.js"; diff --git a/javascriptv3/example_code/dynamodb/tests/document-batch-get.integration.test.js b/javascriptv3/example_code/dynamodb/tests/document-batch-get.integration.test.js index c7bcc716388..85dd45da9d3 100644 --- a/javascriptv3/example_code/dynamodb/tests/document-batch-get.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/document-batch-get.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { main } from "../actions/document-client/batch-get.js"; diff --git a/javascriptv3/example_code/dynamodb/tests/document-batch-write.integration.test.js b/javascriptv3/example_code/dynamodb/tests/document-batch-write.integration.test.js index fb84c4e6a8e..e8ac13b0367 100644 --- a/javascriptv3/example_code/dynamodb/tests/document-batch-write.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/document-batch-write.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { main } from "../actions/document-client/batch-write.js"; diff --git a/javascriptv3/example_code/dynamodb/tests/document-delete.integration.test.js b/javascriptv3/example_code/dynamodb/tests/document-delete.integration.test.js index 4b6694be7a1..2806747c053 100644 --- a/javascriptv3/example_code/dynamodb/tests/document-delete.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/document-delete.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { main } from "../actions/document-client/delete.js"; diff --git a/javascriptv3/example_code/dynamodb/tests/document-get.integration.test.js b/javascriptv3/example_code/dynamodb/tests/document-get.integration.test.js index 61cddf81d82..2ad9bf734de 100644 --- a/javascriptv3/example_code/dynamodb/tests/document-get.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/document-get.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { main } from "../actions/document-client/get.js"; diff --git a/javascriptv3/example_code/dynamodb/tests/document-put.integration.test.js b/javascriptv3/example_code/dynamodb/tests/document-put.integration.test.js index 61c26bd77b8..cf186ff9d4c 100644 --- a/javascriptv3/example_code/dynamodb/tests/document-put.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/document-put.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { main } from "../actions/document-client/put.js"; diff --git a/javascriptv3/example_code/dynamodb/tests/document-query.integration.test.js b/javascriptv3/example_code/dynamodb/tests/document-query.integration.test.js index 7043afb8742..8b1e0f28901 100644 --- a/javascriptv3/example_code/dynamodb/tests/document-query.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/document-query.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { main } from "../actions/document-client/query.js"; diff --git a/javascriptv3/example_code/dynamodb/tests/document-scan.integration.test.js b/javascriptv3/example_code/dynamodb/tests/document-scan.integration.test.js index 63068857c4d..590be99128b 100644 --- a/javascriptv3/example_code/dynamodb/tests/document-scan.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/document-scan.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { main } from "../actions/document-client/scan.js"; diff --git a/javascriptv3/example_code/dynamodb/tests/document-update.integration.test.js b/javascriptv3/example_code/dynamodb/tests/document-update.integration.test.js index 9fe8f5f7a09..d0f037a58a0 100644 --- a/javascriptv3/example_code/dynamodb/tests/document-update.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/document-update.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { main } from "../actions/document-client/update.js"; diff --git a/javascriptv3/example_code/dynamodb/tests/get-item.integration.test.js b/javascriptv3/example_code/dynamodb/tests/get-item.integration.test.js index be1d36da836..cdc4850035f 100644 --- a/javascriptv3/example_code/dynamodb/tests/get-item.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/get-item.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { main } from "../actions/get-item.js"; diff --git a/javascriptv3/example_code/dynamodb/tests/hello.integration.test.js b/javascriptv3/example_code/dynamodb/tests/hello.integration.test.js index 218827392d5..73fed74c546 100644 --- a/javascriptv3/example_code/dynamodb/tests/hello.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/hello.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { main } from "../hello.js"; diff --git a/javascriptv3/example_code/dynamodb/tests/list-tables.integration.test.js b/javascriptv3/example_code/dynamodb/tests/list-tables.integration.test.js index 8d3b435b19a..c97b0903557 100644 --- a/javascriptv3/example_code/dynamodb/tests/list-tables.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/list-tables.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { main } from "../actions/list-tables.js"; diff --git a/javascriptv3/example_code/dynamodb/tests/partiql-batch-delete.integration.test.js b/javascriptv3/example_code/dynamodb/tests/partiql-batch-delete.integration.test.js index fd3c604622b..57f879e5ed8 100644 --- a/javascriptv3/example_code/dynamodb/tests/partiql-batch-delete.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/partiql-batch-delete.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { DynamoDBClient, ScanCommand } from "@aws-sdk/client-dynamodb"; diff --git a/javascriptv3/example_code/dynamodb/tests/partiql-batch-get.integration.test.js b/javascriptv3/example_code/dynamodb/tests/partiql-batch-get.integration.test.js index 8b3952f2343..35e47e100a1 100644 --- a/javascriptv3/example_code/dynamodb/tests/partiql-batch-get.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/partiql-batch-get.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { main } from "../actions/partiql/partiql-batch-get.js"; diff --git a/javascriptv3/example_code/dynamodb/tests/partiql-batch-put.integration.test.js b/javascriptv3/example_code/dynamodb/tests/partiql-batch-put.integration.test.js index 299fb51af89..46e5e5a32f8 100644 --- a/javascriptv3/example_code/dynamodb/tests/partiql-batch-put.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/partiql-batch-put.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { ScanCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb"; diff --git a/javascriptv3/example_code/dynamodb/tests/partiql-batch-update.integration.test.js b/javascriptv3/example_code/dynamodb/tests/partiql-batch-update.integration.test.js index 3349c65c893..ccd13a67bd5 100644 --- a/javascriptv3/example_code/dynamodb/tests/partiql-batch-update.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/partiql-batch-update.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { ScanCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb"; diff --git a/javascriptv3/example_code/dynamodb/tests/partiql-batch.integration.test.js b/javascriptv3/example_code/dynamodb/tests/partiql-batch.integration.test.js index 3527216f090..3d33492c0ee 100644 --- a/javascriptv3/example_code/dynamodb/tests/partiql-batch.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/partiql-batch.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it } from "vitest"; import { main } from "../scenarios/partiql-batch.js"; diff --git a/javascriptv3/example_code/dynamodb/tests/partiql-delete.integration.test.js b/javascriptv3/example_code/dynamodb/tests/partiql-delete.integration.test.js index 93ccf1b9cbd..fa93bafbd9f 100644 --- a/javascriptv3/example_code/dynamodb/tests/partiql-delete.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/partiql-delete.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { DynamoDBClient, ScanCommand } from "@aws-sdk/client-dynamodb"; diff --git a/javascriptv3/example_code/dynamodb/tests/partiql-get.integration.test.js b/javascriptv3/example_code/dynamodb/tests/partiql-get.integration.test.js index b8c08fd3f67..fb75ec88b68 100644 --- a/javascriptv3/example_code/dynamodb/tests/partiql-get.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/partiql-get.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { main } from "../actions/partiql/partiql-get.js"; diff --git a/javascriptv3/example_code/dynamodb/tests/partiql-put.integration.test.js b/javascriptv3/example_code/dynamodb/tests/partiql-put.integration.test.js index 9b53205b459..e7340b390c4 100644 --- a/javascriptv3/example_code/dynamodb/tests/partiql-put.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/partiql-put.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { ScanCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb"; diff --git a/javascriptv3/example_code/dynamodb/tests/partiql-single.integration.test.js b/javascriptv3/example_code/dynamodb/tests/partiql-single.integration.test.js index d7ccae464e9..3fb60cf3c7f 100644 --- a/javascriptv3/example_code/dynamodb/tests/partiql-single.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/partiql-single.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it } from "vitest"; import { main } from "../scenarios/partiql-single.js"; diff --git a/javascriptv3/example_code/dynamodb/tests/partiql-update.integration.test.js b/javascriptv3/example_code/dynamodb/tests/partiql-update.integration.test.js index cda40234bca..773fc475a6b 100644 --- a/javascriptv3/example_code/dynamodb/tests/partiql-update.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/partiql-update.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { DynamoDBClient, GetItemCommand } from "@aws-sdk/client-dynamodb"; diff --git a/javascriptv3/example_code/dynamodb/tests/put-item.integration.test.js b/javascriptv3/example_code/dynamodb/tests/put-item.integration.test.js index eda5328d93a..d8d0a8415c7 100644 --- a/javascriptv3/example_code/dynamodb/tests/put-item.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/put-item.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { main } from "../actions/put-item.js"; diff --git a/javascriptv3/example_code/dynamodb/tests/query-and-scan.integration.test.js b/javascriptv3/example_code/dynamodb/tests/query-and-scan.integration.test.js index 2d208222d97..166b2bc3f37 100644 --- a/javascriptv3/example_code/dynamodb/tests/query-and-scan.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/query-and-scan.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, expect, it } from "vitest"; import { main as query } from "../actions/query.js"; diff --git a/javascriptv3/example_code/dynamodb/tests/update-item.integration.test.js b/javascriptv3/example_code/dynamodb/tests/update-item.integration.test.js index 4093e8cbf06..25600fc428c 100644 --- a/javascriptv3/example_code/dynamodb/tests/update-item.integration.test.js +++ b/javascriptv3/example_code/dynamodb/tests/update-item.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { DynamoDBDocumentClient, GetCommand } from "@aws-sdk/lib-dynamodb"; import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; diff --git a/javascriptv3/example_code/dynamodb/vite.config.js b/javascriptv3/example_code/dynamodb/vite.config.js index 725a62bab5c..acd4add0493 100644 --- a/javascriptv3/example_code/dynamodb/vite.config.js +++ b/javascriptv3/example_code/dynamodb/vite.config.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { defineConfig } from "vitest/config"; diff --git a/javascriptv3/example_code/ec2/actions/allocate-address.js b/javascriptv3/example_code/ec2/actions/allocate-address.js index e48eea3f711..cacb3f61c06 100644 --- a/javascriptv3/example_code/ec2/actions/allocate-address.js +++ b/javascriptv3/example_code/ec2/actions/allocate-address.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/associate-address.js b/javascriptv3/example_code/ec2/actions/associate-address.js index d22da367c02..60c6c55cd9a 100644 --- a/javascriptv3/example_code/ec2/actions/associate-address.js +++ b/javascriptv3/example_code/ec2/actions/associate-address.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/authorize-security-group-ingress.js b/javascriptv3/example_code/ec2/actions/authorize-security-group-ingress.js index ef77329340b..b15a7d64f48 100644 --- a/javascriptv3/example_code/ec2/actions/authorize-security-group-ingress.js +++ b/javascriptv3/example_code/ec2/actions/authorize-security-group-ingress.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/create-key-pair.js b/javascriptv3/example_code/ec2/actions/create-key-pair.js index 3a6960dd4ef..1b2badcc07a 100644 --- a/javascriptv3/example_code/ec2/actions/create-key-pair.js +++ b/javascriptv3/example_code/ec2/actions/create-key-pair.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/create-security-group.js b/javascriptv3/example_code/ec2/actions/create-security-group.js index eaa4d665e1f..6945f92885b 100644 --- a/javascriptv3/example_code/ec2/actions/create-security-group.js +++ b/javascriptv3/example_code/ec2/actions/create-security-group.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/delete-key-pair.js b/javascriptv3/example_code/ec2/actions/delete-key-pair.js index 5dd7292896d..5cdb11faaf8 100644 --- a/javascriptv3/example_code/ec2/actions/delete-key-pair.js +++ b/javascriptv3/example_code/ec2/actions/delete-key-pair.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/delete-security-group.js b/javascriptv3/example_code/ec2/actions/delete-security-group.js index 0100a63cd97..698e6ac8f2b 100644 --- a/javascriptv3/example_code/ec2/actions/delete-security-group.js +++ b/javascriptv3/example_code/ec2/actions/delete-security-group.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/describe-addresses.js b/javascriptv3/example_code/ec2/actions/describe-addresses.js index e27ee41a771..8bd03c9f4ef 100644 --- a/javascriptv3/example_code/ec2/actions/describe-addresses.js +++ b/javascriptv3/example_code/ec2/actions/describe-addresses.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/describe-images.js b/javascriptv3/example_code/ec2/actions/describe-images.js index 0d7afd14297..fbdae97a213 100644 --- a/javascriptv3/example_code/ec2/actions/describe-images.js +++ b/javascriptv3/example_code/ec2/actions/describe-images.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/describe-instance-types.js b/javascriptv3/example_code/ec2/actions/describe-instance-types.js index b213014e407..2aff493611e 100644 --- a/javascriptv3/example_code/ec2/actions/describe-instance-types.js +++ b/javascriptv3/example_code/ec2/actions/describe-instance-types.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/describe-instances.js b/javascriptv3/example_code/ec2/actions/describe-instances.js index 2ec9a4d250c..85d5e22ddc6 100644 --- a/javascriptv3/example_code/ec2/actions/describe-instances.js +++ b/javascriptv3/example_code/ec2/actions/describe-instances.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/describe-key-pairs.js b/javascriptv3/example_code/ec2/actions/describe-key-pairs.js index c7c202583a2..3896544f605 100644 --- a/javascriptv3/example_code/ec2/actions/describe-key-pairs.js +++ b/javascriptv3/example_code/ec2/actions/describe-key-pairs.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/describe-regions.js b/javascriptv3/example_code/ec2/actions/describe-regions.js index de843000ab3..f4c7b385480 100644 --- a/javascriptv3/example_code/ec2/actions/describe-regions.js +++ b/javascriptv3/example_code/ec2/actions/describe-regions.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/describe-security-groups.js b/javascriptv3/example_code/ec2/actions/describe-security-groups.js index c72b967ed61..ab0a783ff88 100644 --- a/javascriptv3/example_code/ec2/actions/describe-security-groups.js +++ b/javascriptv3/example_code/ec2/actions/describe-security-groups.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/disassociate-address.js b/javascriptv3/example_code/ec2/actions/disassociate-address.js index 8125bb08b26..bba61510c66 100644 --- a/javascriptv3/example_code/ec2/actions/disassociate-address.js +++ b/javascriptv3/example_code/ec2/actions/disassociate-address.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/monitor-instances.js b/javascriptv3/example_code/ec2/actions/monitor-instances.js index b347c38b623..ed6a58433ff 100644 --- a/javascriptv3/example_code/ec2/actions/monitor-instances.js +++ b/javascriptv3/example_code/ec2/actions/monitor-instances.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/reboot-instances.js b/javascriptv3/example_code/ec2/actions/reboot-instances.js index 6cbc9fab44c..f5c9e100c44 100644 --- a/javascriptv3/example_code/ec2/actions/reboot-instances.js +++ b/javascriptv3/example_code/ec2/actions/reboot-instances.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/release-address.js b/javascriptv3/example_code/ec2/actions/release-address.js index 519f0b4a5fa..c2b98c412da 100644 --- a/javascriptv3/example_code/ec2/actions/release-address.js +++ b/javascriptv3/example_code/ec2/actions/release-address.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/run-instances.js b/javascriptv3/example_code/ec2/actions/run-instances.js index 0213e159834..cf33138c32d 100644 --- a/javascriptv3/example_code/ec2/actions/run-instances.js +++ b/javascriptv3/example_code/ec2/actions/run-instances.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/start-instances.js b/javascriptv3/example_code/ec2/actions/start-instances.js index d86e83f2b0f..f584b2013a3 100644 --- a/javascriptv3/example_code/ec2/actions/start-instances.js +++ b/javascriptv3/example_code/ec2/actions/start-instances.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/stop-instances.js b/javascriptv3/example_code/ec2/actions/stop-instances.js index 88e45086ebc..69013153b2e 100644 --- a/javascriptv3/example_code/ec2/actions/stop-instances.js +++ b/javascriptv3/example_code/ec2/actions/stop-instances.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/terminate-instances.js b/javascriptv3/example_code/ec2/actions/terminate-instances.js index 6800ea7a650..0d796109beb 100644 --- a/javascriptv3/example_code/ec2/actions/terminate-instances.js +++ b/javascriptv3/example_code/ec2/actions/terminate-instances.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/actions/unmonitor-instances.js b/javascriptv3/example_code/ec2/actions/unmonitor-instances.js index 69aff1eab62..ad3f605f435 100644 --- a/javascriptv3/example_code/ec2/actions/unmonitor-instances.js +++ b/javascriptv3/example_code/ec2/actions/unmonitor-instances.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/hello.js b/javascriptv3/example_code/ec2/hello.js index 6a6756a4258..56cb6a84cf4 100644 --- a/javascriptv3/example_code/ec2/hello.js +++ b/javascriptv3/example_code/ec2/hello.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/libs/client.js b/javascriptv3/example_code/ec2/libs/client.js index fa940095c48..40aba234699 100644 --- a/javascriptv3/example_code/ec2/libs/client.js +++ b/javascriptv3/example_code/ec2/libs/client.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[ec2.JavaScript.createclientv3] import { EC2Client } from "@aws-sdk/client-ec2"; diff --git a/javascriptv3/example_code/ec2/scenarios/basic.js b/javascriptv3/example_code/ec2/scenarios/basic.js index d9c00a6b2f6..bcb77240189 100644 --- a/javascriptv3/example_code/ec2/scenarios/basic.js +++ b/javascriptv3/example_code/ec2/scenarios/basic.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ec2/tests/allocate-address.unit.test.js b/javascriptv3/example_code/ec2/tests/allocate-address.unit.test.js index 9ed3997fdf0..46abd32cf92 100644 --- a/javascriptv3/example_code/ec2/tests/allocate-address.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/allocate-address.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/associate-address.unit.test.js b/javascriptv3/example_code/ec2/tests/associate-address.unit.test.js index e90d05a536b..8b4ab0a71a3 100644 --- a/javascriptv3/example_code/ec2/tests/associate-address.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/associate-address.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/authorize-security-group-ingress.unit.test.js b/javascriptv3/example_code/ec2/tests/authorize-security-group-ingress.unit.test.js index 4cefe80ebe8..cee5019767f 100644 --- a/javascriptv3/example_code/ec2/tests/authorize-security-group-ingress.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/authorize-security-group-ingress.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/create-key-pair.unit.test.js b/javascriptv3/example_code/ec2/tests/create-key-pair.unit.test.js index 63f68b76235..62d10470cc7 100644 --- a/javascriptv3/example_code/ec2/tests/create-key-pair.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/create-key-pair.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/create-security-group.unit.test.js b/javascriptv3/example_code/ec2/tests/create-security-group.unit.test.js index 013632d3f4d..a4001e48dd5 100644 --- a/javascriptv3/example_code/ec2/tests/create-security-group.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/create-security-group.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/delete-key-pair.unit.test.js b/javascriptv3/example_code/ec2/tests/delete-key-pair.unit.test.js index 29e1cab15e7..30fc513a181 100644 --- a/javascriptv3/example_code/ec2/tests/delete-key-pair.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/delete-key-pair.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/delete-security-group.unit.test.js b/javascriptv3/example_code/ec2/tests/delete-security-group.unit.test.js index 8bc91a1f365..25452a88dd6 100644 --- a/javascriptv3/example_code/ec2/tests/delete-security-group.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/delete-security-group.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/describe-addresses.unit.test.js b/javascriptv3/example_code/ec2/tests/describe-addresses.unit.test.js index 6c62e56a81c..c95481f46bc 100644 --- a/javascriptv3/example_code/ec2/tests/describe-addresses.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/describe-addresses.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/describe-images.unit.test.js b/javascriptv3/example_code/ec2/tests/describe-images.unit.test.js index 66c76bb8298..b8b89a6f901 100644 --- a/javascriptv3/example_code/ec2/tests/describe-images.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/describe-images.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/describe-instance-types.unit.test.js b/javascriptv3/example_code/ec2/tests/describe-instance-types.unit.test.js index 50c37cc5eb0..f22aeacfe0e 100644 --- a/javascriptv3/example_code/ec2/tests/describe-instance-types.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/describe-instance-types.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/describe-instances.unit.test.js b/javascriptv3/example_code/ec2/tests/describe-instances.unit.test.js index 3c9e87c05b8..893a8d3ac03 100644 --- a/javascriptv3/example_code/ec2/tests/describe-instances.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/describe-instances.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/describe-key-pairs.unit.test.js b/javascriptv3/example_code/ec2/tests/describe-key-pairs.unit.test.js index e837864a255..8ce732dc41c 100644 --- a/javascriptv3/example_code/ec2/tests/describe-key-pairs.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/describe-key-pairs.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/describe-regions.unit.test.js b/javascriptv3/example_code/ec2/tests/describe-regions.unit.test.js index 551061bdbf5..adc3e8edbcd 100644 --- a/javascriptv3/example_code/ec2/tests/describe-regions.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/describe-regions.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/describe-security-groups.unit.test.js b/javascriptv3/example_code/ec2/tests/describe-security-groups.unit.test.js index 35f41213c0c..b1df3d88587 100644 --- a/javascriptv3/example_code/ec2/tests/describe-security-groups.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/describe-security-groups.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/disassociate-address.unit.test.js b/javascriptv3/example_code/ec2/tests/disassociate-address.unit.test.js index 11ec195105d..708959723e2 100644 --- a/javascriptv3/example_code/ec2/tests/disassociate-address.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/disassociate-address.unit.test.js @@ -1,12 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ - -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/hello.unit.test.js b/javascriptv3/example_code/ec2/tests/hello.unit.test.js index 63748366c55..a01448787c7 100644 --- a/javascriptv3/example_code/ec2/tests/hello.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/hello.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/monitor-instances.unit.test.js b/javascriptv3/example_code/ec2/tests/monitor-instances.unit.test.js index 8ce98f151bc..9558662b78a 100644 --- a/javascriptv3/example_code/ec2/tests/monitor-instances.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/monitor-instances.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/reboot-instances.unit.test.js b/javascriptv3/example_code/ec2/tests/reboot-instances.unit.test.js index 1a7aef25a4a..6c0ea05b47f 100644 --- a/javascriptv3/example_code/ec2/tests/reboot-instances.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/reboot-instances.unit.test.js @@ -1,12 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ - -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/release-address.unit.test.js b/javascriptv3/example_code/ec2/tests/release-address.unit.test.js index 156e74d32ae..40c94368c9c 100644 --- a/javascriptv3/example_code/ec2/tests/release-address.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/release-address.unit.test.js @@ -1,12 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ - -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/run-instances.unit.test.js b/javascriptv3/example_code/ec2/tests/run-instances.unit.test.js index f646b399687..8b3034b2f9c 100644 --- a/javascriptv3/example_code/ec2/tests/run-instances.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/run-instances.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/start-instances.unit.test.js b/javascriptv3/example_code/ec2/tests/start-instances.unit.test.js index 2f5e22eab9f..ee935b16744 100644 --- a/javascriptv3/example_code/ec2/tests/start-instances.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/start-instances.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/stop-instances.unit.test.js b/javascriptv3/example_code/ec2/tests/stop-instances.unit.test.js index f9f06d19b5b..3a694c47e0f 100644 --- a/javascriptv3/example_code/ec2/tests/stop-instances.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/stop-instances.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/terminate-instances.unit.test.js b/javascriptv3/example_code/ec2/tests/terminate-instances.unit.test.js index 966ab55be55..620e017118d 100644 --- a/javascriptv3/example_code/ec2/tests/terminate-instances.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/terminate-instances.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/ec2/tests/unmonitor-instances.unit.test.js b/javascriptv3/example_code/ec2/tests/unmonitor-instances.unit.test.js index be526e82333..2e42bcd7997 100644 --- a/javascriptv3/example_code/ec2/tests/unmonitor-instances.unit.test.js +++ b/javascriptv3/example_code/ec2/tests/unmonitor-instances.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/elastic-load-balancing-v2/hello.js b/javascriptv3/example_code/elastic-load-balancing-v2/hello.js index c4ad8396592..401123d7af3 100644 --- a/javascriptv3/example_code/elastic-load-balancing-v2/hello.js +++ b/javascriptv3/example_code/elastic-load-balancing-v2/hello.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { ElasticLoadBalancingV2Client, diff --git a/javascriptv3/example_code/elastic-load-balancing-v2/tests/hello.integration.test.js b/javascriptv3/example_code/elastic-load-balancing-v2/tests/hello.integration.test.js index bac52203a24..9653275a531 100644 --- a/javascriptv3/example_code/elastic-load-balancing-v2/tests/hello.integration.test.js +++ b/javascriptv3/example_code/elastic-load-balancing-v2/tests/hello.integration.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { vi, describe, it, expect } from "vitest"; import { main as hello } from "../hello.js"; diff --git a/javascriptv3/example_code/eventbridge/actions/put-events.js b/javascriptv3/example_code/eventbridge/actions/put-events.js index 72e9e61ccba..4f316e5aae7 100644 --- a/javascriptv3/example_code/eventbridge/actions/put-events.js +++ b/javascriptv3/example_code/eventbridge/actions/put-events.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[eventBridge.JavaScript.eb.putEventsV3] import { diff --git a/javascriptv3/example_code/eventbridge/actions/put-rule.js b/javascriptv3/example_code/eventbridge/actions/put-rule.js index 225145e0af7..dd33662ba3d 100644 --- a/javascriptv3/example_code/eventbridge/actions/put-rule.js +++ b/javascriptv3/example_code/eventbridge/actions/put-rule.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[eventBridge.JavaScript.eb.putRuleV3] import { EventBridgeClient, PutRuleCommand } from "@aws-sdk/client-eventbridge"; diff --git a/javascriptv3/example_code/eventbridge/actions/put-targets.js b/javascriptv3/example_code/eventbridge/actions/put-targets.js index f7eb9853c79..361eca4a93f 100644 --- a/javascriptv3/example_code/eventbridge/actions/put-targets.js +++ b/javascriptv3/example_code/eventbridge/actions/put-targets.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[eventBridge.JavaScript.eb.putTargetsV3] import { diff --git a/javascriptv3/example_code/eventbridge/client.js b/javascriptv3/example_code/eventbridge/client.js index 26453fd19f5..df16731fdb1 100644 --- a/javascriptv3/example_code/eventbridge/client.js +++ b/javascriptv3/example_code/eventbridge/client.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[eventbridge.JavaScript.events.createclientv3] import { EventBridgeClient } from "@aws-sdk/client-eventbridge"; diff --git a/javascriptv3/example_code/eventbridge/tests/eventbridge.integration.test.js b/javascriptv3/example_code/eventbridge/tests/eventbridge.integration.test.js index d9fac63af90..9babf65d35e 100644 --- a/javascriptv3/example_code/eventbridge/tests/eventbridge.integration.test.js +++ b/javascriptv3/example_code/eventbridge/tests/eventbridge.integration.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { test, expect, beforeAll, afterAll } from "vitest"; diff --git a/javascriptv3/example_code/eventbridge/vite.config.js b/javascriptv3/example_code/eventbridge/vite.config.js index 232090ca4de..97e20ba2b3d 100644 --- a/javascriptv3/example_code/eventbridge/vite.config.js +++ b/javascriptv3/example_code/eventbridge/vite.config.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { defineConfig } from "vitest/config"; diff --git a/javascriptv3/example_code/glacier/src/createVault.ts b/javascriptv3/example_code/glacier/src/createVault.ts index 03cfc254c19..3620544065d 100644 --- a/javascriptv3/example_code/glacier/src/createVault.ts +++ b/javascriptv3/example_code/glacier/src/createVault.ts @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/glacier-example-creating-a-vault.html. diff --git a/javascriptv3/example_code/glacier/src/libs/glacierClient.js b/javascriptv3/example_code/glacier/src/libs/glacierClient.js index ec24d169b51..806e50016b4 100644 --- a/javascriptv3/example_code/glacier/src/libs/glacierClient.js +++ b/javascriptv3/example_code/glacier/src/libs/glacierClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/glacier-examples.html. diff --git a/javascriptv3/example_code/glacier/src/uploadArchive.ts b/javascriptv3/example_code/glacier/src/uploadArchive.ts index 52a54f417c5..ca95bb884bf 100644 --- a/javascriptv3/example_code/glacier/src/uploadArchive.ts +++ b/javascriptv3/example_code/glacier/src/uploadArchive.ts @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/glacier-example-uploadarchive.html. diff --git a/javascriptv3/example_code/glue/actions/create-crawler.js b/javascriptv3/example_code/glue/actions/create-crawler.js index 742d7515ef0..817c06816a0 100644 --- a/javascriptv3/example_code/glue/actions/create-crawler.js +++ b/javascriptv3/example_code/glue/actions/create-crawler.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { CreateCrawlerCommand, GlueClient } from "@aws-sdk/client-glue"; diff --git a/javascriptv3/example_code/glue/actions/create-job.js b/javascriptv3/example_code/glue/actions/create-job.js index 6ea8ccb6cb3..9ee4577ce26 100644 --- a/javascriptv3/example_code/glue/actions/create-job.js +++ b/javascriptv3/example_code/glue/actions/create-job.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { CreateJobCommand, GlueClient } from "@aws-sdk/client-glue"; diff --git a/javascriptv3/example_code/glue/actions/delete-crawler.js b/javascriptv3/example_code/glue/actions/delete-crawler.js index 434b2ba38d3..d7b0ac13935 100644 --- a/javascriptv3/example_code/glue/actions/delete-crawler.js +++ b/javascriptv3/example_code/glue/actions/delete-crawler.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { DeleteCrawlerCommand, GlueClient } from "@aws-sdk/client-glue"; diff --git a/javascriptv3/example_code/glue/actions/delete-database.js b/javascriptv3/example_code/glue/actions/delete-database.js index eee9e1410ff..e6aa5928028 100644 --- a/javascriptv3/example_code/glue/actions/delete-database.js +++ b/javascriptv3/example_code/glue/actions/delete-database.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { DeleteDatabaseCommand, GlueClient } from "@aws-sdk/client-glue"; diff --git a/javascriptv3/example_code/glue/actions/delete-job.js b/javascriptv3/example_code/glue/actions/delete-job.js index e62d5dc579f..9760aaa0624 100644 --- a/javascriptv3/example_code/glue/actions/delete-job.js +++ b/javascriptv3/example_code/glue/actions/delete-job.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { DeleteJobCommand, GlueClient } from "@aws-sdk/client-glue"; diff --git a/javascriptv3/example_code/glue/actions/delete-table.js b/javascriptv3/example_code/glue/actions/delete-table.js index c74fa82ddb0..68e9ae520e4 100644 --- a/javascriptv3/example_code/glue/actions/delete-table.js +++ b/javascriptv3/example_code/glue/actions/delete-table.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { DeleteTableCommand, GlueClient } from "@aws-sdk/client-glue"; diff --git a/javascriptv3/example_code/glue/actions/get-crawler.js b/javascriptv3/example_code/glue/actions/get-crawler.js index 1a3f3120406..c6c27a8e484 100644 --- a/javascriptv3/example_code/glue/actions/get-crawler.js +++ b/javascriptv3/example_code/glue/actions/get-crawler.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { GetCrawlerCommand, GlueClient } from "@aws-sdk/client-glue"; diff --git a/javascriptv3/example_code/glue/actions/get-database.js b/javascriptv3/example_code/glue/actions/get-database.js index 035ed51e438..3a491e97ae8 100644 --- a/javascriptv3/example_code/glue/actions/get-database.js +++ b/javascriptv3/example_code/glue/actions/get-database.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { GetDatabaseCommand, GlueClient } from "@aws-sdk/client-glue"; diff --git a/javascriptv3/example_code/glue/actions/get-databases.js b/javascriptv3/example_code/glue/actions/get-databases.js index c0f0efb51a8..0edd053f4f3 100644 --- a/javascriptv3/example_code/glue/actions/get-databases.js +++ b/javascriptv3/example_code/glue/actions/get-databases.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { GetDatabasesCommand, GlueClient } from "@aws-sdk/client-glue"; diff --git a/javascriptv3/example_code/glue/actions/get-job-run.js b/javascriptv3/example_code/glue/actions/get-job-run.js index 0524b3df157..9a05df732d5 100644 --- a/javascriptv3/example_code/glue/actions/get-job-run.js +++ b/javascriptv3/example_code/glue/actions/get-job-run.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { GetJobRunCommand, GlueClient } from "@aws-sdk/client-glue"; diff --git a/javascriptv3/example_code/glue/actions/get-job-runs.js b/javascriptv3/example_code/glue/actions/get-job-runs.js index 8a367e5e2b5..34d3f9d6c58 100644 --- a/javascriptv3/example_code/glue/actions/get-job-runs.js +++ b/javascriptv3/example_code/glue/actions/get-job-runs.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { GetJobRunsCommand, GlueClient } from "@aws-sdk/client-glue"; diff --git a/javascriptv3/example_code/glue/actions/get-job.js b/javascriptv3/example_code/glue/actions/get-job.js index 73825f90583..046f1bb4685 100644 --- a/javascriptv3/example_code/glue/actions/get-job.js +++ b/javascriptv3/example_code/glue/actions/get-job.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { GetJobCommand, GlueClient } from "@aws-sdk/client-glue"; diff --git a/javascriptv3/example_code/glue/actions/get-tables.js b/javascriptv3/example_code/glue/actions/get-tables.js index 921ebf4ea77..90ff2b4d3d1 100644 --- a/javascriptv3/example_code/glue/actions/get-tables.js +++ b/javascriptv3/example_code/glue/actions/get-tables.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { GetTablesCommand, GlueClient } from "@aws-sdk/client-glue"; diff --git a/javascriptv3/example_code/glue/actions/list-jobs.js b/javascriptv3/example_code/glue/actions/list-jobs.js index c50ccf79f8c..774d757e84d 100644 --- a/javascriptv3/example_code/glue/actions/list-jobs.js +++ b/javascriptv3/example_code/glue/actions/list-jobs.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { ListJobsCommand, GlueClient } from "@aws-sdk/client-glue"; diff --git a/javascriptv3/example_code/glue/actions/start-crawler.js b/javascriptv3/example_code/glue/actions/start-crawler.js index 5c9542f1887..68ce922bb73 100644 --- a/javascriptv3/example_code/glue/actions/start-crawler.js +++ b/javascriptv3/example_code/glue/actions/start-crawler.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { GlueClient, StartCrawlerCommand } from "@aws-sdk/client-glue"; diff --git a/javascriptv3/example_code/glue/actions/start-job-run.js b/javascriptv3/example_code/glue/actions/start-job-run.js index 6bcd589c32d..a3b40b7e47b 100644 --- a/javascriptv3/example_code/glue/actions/start-job-run.js +++ b/javascriptv3/example_code/glue/actions/start-job-run.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { GlueClient, StartJobRunCommand } from "@aws-sdk/client-glue"; diff --git a/javascriptv3/example_code/glue/hello.js b/javascriptv3/example_code/glue/hello.js index 466a43f2c60..2c4a7f5f921 100644 --- a/javascriptv3/example_code/glue/hello.js +++ b/javascriptv3/example_code/glue/hello.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/glue/non-glue-actions/s3-list-objects.js b/javascriptv3/example_code/glue/non-glue-actions/s3-list-objects.js index 74b1b45da4e..182328ae380 100644 --- a/javascriptv3/example_code/glue/non-glue-actions/s3-list-objects.js +++ b/javascriptv3/example_code/glue/non-glue-actions/s3-list-objects.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { ListObjectsCommand, S3Client } from "@aws-sdk/client-s3"; diff --git a/javascriptv3/example_code/glue/scenarios/basic/index.js b/javascriptv3/example_code/glue/scenarios/basic/index.js index d0690141e6f..23ee1942a8f 100644 --- a/javascriptv3/example_code/glue/scenarios/basic/index.js +++ b/javascriptv3/example_code/glue/scenarios/basic/index.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import inquirer from "inquirer"; import { config } from "dotenv"; diff --git a/javascriptv3/example_code/glue/scenarios/basic/log.js b/javascriptv3/example_code/glue/scenarios/basic/log.js index 82293ce9bf9..5d9e2aad495 100644 --- a/javascriptv3/example_code/glue/scenarios/basic/log.js +++ b/javascriptv3/example_code/glue/scenarios/basic/log.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import chalk from "chalk"; diff --git a/javascriptv3/example_code/glue/scenarios/basic/steps/clean-up-crawler.js b/javascriptv3/example_code/glue/scenarios/basic/steps/clean-up-crawler.js index c7675d03f50..cf9aa063560 100644 --- a/javascriptv3/example_code/glue/scenarios/basic/steps/clean-up-crawler.js +++ b/javascriptv3/example_code/glue/scenarios/basic/steps/clean-up-crawler.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { deleteCrawler } from "../../../actions/delete-crawler.js"; import { log } from "../log.js"; diff --git a/javascriptv3/example_code/glue/scenarios/basic/steps/clean-up-databases.js b/javascriptv3/example_code/glue/scenarios/basic/steps/clean-up-databases.js index c2ee3b6ee00..819113ae53b 100644 --- a/javascriptv3/example_code/glue/scenarios/basic/steps/clean-up-databases.js +++ b/javascriptv3/example_code/glue/scenarios/basic/steps/clean-up-databases.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { log } from "../log.js"; diff --git a/javascriptv3/example_code/glue/scenarios/basic/steps/clean-up-jobs.js b/javascriptv3/example_code/glue/scenarios/basic/steps/clean-up-jobs.js index 0c3e66495fb..0833e3c0ce5 100644 --- a/javascriptv3/example_code/glue/scenarios/basic/steps/clean-up-jobs.js +++ b/javascriptv3/example_code/glue/scenarios/basic/steps/clean-up-jobs.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { log } from "../log.js"; diff --git a/javascriptv3/example_code/glue/scenarios/basic/steps/clean-up-tables.js b/javascriptv3/example_code/glue/scenarios/basic/steps/clean-up-tables.js index 2fb2195328f..309115413f4 100644 --- a/javascriptv3/example_code/glue/scenarios/basic/steps/clean-up-tables.js +++ b/javascriptv3/example_code/glue/scenarios/basic/steps/clean-up-tables.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { log } from "../log.js"; diff --git a/javascriptv3/example_code/glue/scenarios/basic/steps/create-crawler.js b/javascriptv3/example_code/glue/scenarios/basic/steps/create-crawler.js index f3957a8212c..da775f65c5c 100644 --- a/javascriptv3/example_code/glue/scenarios/basic/steps/create-crawler.js +++ b/javascriptv3/example_code/glue/scenarios/basic/steps/create-crawler.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { log } from "../log.js"; /** snippet-start:[javascript.v3.glue.scenarios.basic.CreateCrawlerStep] */ diff --git a/javascriptv3/example_code/glue/scenarios/basic/steps/create-job.js b/javascriptv3/example_code/glue/scenarios/basic/steps/create-job.js index 41dd9e20dc2..9735dab4df7 100644 --- a/javascriptv3/example_code/glue/scenarios/basic/steps/create-job.js +++ b/javascriptv3/example_code/glue/scenarios/basic/steps/create-job.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { log } from "../log.js"; diff --git a/javascriptv3/example_code/glue/scenarios/basic/steps/delete-stack-reminder.js b/javascriptv3/example_code/glue/scenarios/basic/steps/delete-stack-reminder.js index d7b308b7f69..a79c5b0e235 100644 --- a/javascriptv3/example_code/glue/scenarios/basic/steps/delete-stack-reminder.js +++ b/javascriptv3/example_code/glue/scenarios/basic/steps/delete-stack-reminder.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { log } from "../log.js"; diff --git a/javascriptv3/example_code/glue/scenarios/basic/steps/get-database.js b/javascriptv3/example_code/glue/scenarios/basic/steps/get-database.js index 3b9b2c4f443..ddd0484086e 100644 --- a/javascriptv3/example_code/glue/scenarios/basic/steps/get-database.js +++ b/javascriptv3/example_code/glue/scenarios/basic/steps/get-database.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { log } from "../log.js"; diff --git a/javascriptv3/example_code/glue/scenarios/basic/steps/get-tables.js b/javascriptv3/example_code/glue/scenarios/basic/steps/get-tables.js index c1a912bed97..aca5a7be4b5 100644 --- a/javascriptv3/example_code/glue/scenarios/basic/steps/get-tables.js +++ b/javascriptv3/example_code/glue/scenarios/basic/steps/get-tables.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { log } from "../log.js"; diff --git a/javascriptv3/example_code/glue/scenarios/basic/steps/pick-job-run.js b/javascriptv3/example_code/glue/scenarios/basic/steps/pick-job-run.js index 6a6c5e6ee13..0a91415501d 100644 --- a/javascriptv3/example_code/glue/scenarios/basic/steps/pick-job-run.js +++ b/javascriptv3/example_code/glue/scenarios/basic/steps/pick-job-run.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { log } from "../log.js"; diff --git a/javascriptv3/example_code/glue/scenarios/basic/steps/pick-job.js b/javascriptv3/example_code/glue/scenarios/basic/steps/pick-job.js index 9b47deddccd..f580e130653 100644 --- a/javascriptv3/example_code/glue/scenarios/basic/steps/pick-job.js +++ b/javascriptv3/example_code/glue/scenarios/basic/steps/pick-job.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 const makePickJobStep = diff --git a/javascriptv3/example_code/glue/scenarios/basic/steps/start-crawler.js b/javascriptv3/example_code/glue/scenarios/basic/steps/start-crawler.js index 2dca754fced..ca237314522 100644 --- a/javascriptv3/example_code/glue/scenarios/basic/steps/start-crawler.js +++ b/javascriptv3/example_code/glue/scenarios/basic/steps/start-crawler.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { wait } from "@aws-sdk-examples/libs/utils/util-timers.js"; import { log } from "../log.js"; diff --git a/javascriptv3/example_code/glue/scenarios/basic/steps/start-job-run.js b/javascriptv3/example_code/glue/scenarios/basic/steps/start-job-run.js index 065d753057a..58068d67033 100644 --- a/javascriptv3/example_code/glue/scenarios/basic/steps/start-job-run.js +++ b/javascriptv3/example_code/glue/scenarios/basic/steps/start-job-run.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import open from "open"; import { wait } from "@aws-sdk-examples/libs/utils/util-timers.js"; diff --git a/javascriptv3/example_code/glue/scenarios/basic/steps/validate-env.js b/javascriptv3/example_code/glue/scenarios/basic/steps/validate-env.js index 239c58cbd4f..72c13969c0c 100644 --- a/javascriptv3/example_code/glue/scenarios/basic/steps/validate-env.js +++ b/javascriptv3/example_code/glue/scenarios/basic/steps/validate-env.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { log } from "../log.js"; const keys = [ diff --git a/javascriptv3/example_code/glue/scenarios/basic/steps/validate-python-script.js b/javascriptv3/example_code/glue/scenarios/basic/steps/validate-python-script.js index f8210fa97ac..c51dfdbca14 100644 --- a/javascriptv3/example_code/glue/scenarios/basic/steps/validate-python-script.js +++ b/javascriptv3/example_code/glue/scenarios/basic/steps/validate-python-script.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { log } from "../log.js"; diff --git a/javascriptv3/example_code/glue/tests/actions.integration.test.js b/javascriptv3/example_code/glue/tests/actions.integration.test.js index 4446592048a..41f288712b9 100644 --- a/javascriptv3/example_code/glue/tests/actions.integration.test.js +++ b/javascriptv3/example_code/glue/tests/actions.integration.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { readFile } from "fs/promises"; import { describe, it, expect, beforeAll, afterAll } from "vitest"; diff --git a/javascriptv3/example_code/glue/tests/clean-up-crawler.unit.test.js b/javascriptv3/example_code/glue/tests/clean-up-crawler.unit.test.js index c6a42d21246..5c9e78a3091 100644 --- a/javascriptv3/example_code/glue/tests/clean-up-crawler.unit.test.js +++ b/javascriptv3/example_code/glue/tests/clean-up-crawler.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; import { GlueClient, DeleteCrawlerCommand } from "@aws-sdk/client-glue"; diff --git a/javascriptv3/example_code/glue/tests/clean-up-databases.unit.test.js b/javascriptv3/example_code/glue/tests/clean-up-databases.unit.test.js index 7b3ae8c690b..434dba79cbd 100644 --- a/javascriptv3/example_code/glue/tests/clean-up-databases.unit.test.js +++ b/javascriptv3/example_code/glue/tests/clean-up-databases.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; import { makeCleanUpDatabasesStep } from "../scenarios/basic/steps/clean-up-databases.js"; diff --git a/javascriptv3/example_code/glue/tests/clean-up-jobs.unit.test.js b/javascriptv3/example_code/glue/tests/clean-up-jobs.unit.test.js index 1334bbdd009..2f859b94648 100644 --- a/javascriptv3/example_code/glue/tests/clean-up-jobs.unit.test.js +++ b/javascriptv3/example_code/glue/tests/clean-up-jobs.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { it, describe, vi, expect } from "vitest"; import { makeCleanUpJobsStep } from "../scenarios/basic/steps/clean-up-jobs.js"; diff --git a/javascriptv3/example_code/glue/tests/clean-up-tables.unit.test.js b/javascriptv3/example_code/glue/tests/clean-up-tables.unit.test.js index 5df36ea8f79..140f339e847 100644 --- a/javascriptv3/example_code/glue/tests/clean-up-tables.unit.test.js +++ b/javascriptv3/example_code/glue/tests/clean-up-tables.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { it, describe, vi, expect } from "vitest"; import { makeCleanUpTablesStep } from "../scenarios/basic/steps/clean-up-tables.js"; diff --git a/javascriptv3/example_code/glue/tests/create-crawler.unit.test.js b/javascriptv3/example_code/glue/tests/create-crawler.unit.test.js index 9739ee9525c..15edc284012 100644 --- a/javascriptv3/example_code/glue/tests/create-crawler.unit.test.js +++ b/javascriptv3/example_code/glue/tests/create-crawler.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { makeCreateCrawlerStep } from "../scenarios/basic/steps/create-crawler.js"; diff --git a/javascriptv3/example_code/glue/tests/create-job.unit.test.js b/javascriptv3/example_code/glue/tests/create-job.unit.test.js index 81d281deb8f..4be35885095 100644 --- a/javascriptv3/example_code/glue/tests/create-job.unit.test.js +++ b/javascriptv3/example_code/glue/tests/create-job.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { makeCreateJobStep } from "../scenarios/basic/steps/create-job.js"; diff --git a/javascriptv3/example_code/glue/tests/get-database.unit.test.js b/javascriptv3/example_code/glue/tests/get-database.unit.test.js index 01b778f5abc..bb479149ed6 100644 --- a/javascriptv3/example_code/glue/tests/get-database.unit.test.js +++ b/javascriptv3/example_code/glue/tests/get-database.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { makeGetDatabaseStep } from "../scenarios/basic/steps/get-database.js"; diff --git a/javascriptv3/example_code/glue/tests/get-tables.unit.test.js b/javascriptv3/example_code/glue/tests/get-tables.unit.test.js index c63b13d7392..242ac406353 100644 --- a/javascriptv3/example_code/glue/tests/get-tables.unit.test.js +++ b/javascriptv3/example_code/glue/tests/get-tables.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/glue/tests/mock-prompter.js b/javascriptv3/example_code/glue/tests/mock-prompter.js index 514ab71454c..e4762a70ac7 100644 --- a/javascriptv3/example_code/glue/tests/mock-prompter.js +++ b/javascriptv3/example_code/glue/tests/mock-prompter.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { vi } from "vitest"; diff --git a/javascriptv3/example_code/glue/tests/pick-job-run.unit.test.js b/javascriptv3/example_code/glue/tests/pick-job-run.unit.test.js index d9f50d9b8c6..17f35f7ac28 100644 --- a/javascriptv3/example_code/glue/tests/pick-job-run.unit.test.js +++ b/javascriptv3/example_code/glue/tests/pick-job-run.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { mockPrompter } from "./mock-prompter.js"; diff --git a/javascriptv3/example_code/glue/tests/start-crawler.unit.test.js b/javascriptv3/example_code/glue/tests/start-crawler.unit.test.js index e65cf626c7c..ad8a8b00783 100644 --- a/javascriptv3/example_code/glue/tests/start-crawler.unit.test.js +++ b/javascriptv3/example_code/glue/tests/start-crawler.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/glue/tests/start-job-run.unit.test.js b/javascriptv3/example_code/glue/tests/start-job-run.unit.test.js index e0b259d0b30..3b1487eccd8 100644 --- a/javascriptv3/example_code/glue/tests/start-job-run.unit.test.js +++ b/javascriptv3/example_code/glue/tests/start-job-run.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/glue/tests/validate-env.unit.test.js b/javascriptv3/example_code/glue/tests/validate-env.unit.test.js index 61a17cf8d0d..2c74777c0b3 100644 --- a/javascriptv3/example_code/glue/tests/validate-env.unit.test.js +++ b/javascriptv3/example_code/glue/tests/validate-env.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, beforeAll } from "vitest"; import { validateEnv, keys } from "../scenarios/basic/steps/validate-env.js"; diff --git a/javascriptv3/example_code/glue/tests/validate-python-script.unit.test.js b/javascriptv3/example_code/glue/tests/validate-python-script.unit.test.js index 46a18abfcc3..d8657a6a929 100644 --- a/javascriptv3/example_code/glue/tests/validate-python-script.unit.test.js +++ b/javascriptv3/example_code/glue/tests/validate-python-script.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { makeValidatePythonScriptStep } from "../scenarios/basic/steps/validate-python-script.js"; diff --git a/javascriptv3/example_code/glue/vite.config.js b/javascriptv3/example_code/glue/vite.config.js index 019dbc2b65c..4840d2c99fc 100644 --- a/javascriptv3/example_code/glue/vite.config.js +++ b/javascriptv3/example_code/glue/vite.config.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { defineConfig } from "vitest/config"; diff --git a/javascriptv3/example_code/iam/actions/attach-role-policy.js b/javascriptv3/example_code/iam/actions/attach-role-policy.js index 0c0118d0dd9..7f1ded15052 100644 --- a/javascriptv3/example_code/iam/actions/attach-role-policy.js +++ b/javascriptv3/example_code/iam/actions/attach-role-policy.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/create-access-key.js b/javascriptv3/example_code/iam/actions/create-access-key.js index 49790e26291..41f8ce36378 100644 --- a/javascriptv3/example_code/iam/actions/create-access-key.js +++ b/javascriptv3/example_code/iam/actions/create-access-key.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/create-account-alias.js b/javascriptv3/example_code/iam/actions/create-account-alias.js index 8f7f2112c95..8187aed0ba7 100644 --- a/javascriptv3/example_code/iam/actions/create-account-alias.js +++ b/javascriptv3/example_code/iam/actions/create-account-alias.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/create-group.js b/javascriptv3/example_code/iam/actions/create-group.js index 74a18b787df..64f38d1ecc8 100644 --- a/javascriptv3/example_code/iam/actions/create-group.js +++ b/javascriptv3/example_code/iam/actions/create-group.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/create-policy.js b/javascriptv3/example_code/iam/actions/create-policy.js index 48beacd0ce4..28562eab29c 100644 --- a/javascriptv3/example_code/iam/actions/create-policy.js +++ b/javascriptv3/example_code/iam/actions/create-policy.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/create-role.js b/javascriptv3/example_code/iam/actions/create-role.js index 57b5cd2d4cd..fcde0ea9c3c 100644 --- a/javascriptv3/example_code/iam/actions/create-role.js +++ b/javascriptv3/example_code/iam/actions/create-role.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/create-saml-provider.js b/javascriptv3/example_code/iam/actions/create-saml-provider.js index 4a8f775b3b5..699bb469ddc 100644 --- a/javascriptv3/example_code/iam/actions/create-saml-provider.js +++ b/javascriptv3/example_code/iam/actions/create-saml-provider.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/create-service-linked-role.js b/javascriptv3/example_code/iam/actions/create-service-linked-role.js index bcc536b0c4b..754dfa5b473 100644 --- a/javascriptv3/example_code/iam/actions/create-service-linked-role.js +++ b/javascriptv3/example_code/iam/actions/create-service-linked-role.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/create-user.js b/javascriptv3/example_code/iam/actions/create-user.js index 01ee53b20e7..65a4a18a64f 100644 --- a/javascriptv3/example_code/iam/actions/create-user.js +++ b/javascriptv3/example_code/iam/actions/create-user.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/delete-access-key.js b/javascriptv3/example_code/iam/actions/delete-access-key.js index 284f1f5290d..37fd74f894d 100644 --- a/javascriptv3/example_code/iam/actions/delete-access-key.js +++ b/javascriptv3/example_code/iam/actions/delete-access-key.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/delete-account-alias.js b/javascriptv3/example_code/iam/actions/delete-account-alias.js index 12d942100a4..45ba77d2bf4 100644 --- a/javascriptv3/example_code/iam/actions/delete-account-alias.js +++ b/javascriptv3/example_code/iam/actions/delete-account-alias.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/delete-group.js b/javascriptv3/example_code/iam/actions/delete-group.js index c323f8ed755..fb890d6036e 100644 --- a/javascriptv3/example_code/iam/actions/delete-group.js +++ b/javascriptv3/example_code/iam/actions/delete-group.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/delete-policy.js b/javascriptv3/example_code/iam/actions/delete-policy.js index 66c1ae68b0c..69810faad6e 100644 --- a/javascriptv3/example_code/iam/actions/delete-policy.js +++ b/javascriptv3/example_code/iam/actions/delete-policy.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/delete-role-policy.js b/javascriptv3/example_code/iam/actions/delete-role-policy.js index 5db588ddd95..82201d3e202 100644 --- a/javascriptv3/example_code/iam/actions/delete-role-policy.js +++ b/javascriptv3/example_code/iam/actions/delete-role-policy.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/delete-role.js b/javascriptv3/example_code/iam/actions/delete-role.js index 8a1713ce215..5db5278e5a4 100644 --- a/javascriptv3/example_code/iam/actions/delete-role.js +++ b/javascriptv3/example_code/iam/actions/delete-role.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/delete-saml-provider.js b/javascriptv3/example_code/iam/actions/delete-saml-provider.js index e6bf9d49a48..61d32c882d5 100644 --- a/javascriptv3/example_code/iam/actions/delete-saml-provider.js +++ b/javascriptv3/example_code/iam/actions/delete-saml-provider.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/delete-server-certificate.js b/javascriptv3/example_code/iam/actions/delete-server-certificate.js index 2cf10c417b5..913df3ecda9 100644 --- a/javascriptv3/example_code/iam/actions/delete-server-certificate.js +++ b/javascriptv3/example_code/iam/actions/delete-server-certificate.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/delete-service-linked-role.js b/javascriptv3/example_code/iam/actions/delete-service-linked-role.js index 8521ecf3d3a..4dabda19143 100644 --- a/javascriptv3/example_code/iam/actions/delete-service-linked-role.js +++ b/javascriptv3/example_code/iam/actions/delete-service-linked-role.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/delete-user.js b/javascriptv3/example_code/iam/actions/delete-user.js index 22d5e051a7b..ca4fda6d788 100644 --- a/javascriptv3/example_code/iam/actions/delete-user.js +++ b/javascriptv3/example_code/iam/actions/delete-user.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/detach-role-policy.js b/javascriptv3/example_code/iam/actions/detach-role-policy.js index 1bd7c82d2f9..c3da55d7aa2 100644 --- a/javascriptv3/example_code/iam/actions/detach-role-policy.js +++ b/javascriptv3/example_code/iam/actions/detach-role-policy.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/get-access-key-last-used.js b/javascriptv3/example_code/iam/actions/get-access-key-last-used.js index ef46c58fc6d..a1d6ba70c37 100644 --- a/javascriptv3/example_code/iam/actions/get-access-key-last-used.js +++ b/javascriptv3/example_code/iam/actions/get-access-key-last-used.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/get-account-password-policy.js b/javascriptv3/example_code/iam/actions/get-account-password-policy.js index 97641a30add..6aa34ad2072 100644 --- a/javascriptv3/example_code/iam/actions/get-account-password-policy.js +++ b/javascriptv3/example_code/iam/actions/get-account-password-policy.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/get-policy.js b/javascriptv3/example_code/iam/actions/get-policy.js index 8e4148243e1..c530193b209 100644 --- a/javascriptv3/example_code/iam/actions/get-policy.js +++ b/javascriptv3/example_code/iam/actions/get-policy.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/get-role.js b/javascriptv3/example_code/iam/actions/get-role.js index 80bd2e6cfb7..b51a23867ca 100644 --- a/javascriptv3/example_code/iam/actions/get-role.js +++ b/javascriptv3/example_code/iam/actions/get-role.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/get-server-certificate.js b/javascriptv3/example_code/iam/actions/get-server-certificate.js index 65ec8fb0435..84e1de9435a 100644 --- a/javascriptv3/example_code/iam/actions/get-server-certificate.js +++ b/javascriptv3/example_code/iam/actions/get-server-certificate.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/get-service-linked-role-deletion-status.js b/javascriptv3/example_code/iam/actions/get-service-linked-role-deletion-status.js index b7ac2076f2e..f8022e64c0f 100644 --- a/javascriptv3/example_code/iam/actions/get-service-linked-role-deletion-status.js +++ b/javascriptv3/example_code/iam/actions/get-service-linked-role-deletion-status.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/list-access-keys.js b/javascriptv3/example_code/iam/actions/list-access-keys.js index 9b38578cafc..57e78437ccc 100644 --- a/javascriptv3/example_code/iam/actions/list-access-keys.js +++ b/javascriptv3/example_code/iam/actions/list-access-keys.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/list-account-aliases.js b/javascriptv3/example_code/iam/actions/list-account-aliases.js index faca426a00a..7a16cb31420 100644 --- a/javascriptv3/example_code/iam/actions/list-account-aliases.js +++ b/javascriptv3/example_code/iam/actions/list-account-aliases.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/list-attached-role-policies.js b/javascriptv3/example_code/iam/actions/list-attached-role-policies.js index 7bb559b18e0..d02e491be6c 100644 --- a/javascriptv3/example_code/iam/actions/list-attached-role-policies.js +++ b/javascriptv3/example_code/iam/actions/list-attached-role-policies.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/list-groups.js b/javascriptv3/example_code/iam/actions/list-groups.js index 853ed59947b..3f328c0d85e 100644 --- a/javascriptv3/example_code/iam/actions/list-groups.js +++ b/javascriptv3/example_code/iam/actions/list-groups.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/list-policies.js b/javascriptv3/example_code/iam/actions/list-policies.js index 37c6b3bd31c..f802143d82a 100644 --- a/javascriptv3/example_code/iam/actions/list-policies.js +++ b/javascriptv3/example_code/iam/actions/list-policies.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/list-role-policies.js b/javascriptv3/example_code/iam/actions/list-role-policies.js index 989701f1776..1cf5edd01bc 100644 --- a/javascriptv3/example_code/iam/actions/list-role-policies.js +++ b/javascriptv3/example_code/iam/actions/list-role-policies.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/list-roles.js b/javascriptv3/example_code/iam/actions/list-roles.js index 60d34c9a05f..35265ecb116 100644 --- a/javascriptv3/example_code/iam/actions/list-roles.js +++ b/javascriptv3/example_code/iam/actions/list-roles.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/list-saml-providers.js b/javascriptv3/example_code/iam/actions/list-saml-providers.js index 887e07a2ad2..39164315eb6 100644 --- a/javascriptv3/example_code/iam/actions/list-saml-providers.js +++ b/javascriptv3/example_code/iam/actions/list-saml-providers.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/list-server-certificates.js b/javascriptv3/example_code/iam/actions/list-server-certificates.js index 3e5a39dff25..49544b031d5 100644 --- a/javascriptv3/example_code/iam/actions/list-server-certificates.js +++ b/javascriptv3/example_code/iam/actions/list-server-certificates.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/list-users.js b/javascriptv3/example_code/iam/actions/list-users.js index 1c56b94b774..53cbc977ce4 100644 --- a/javascriptv3/example_code/iam/actions/list-users.js +++ b/javascriptv3/example_code/iam/actions/list-users.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/put-role-policy.js b/javascriptv3/example_code/iam/actions/put-role-policy.js index b99dd23dfb7..e208bfcfca8 100644 --- a/javascriptv3/example_code/iam/actions/put-role-policy.js +++ b/javascriptv3/example_code/iam/actions/put-role-policy.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/update-access-key.js b/javascriptv3/example_code/iam/actions/update-access-key.js index 8229eb78800..147e0eea202 100644 --- a/javascriptv3/example_code/iam/actions/update-access-key.js +++ b/javascriptv3/example_code/iam/actions/update-access-key.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/update-server-certificate.js b/javascriptv3/example_code/iam/actions/update-server-certificate.js index 649cff8631e..55203f6613a 100644 --- a/javascriptv3/example_code/iam/actions/update-server-certificate.js +++ b/javascriptv3/example_code/iam/actions/update-server-certificate.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/update-user.js b/javascriptv3/example_code/iam/actions/update-user.js index c0ecca87a58..331fb163454 100644 --- a/javascriptv3/example_code/iam/actions/update-user.js +++ b/javascriptv3/example_code/iam/actions/update-user.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/actions/upload-server-certificate.js b/javascriptv3/example_code/iam/actions/upload-server-certificate.js index ab1ca9b17a2..2bd7fb165ac 100644 --- a/javascriptv3/example_code/iam/actions/upload-server-certificate.js +++ b/javascriptv3/example_code/iam/actions/upload-server-certificate.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/client.js b/javascriptv3/example_code/iam/client.js index 8d278aa4d26..77f4d117482 100644 --- a/javascriptv3/example_code/iam/client.js +++ b/javascriptv3/example_code/iam/client.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[iam.JavaScript.createclientv3] import { IAMClient } from "@aws-sdk/client-iam"; diff --git a/javascriptv3/example_code/iam/hello.js b/javascriptv3/example_code/iam/hello.js index fdcc6407dd9..c24aa472e64 100644 --- a/javascriptv3/example_code/iam/hello.js +++ b/javascriptv3/example_code/iam/hello.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/scenarios/basic.js b/javascriptv3/example_code/iam/scenarios/basic.js index 9c150b835e9..78463046069 100644 --- a/javascriptv3/example_code/iam/scenarios/basic.js +++ b/javascriptv3/example_code/iam/scenarios/basic.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/iam/tests/account-alias.integration.test.js b/javascriptv3/example_code/iam/tests/account-alias.integration.test.js index b6f7874a927..aaa89c2ec5b 100644 --- a/javascriptv3/example_code/iam/tests/account-alias.integration.test.js +++ b/javascriptv3/example_code/iam/tests/account-alias.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { createAccountAlias } from "../actions/create-account-alias.js"; diff --git a/javascriptv3/example_code/iam/tests/basic.integration.test.js b/javascriptv3/example_code/iam/tests/basic.integration.test.js index ff7927b8d52..bac87f63c26 100644 --- a/javascriptv3/example_code/iam/tests/basic.integration.test.js +++ b/javascriptv3/example_code/iam/tests/basic.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it } from "vitest"; import { main } from "../scenarios/basic.js"; diff --git a/javascriptv3/example_code/iam/tests/client.integration.test.js b/javascriptv3/example_code/iam/tests/client.integration.test.js index d9a4d312f60..99896df360d 100644 --- a/javascriptv3/example_code/iam/tests/client.integration.test.js +++ b/javascriptv3/example_code/iam/tests/client.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it } from "vitest"; import { client } from "../client.js"; import { ListUsersCommand } from "@aws-sdk/client-iam"; diff --git a/javascriptv3/example_code/iam/tests/get-account-password-policy.integration.test.js b/javascriptv3/example_code/iam/tests/get-account-password-policy.integration.test.js index 2e3b8df63fe..2b30cbe2b20 100644 --- a/javascriptv3/example_code/iam/tests/get-account-password-policy.integration.test.js +++ b/javascriptv3/example_code/iam/tests/get-account-password-policy.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { getAccountPasswordPolicy } from "../actions/get-account-password-policy.js"; diff --git a/javascriptv3/example_code/iam/tests/hello.integration.test.js b/javascriptv3/example_code/iam/tests/hello.integration.test.js index 10bbe9152f7..2b1e53f1e81 100644 --- a/javascriptv3/example_code/iam/tests/hello.integration.test.js +++ b/javascriptv3/example_code/iam/tests/hello.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vitest } from "vitest"; import { getUniqueName } from "@aws-sdk-examples/libs/utils/util-string.js"; import { createPolicy } from "../actions/create-policy.js"; diff --git a/javascriptv3/example_code/iam/tests/list-groups.integration.test.js b/javascriptv3/example_code/iam/tests/list-groups.integration.test.js index 69941987c75..a184ee828f3 100644 --- a/javascriptv3/example_code/iam/tests/list-groups.integration.test.js +++ b/javascriptv3/example_code/iam/tests/list-groups.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vitest, beforeAll, afterAll } from "vitest"; import { listGroups } from "../actions/list-groups.js"; import { getUniqueName } from "@aws-sdk-examples/libs/utils/util-string.js"; diff --git a/javascriptv3/example_code/iam/tests/role-and-policy.integration.test.js b/javascriptv3/example_code/iam/tests/role-and-policy.integration.test.js index 011964a3054..2df3a3f77ea 100644 --- a/javascriptv3/example_code/iam/tests/role-and-policy.integration.test.js +++ b/javascriptv3/example_code/iam/tests/role-and-policy.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { getUniqueName } from "@aws-sdk-examples/libs/utils/util-string.js"; diff --git a/javascriptv3/example_code/iam/tests/saml-provider.integration.test.js b/javascriptv3/example_code/iam/tests/saml-provider.integration.test.js index 40848995d6e..1dfc5163634 100644 --- a/javascriptv3/example_code/iam/tests/saml-provider.integration.test.js +++ b/javascriptv3/example_code/iam/tests/saml-provider.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { getUniqueName } from "@aws-sdk-examples/libs/utils/util-string.js"; import { describe, it, expect } from "vitest"; import { createSAMLProvider } from "../actions/create-saml-provider.js"; diff --git a/javascriptv3/example_code/iam/tests/service-linked-role.integration.test.js b/javascriptv3/example_code/iam/tests/service-linked-role.integration.test.js index 873c3e59fbc..20f1beb6dd4 100644 --- a/javascriptv3/example_code/iam/tests/service-linked-role.integration.test.js +++ b/javascriptv3/example_code/iam/tests/service-linked-role.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { createServiceLinkedRole } from "../actions/create-service-linked-role.js"; diff --git a/javascriptv3/example_code/iam/tests/user-and-access-key.integration.test.js b/javascriptv3/example_code/iam/tests/user-and-access-key.integration.test.js index 893847e1b72..28a7a0df9b7 100644 --- a/javascriptv3/example_code/iam/tests/user-and-access-key.integration.test.js +++ b/javascriptv3/example_code/iam/tests/user-and-access-key.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { StatusType } from "@aws-sdk/client-iam"; diff --git a/javascriptv3/example_code/iam/vite.config.js b/javascriptv3/example_code/iam/vite.config.js index 227661def32..c5cc83c928b 100644 --- a/javascriptv3/example_code/iam/vite.config.js +++ b/javascriptv3/example_code/iam/vite.config.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { defineConfig } from "vitest/config"; diff --git a/javascriptv3/example_code/kinesis/src/kinesis-example.js b/javascriptv3/example_code/kinesis/src/kinesis-example.js index c74f198bdec..418b9132d97 100644 --- a/javascriptv3/example_code/kinesis/src/kinesis-example.js +++ b/javascriptv3/example_code/kinesis/src/kinesis-example.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/kinesis/src/libs/kinesisClient.js b/javascriptv3/example_code/kinesis/src/libs/kinesisClient.js index 3cefc1e7b5d..ff6277f702e 100644 --- a/javascriptv3/example_code/kinesis/src/libs/kinesisClient.js +++ b/javascriptv3/example_code/kinesis/src/libs/kinesisClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/kinesis-examples-capturing-page-scrolling.html. diff --git a/javascriptv3/example_code/lambda/actions/create-function.js b/javascriptv3/example_code/lambda/actions/create-function.js index e7413bb632d..28377fb96b1 100644 --- a/javascriptv3/example_code/lambda/actions/create-function.js +++ b/javascriptv3/example_code/lambda/actions/create-function.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { Architecture, CreateFunctionCommand, diff --git a/javascriptv3/example_code/lambda/actions/delete-function.js b/javascriptv3/example_code/lambda/actions/delete-function.js index 1bc46531c7b..9342d7a049b 100644 --- a/javascriptv3/example_code/lambda/actions/delete-function.js +++ b/javascriptv3/example_code/lambda/actions/delete-function.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { LambdaClient, DeleteFunctionCommand } from "@aws-sdk/client-lambda"; /** snippet-start:[javascript.v3.lambda.actions.DeleteFunction] */ diff --git a/javascriptv3/example_code/lambda/actions/get-function.js b/javascriptv3/example_code/lambda/actions/get-function.js index 42e4da8c70e..13880991eca 100644 --- a/javascriptv3/example_code/lambda/actions/get-function.js +++ b/javascriptv3/example_code/lambda/actions/get-function.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { LambdaClient, GetFunctionCommand } from "@aws-sdk/client-lambda"; /** snippet-start:[javascript.v3.lambda.actions.GetFunction] */ diff --git a/javascriptv3/example_code/lambda/actions/invoke.js b/javascriptv3/example_code/lambda/actions/invoke.js index 725e4fe611f..84596bb9c56 100644 --- a/javascriptv3/example_code/lambda/actions/invoke.js +++ b/javascriptv3/example_code/lambda/actions/invoke.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { InvokeCommand, LambdaClient, LogType } from "@aws-sdk/client-lambda"; /** snippet-start:[javascript.v3.lambda.actions.Invoke] */ diff --git a/javascriptv3/example_code/lambda/actions/list-functions.js b/javascriptv3/example_code/lambda/actions/list-functions.js index c8817eb3888..a7782b34117 100644 --- a/javascriptv3/example_code/lambda/actions/list-functions.js +++ b/javascriptv3/example_code/lambda/actions/list-functions.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { LambdaClient, ListFunctionsCommand } from "@aws-sdk/client-lambda"; /** snippet-start:[javascript.v3.lambda.actions.ListFunctions] **/ diff --git a/javascriptv3/example_code/lambda/actions/update-function-code.js b/javascriptv3/example_code/lambda/actions/update-function-code.js index 6bfc702534e..9904b80527d 100644 --- a/javascriptv3/example_code/lambda/actions/update-function-code.js +++ b/javascriptv3/example_code/lambda/actions/update-function-code.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { LambdaClient, UpdateFunctionCodeCommand, diff --git a/javascriptv3/example_code/lambda/actions/update-function-configuration.js b/javascriptv3/example_code/lambda/actions/update-function-configuration.js index f03ec5dc876..454e1959c42 100644 --- a/javascriptv3/example_code/lambda/actions/update-function-configuration.js +++ b/javascriptv3/example_code/lambda/actions/update-function-configuration.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { LambdaClient, UpdateFunctionConfigurationCommand, diff --git a/javascriptv3/example_code/lambda/guide_supplements/guide-cdk-lambda-function.js b/javascriptv3/example_code/lambda/guide_supplements/guide-cdk-lambda-function.js index e65a2eb1d82..3d010d130e3 100644 --- a/javascriptv3/example_code/lambda/guide_supplements/guide-cdk-lambda-function.js +++ b/javascriptv3/example_code/lambda/guide_supplements/guide-cdk-lambda-function.js @@ -1,9 +1,7 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -//snippet-start:[javascript.v3.cross_service.supplement.list_widgets] +// snippet-start:[javascript.v3.cross_service.supplement.list_widgets] import { S3Client, ListObjectsCommand } from "@aws-sdk/client-s3"; // The following code uses the AWS SDK for JavaScript (v3). @@ -104,4 +102,4 @@ export const handler = async (event) => { return buildResponseBody(500, err.message || "Unknown server error"); } }; -//snippet-end:[javascript.v3.cross_service.supplement.list_widgets] +// snippet-end:[javascript.v3.cross_service.supplement.list_widgets] diff --git a/javascriptv3/example_code/lambda/hello.js b/javascriptv3/example_code/lambda/hello.js index 38310df7c63..765668284e7 100644 --- a/javascriptv3/example_code/lambda/hello.js +++ b/javascriptv3/example_code/lambda/hello.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/clean-up-handler.js b/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/clean-up-handler.js index 72706b8d51d..b405d9ac4e6 100644 --- a/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/clean-up-handler.js +++ b/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/clean-up-handler.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { readdirSync } from "fs"; import { log } from "@aws-sdk-examples/libs/utils/util-log.js"; import { diff --git a/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/constants.js b/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/constants.js index 10e197a7389..c45a8713afa 100644 --- a/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/constants.js +++ b/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/constants.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 const NAME_ROLE_LAMBDA = "lambda-scenarios-basic"; const ARN_POLICY_LAMBDA_BASIC_EXECUTION = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"; diff --git a/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/create-function-handler.js b/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/create-function-handler.js index 71856de5b56..42d9e9f7be0 100644 --- a/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/create-function-handler.js +++ b/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/create-function-handler.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { log } from "@aws-sdk-examples/libs/utils/util-log.js"; import { getTmp } from "@aws-sdk-examples/libs/utils/util-fs.js"; import { createFunction } from "../../../actions/create-function.js"; diff --git a/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/initialize-handler.js b/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/initialize-handler.js index 55306a28aad..4af87def530 100644 --- a/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/initialize-handler.js +++ b/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/initialize-handler.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { log } from "@aws-sdk-examples/libs/utils/util-log.js"; import { getTmp, setTmp } from "@aws-sdk-examples/libs/utils/util-fs.js"; import { attachRolePolicy } from "../../../../iam/actions/attach-role-policy.js"; diff --git a/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/invoke-handler.js b/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/invoke-handler.js index 9179ae7e50a..b140b9ecd65 100644 --- a/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/invoke-handler.js +++ b/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/invoke-handler.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { log } from "@aws-sdk-examples/libs/utils/util-log.js"; import { invoke } from "../../../actions/invoke.js"; diff --git a/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/list-functions-handler.js b/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/list-functions-handler.js index 42bf0702bee..4049e6196d4 100644 --- a/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/list-functions-handler.js +++ b/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/list-functions-handler.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { log } from "@aws-sdk-examples/libs/utils/util-log.js"; import { listFunctions } from "../../../actions/list-functions.js"; diff --git a/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/update-function-code-handler.js b/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/update-function-code-handler.js index d4301182932..75970e951d1 100644 --- a/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/update-function-code-handler.js +++ b/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/update-function-code-handler.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { log } from "@aws-sdk-examples/libs/utils/util-log.js"; import { updateFunctionCode } from "../../../actions/update-function-code.js"; diff --git a/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/update-function-configuration-handler.js b/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/update-function-configuration-handler.js index 5a3e61afef0..79e7a81bb78 100644 --- a/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/update-function-configuration-handler.js +++ b/javascriptv3/example_code/lambda/scenarios/basic/command-handlers/update-function-configuration-handler.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { log } from "@aws-sdk-examples/libs/utils/util-log.js"; import { updateFunctionConfiguration } from "../../../actions/update-function-configuration.js"; diff --git a/javascriptv3/example_code/lambda/scenarios/basic/index.js b/javascriptv3/example_code/lambda/scenarios/basic/index.js index fdd98480801..438bbde7807 100644 --- a/javascriptv3/example_code/lambda/scenarios/basic/index.js +++ b/javascriptv3/example_code/lambda/scenarios/basic/index.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { createInterface } from "readline"; import { stdin as input, stdout as output } from "process"; diff --git a/javascriptv3/example_code/lambda/tests/guide-cdk-lambda-function.unit.test.js b/javascriptv3/example_code/lambda/tests/guide-cdk-lambda-function.unit.test.js index 5ce442d656d..0e49da5d0fd 100644 --- a/javascriptv3/example_code/lambda/tests/guide-cdk-lambda-function.unit.test.js +++ b/javascriptv3/example_code/lambda/tests/guide-cdk-lambda-function.unit.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; const mockSendFn = vi.fn(); diff --git a/javascriptv3/example_code/lambda/tests/lambda-actions.integration.test.js b/javascriptv3/example_code/lambda/tests/lambda-actions.integration.test.js index 55c59611ce2..55026f3f56b 100644 --- a/javascriptv3/example_code/lambda/tests/lambda-actions.integration.test.js +++ b/javascriptv3/example_code/lambda/tests/lambda-actions.integration.test.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, beforeAll, afterAll, expect } from "vitest"; import { IAMClient, diff --git a/javascriptv3/example_code/lambda/vite.config.ts b/javascriptv3/example_code/lambda/vite.config.ts index d88efe3b2cc..548525f664d 100644 --- a/javascriptv3/example_code/lambda/vite.config.ts +++ b/javascriptv3/example_code/lambda/vite.config.ts @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { defineConfig } from "vitest/config"; diff --git a/javascriptv3/example_code/lambda/waiters/index.js b/javascriptv3/example_code/lambda/waiters/index.js index cc27f647726..20a2fe8a541 100644 --- a/javascriptv3/example_code/lambda/waiters/index.js +++ b/javascriptv3/example_code/lambda/waiters/index.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { LambdaClient, waitUntilFunctionActive, diff --git a/javascriptv3/example_code/libs/cmd-runner.js b/javascriptv3/example_code/libs/cmd-runner.js index 73348927a2f..9ec02f06e98 100644 --- a/javascriptv3/example_code/libs/cmd-runner.js +++ b/javascriptv3/example_code/libs/cmd-runner.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { startsWith } from "./utils/util-array.js"; import { log } from "./utils/util-log.js"; diff --git a/javascriptv3/example_code/libs/logger.js b/javascriptv3/example_code/libs/logger.js index 4026f5aaf40..295e4817cb4 100644 --- a/javascriptv3/example_code/libs/logger.js +++ b/javascriptv3/example_code/libs/logger.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import wrap from "fast-word-wrap"; diff --git a/javascriptv3/example_code/libs/prompter.js b/javascriptv3/example_code/libs/prompter.js index da39acbbc18..cd079357ebf 100644 --- a/javascriptv3/example_code/libs/prompter.js +++ b/javascriptv3/example_code/libs/prompter.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.utils.prompter] import { select, input, confirm, checkbox } from "@inquirer/prompts"; diff --git a/javascriptv3/example_code/libs/scenario/index.js b/javascriptv3/example_code/libs/scenario/index.js index 3da43209606..eaa95d7ac30 100644 --- a/javascriptv3/example_code/libs/scenario/index.js +++ b/javascriptv3/example_code/libs/scenario/index.js @@ -1,2 +1,4 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 export * from "./scenario.js"; export * from "./scenario-parser.js"; diff --git a/javascriptv3/example_code/libs/scenario/scenario-example.js b/javascriptv3/example_code/libs/scenario/scenario-example.js index aa40600daad..6fa7a8d49cd 100644 --- a/javascriptv3/example_code/libs/scenario/scenario-example.js +++ b/javascriptv3/example_code/libs/scenario/scenario-example.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { Scenario, diff --git a/javascriptv3/example_code/libs/scenario/scenario-parser.js b/javascriptv3/example_code/libs/scenario/scenario-parser.js index a29f139d150..feeb28ca335 100644 --- a/javascriptv3/example_code/libs/scenario/scenario-parser.js +++ b/javascriptv3/example_code/libs/scenario/scenario-parser.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { parseArgs } from "node:util"; diff --git a/javascriptv3/example_code/libs/scenario/scenario.js b/javascriptv3/example_code/libs/scenario/scenario.js index 605bc3307ff..7837cff992f 100644 --- a/javascriptv3/example_code/libs/scenario/scenario.js +++ b/javascriptv3/example_code/libs/scenario/scenario.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { Prompter } from "../prompter.js"; import { Logger } from "../logger.js"; diff --git a/javascriptv3/example_code/libs/slow-logger.js b/javascriptv3/example_code/libs/slow-logger.js index 4f37933d213..8a94930c848 100644 --- a/javascriptv3/example_code/libs/slow-logger.js +++ b/javascriptv3/example_code/libs/slow-logger.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { Logger } from "./logger.js"; diff --git a/javascriptv3/example_code/libs/tests/cmd-runner.unit.test.js b/javascriptv3/example_code/libs/tests/cmd-runner.unit.test.js index a2701eb006d..753474e8c1a 100644 --- a/javascriptv3/example_code/libs/tests/cmd-runner.unit.test.js +++ b/javascriptv3/example_code/libs/tests/cmd-runner.unit.test.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { it, describe } from "vitest"; import { getCommands } from "../cmd-runner"; import { testEqual } from "../utils/util-test"; diff --git a/javascriptv3/example_code/libs/tests/util-array.unit.test.js b/javascriptv3/example_code/libs/tests/util-array.unit.test.js index 5f689628a5a..5954ca37de9 100644 --- a/javascriptv3/example_code/libs/tests/util-array.unit.test.js +++ b/javascriptv3/example_code/libs/tests/util-array.unit.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, test, expect } from "vitest"; import { startsWith } from "@aws-sdk-examples/libs/utils/util-array.js"; diff --git a/javascriptv3/example_code/libs/tests/util-csv.unit.test.js b/javascriptv3/example_code/libs/tests/util-csv.unit.test.js index 4023577cb87..ef09d1950c6 100644 --- a/javascriptv3/example_code/libs/tests/util-csv.unit.test.js +++ b/javascriptv3/example_code/libs/tests/util-csv.unit.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, afterAll } from "vitest"; import { testEqual } from "../utils/util-test.js"; import { getUniqueName } from "../utils/util-string.js"; diff --git a/javascriptv3/example_code/libs/tests/util-date.unit.test.js b/javascriptv3/example_code/libs/tests/util-date.unit.test.js index d89b0262553..9169759ba17 100644 --- a/javascriptv3/example_code/libs/tests/util-date.unit.test.js +++ b/javascriptv3/example_code/libs/tests/util-date.unit.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { test, expect } from "vitest"; import { splitDateRange } from "../utils/util-date.js"; diff --git a/javascriptv3/example_code/libs/tests/util-log.unit.test.js b/javascriptv3/example_code/libs/tests/util-log.unit.test.js index 32b79c697f9..75f4b3750d4 100644 --- a/javascriptv3/example_code/libs/tests/util-log.unit.test.js +++ b/javascriptv3/example_code/libs/tests/util-log.unit.test.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { it, describe, expect } from "vitest"; import { log } from "../utils/util-log"; diff --git a/javascriptv3/example_code/libs/tests/util-string.unit.test.js b/javascriptv3/example_code/libs/tests/util-string.unit.test.js index 4c165480bdb..5b2e2d8dd7c 100644 --- a/javascriptv3/example_code/libs/tests/util-string.unit.test.js +++ b/javascriptv3/example_code/libs/tests/util-string.unit.test.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { it, describe, expect } from "vitest"; import { getUniqueName, postfix } from "../utils/util-string"; diff --git a/javascriptv3/example_code/libs/tests/util-timers.unit.test.js b/javascriptv3/example_code/libs/tests/util-timers.unit.test.js index 3fdfb5d7853..46db77dcb33 100644 --- a/javascriptv3/example_code/libs/tests/util-timers.unit.test.js +++ b/javascriptv3/example_code/libs/tests/util-timers.unit.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import { retry } from "../utils/util-timers"; diff --git a/javascriptv3/example_code/libs/utils/util-array.js b/javascriptv3/example_code/libs/utils/util-array.js index 59e7132787d..435220241a3 100644 --- a/javascriptv3/example_code/libs/utils/util-array.js +++ b/javascriptv3/example_code/libs/utils/util-array.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * * @param {Array} arr diff --git a/javascriptv3/example_code/libs/utils/util-csv.js b/javascriptv3/example_code/libs/utils/util-csv.js index 3d08b432bdc..32b4f0340cc 100644 --- a/javascriptv3/example_code/libs/utils/util-csv.js +++ b/javascriptv3/example_code/libs/utils/util-csv.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { splitMapTrim } from "@aws-sdk-examples/libs/utils/util-string.js"; import { getNewLineDelimitedEntries } from "./util-fs.js"; diff --git a/javascriptv3/example_code/libs/utils/util-date.js b/javascriptv3/example_code/libs/utils/util-date.js index d6a18c0ac06..9226fbc5b17 100644 --- a/javascriptv3/example_code/libs/utils/util-date.js +++ b/javascriptv3/example_code/libs/utils/util-date.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * @typedef {Object} Interval * @property {number} years diff --git a/javascriptv3/example_code/libs/utils/util-fs.js b/javascriptv3/example_code/libs/utils/util-fs.js index fe956d5877c..870789bc98d 100644 --- a/javascriptv3/example_code/libs/utils/util-fs.js +++ b/javascriptv3/example_code/libs/utils/util-fs.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { unlink, readFile } from "fs/promises"; import { diff --git a/javascriptv3/example_code/libs/utils/util-log.js b/javascriptv3/example_code/libs/utils/util-log.js index b1a8b0dbcdd..ade245edf9a 100644 --- a/javascriptv3/example_code/libs/utils/util-log.js +++ b/javascriptv3/example_code/libs/utils/util-log.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { parseString } from "@aws-sdk-examples/libs/utils/util-string.js"; const log = (str) => { diff --git a/javascriptv3/example_code/libs/utils/util-node.js b/javascriptv3/example_code/libs/utils/util-node.js index ea4f1542bbc..4f472f4d09d 100644 --- a/javascriptv3/example_code/libs/utils/util-node.js +++ b/javascriptv3/example_code/libs/utils/util-node.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 export const getEnv = (key) => process.env[key]; export const setEnv = (key, value) => { diff --git a/javascriptv3/example_code/libs/utils/util-string.js b/javascriptv3/example_code/libs/utils/util-string.js index d0d5bc94d36..8ec6c886da1 100644 --- a/javascriptv3/example_code/libs/utils/util-string.js +++ b/javascriptv3/example_code/libs/utils/util-string.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { v4 as uuidv4 } from "uuid"; /** diff --git a/javascriptv3/example_code/libs/utils/util-test.js b/javascriptv3/example_code/libs/utils/util-test.js index 10538079959..8276997436f 100644 --- a/javascriptv3/example_code/libs/utils/util-test.js +++ b/javascriptv3/example_code/libs/utils/util-test.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { expect } from "vitest"; /** diff --git a/javascriptv3/example_code/libs/utils/util-timers.js b/javascriptv3/example_code/libs/utils/util-timers.js index 1e3efea7a07..51d2245952b 100644 --- a/javascriptv3/example_code/libs/utils/util-timers.js +++ b/javascriptv3/example_code/libs/utils/util-timers.js @@ -1,7 +1,5 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 const wait = (seconds) => new Promise((resolve) => diff --git a/javascriptv3/example_code/mediaconvert/src/emc_canceljob.js b/javascriptv3/example_code/mediaconvert/src/emc_canceljob.js index 5582d806458..7062a487ef9 100644 --- a/javascriptv3/example_code/mediaconvert/src/emc_canceljob.js +++ b/javascriptv3/example_code/mediaconvert/src/emc_canceljob.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/emc-examples-jobs.html. diff --git a/javascriptv3/example_code/mediaconvert/src/emc_create_jobtemplate.js b/javascriptv3/example_code/mediaconvert/src/emc_create_jobtemplate.js index a7dda3fce72..32b1b6b32f7 100644 --- a/javascriptv3/example_code/mediaconvert/src/emc_create_jobtemplate.js +++ b/javascriptv3/example_code/mediaconvert/src/emc_create_jobtemplate.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with Version 3 (V3) of the AWS SDK for JavaScript, which is scheduled for release by September 2020. The preview version of the SDK is available at https://github.com/aws/aws-sdk-js-v3. The 'SDK for JavaScript Developer Guide' for v3 is also diff --git a/javascriptv3/example_code/mediaconvert/src/emc_createjob.js b/javascriptv3/example_code/mediaconvert/src/emc_createjob.js index dabfb90cf25..fe24ee55a88 100644 --- a/javascriptv3/example_code/mediaconvert/src/emc_createjob.js +++ b/javascriptv3/example_code/mediaconvert/src/emc_createjob.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/emc-examples-jobs.html diff --git a/javascriptv3/example_code/mediaconvert/src/emc_deletetemplate.js b/javascriptv3/example_code/mediaconvert/src/emc_deletetemplate.js index d6ebeaf7d90..4d9be5caab6 100644 --- a/javascriptv3/example_code/mediaconvert/src/emc_deletetemplate.js +++ b/javascriptv3/example_code/mediaconvert/src/emc_deletetemplate.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with Version 3 (V3) of the AWS SDK for JavaScript, which is scheduled for release by September 2020. The preview version of the SDK is available at https://github.com/aws/aws-sdk-js-v3. The 'SDK for JavaScript Developer Guide' for v3 is also diff --git a/javascriptv3/example_code/mediaconvert/src/emc_getendpoint.js b/javascriptv3/example_code/mediaconvert/src/emc_getendpoint.js index 646f2bbb16b..cc8c34da3b9 100644 --- a/javascriptv3/example_code/mediaconvert/src/emc_getendpoint.js +++ b/javascriptv3/example_code/mediaconvert/src/emc_getendpoint.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with Version 3 (V3) of the AWS SDK for JavaScript, which is scheduled for release by September 2020. The preview version of the SDK is available at https://github.com/aws/aws-sdk-js-v3. The 'SDK for JavaScript Developer Guide' for v3 is also diff --git a/javascriptv3/example_code/mediaconvert/src/emc_listjobs.js b/javascriptv3/example_code/mediaconvert/src/emc_listjobs.js index c7d4e74aa26..9c0613a9911 100644 --- a/javascriptv3/example_code/mediaconvert/src/emc_listjobs.js +++ b/javascriptv3/example_code/mediaconvert/src/emc_listjobs.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with Version 3 (V3) of the AWS SDK for JavaScript, which is scheduled for release by September 2020. The preview version of the SDK is available at https://github.com/aws/aws-sdk-js-v3. The 'SDK for JavaScript Developer Guide' for v3 is also diff --git a/javascriptv3/example_code/mediaconvert/src/emc_listtemplates.js b/javascriptv3/example_code/mediaconvert/src/emc_listtemplates.js index 0ad5bc37d21..340d33a5358 100644 --- a/javascriptv3/example_code/mediaconvert/src/emc_listtemplates.js +++ b/javascriptv3/example_code/mediaconvert/src/emc_listtemplates.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with Version 3 (V3) of the AWS SDK for JavaScript, which is scheduled for release by September 2020. The preview version of the SDK is available at https://github.com/aws/aws-sdk-js-v3. The 'SDK for JavaScript Developer Guide' for v3 is also diff --git a/javascriptv3/example_code/mediaconvert/src/emc_template_createjob.js b/javascriptv3/example_code/mediaconvert/src/emc_template_createjob.js index 3d19a95d5d1..1812154fda4 100644 --- a/javascriptv3/example_code/mediaconvert/src/emc_template_createjob.js +++ b/javascriptv3/example_code/mediaconvert/src/emc_template_createjob.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with Version 3 (V3) of the AWS SDK for JavaScript, which is scheduled for release by September 2020. The preview version of the SDK is available at https://github.com/aws/aws-sdk-js-v3. The 'SDK for JavaScript Developer Guide' for v3 is also diff --git a/javascriptv3/example_code/mediaconvert/src/libs/emcClient.js b/javascriptv3/example_code/mediaconvert/src/libs/emcClient.js index c5a49b6ce94..238133a3a95 100644 --- a/javascriptv3/example_code/mediaconvert/src/libs/emcClient.js +++ b/javascriptv3/example_code/mediaconvert/src/libs/emcClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ec2-examples.html. @@ -11,8 +13,10 @@ Inputs (replace in code): - REGION - ENDPOINT */ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ec2-examples.html. diff --git a/javascriptv3/example_code/mediaconvert/src/libs/emcClientGet.js b/javascriptv3/example_code/mediaconvert/src/libs/emcClientGet.js index 9e85911b386..d2ab840aa21 100644 --- a/javascriptv3/example_code/mediaconvert/src/libs/emcClientGet.js +++ b/javascriptv3/example_code/mediaconvert/src/libs/emcClientGet.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ec2-examples.html. diff --git a/javascriptv3/example_code/medical-imaging/actions/copy-image-set.js b/javascriptv3/example_code/medical-imaging/actions/copy-image-set.js index 0bda8f1ac7d..c01f14061f5 100644 --- a/javascriptv3/example_code/medical-imaging/actions/copy-image-set.js +++ b/javascriptv3/example_code/medical-imaging/actions/copy-image-set.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/medical-imaging/actions/create-datastore.js b/javascriptv3/example_code/medical-imaging/actions/create-datastore.js index a4a621b953f..bbfde78d472 100644 --- a/javascriptv3/example_code/medical-imaging/actions/create-datastore.js +++ b/javascriptv3/example_code/medical-imaging/actions/create-datastore.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/medical-imaging/actions/delete-datastore.js b/javascriptv3/example_code/medical-imaging/actions/delete-datastore.js index f33543713c5..dcda6b288a2 100644 --- a/javascriptv3/example_code/medical-imaging/actions/delete-datastore.js +++ b/javascriptv3/example_code/medical-imaging/actions/delete-datastore.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/medical-imaging/actions/delete-image-set.js b/javascriptv3/example_code/medical-imaging/actions/delete-image-set.js index 64123790ba6..e02aca5e251 100644 --- a/javascriptv3/example_code/medical-imaging/actions/delete-image-set.js +++ b/javascriptv3/example_code/medical-imaging/actions/delete-image-set.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/medical-imaging/actions/get-datastore.js b/javascriptv3/example_code/medical-imaging/actions/get-datastore.js index 9b480fa29c7..280353ece3e 100644 --- a/javascriptv3/example_code/medical-imaging/actions/get-datastore.js +++ b/javascriptv3/example_code/medical-imaging/actions/get-datastore.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/medical-imaging/actions/get-dicom-import-job.js b/javascriptv3/example_code/medical-imaging/actions/get-dicom-import-job.js index 6bcc326c4f8..0ed7f41d962 100644 --- a/javascriptv3/example_code/medical-imaging/actions/get-dicom-import-job.js +++ b/javascriptv3/example_code/medical-imaging/actions/get-dicom-import-job.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/medical-imaging/actions/get-image-frame.js b/javascriptv3/example_code/medical-imaging/actions/get-image-frame.js index 20b155bcae8..102038c272a 100644 --- a/javascriptv3/example_code/medical-imaging/actions/get-image-frame.js +++ b/javascriptv3/example_code/medical-imaging/actions/get-image-frame.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; import { writeFileSync } from "fs"; diff --git a/javascriptv3/example_code/medical-imaging/actions/get-image-set-metadata.js b/javascriptv3/example_code/medical-imaging/actions/get-image-set-metadata.js index bd41dcd42ed..3805923d361 100644 --- a/javascriptv3/example_code/medical-imaging/actions/get-image-set-metadata.js +++ b/javascriptv3/example_code/medical-imaging/actions/get-image-set-metadata.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/medical-imaging/actions/get-image-set.js b/javascriptv3/example_code/medical-imaging/actions/get-image-set.js index d5e9e0938c5..9e8d57054f8 100644 --- a/javascriptv3/example_code/medical-imaging/actions/get-image-set.js +++ b/javascriptv3/example_code/medical-imaging/actions/get-image-set.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/medical-imaging/actions/list-datastores.js b/javascriptv3/example_code/medical-imaging/actions/list-datastores.js index 1d75d1c80cb..81a4d60547f 100644 --- a/javascriptv3/example_code/medical-imaging/actions/list-datastores.js +++ b/javascriptv3/example_code/medical-imaging/actions/list-datastores.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/medical-imaging/actions/list-dicom-import-jobs.js b/javascriptv3/example_code/medical-imaging/actions/list-dicom-import-jobs.js index a4720bcc7aa..9edcd8d083d 100644 --- a/javascriptv3/example_code/medical-imaging/actions/list-dicom-import-jobs.js +++ b/javascriptv3/example_code/medical-imaging/actions/list-dicom-import-jobs.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/medical-imaging/actions/list-image-set-versions.js b/javascriptv3/example_code/medical-imaging/actions/list-image-set-versions.js index 83c4f8210f1..cb64e11540d 100644 --- a/javascriptv3/example_code/medical-imaging/actions/list-image-set-versions.js +++ b/javascriptv3/example_code/medical-imaging/actions/list-image-set-versions.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/medical-imaging/actions/list-tags-for-resource.js b/javascriptv3/example_code/medical-imaging/actions/list-tags-for-resource.js index d0c85f87e52..7e10692858e 100644 --- a/javascriptv3/example_code/medical-imaging/actions/list-tags-for-resource.js +++ b/javascriptv3/example_code/medical-imaging/actions/list-tags-for-resource.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/medical-imaging/actions/search-image-sets.js b/javascriptv3/example_code/medical-imaging/actions/search-image-sets.js index 9fbe934cb31..0b9c8049fae 100644 --- a/javascriptv3/example_code/medical-imaging/actions/search-image-sets.js +++ b/javascriptv3/example_code/medical-imaging/actions/search-image-sets.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/medical-imaging/actions/start-dicom-import-job.js b/javascriptv3/example_code/medical-imaging/actions/start-dicom-import-job.js index 62178c90671..d8562a880b0 100644 --- a/javascriptv3/example_code/medical-imaging/actions/start-dicom-import-job.js +++ b/javascriptv3/example_code/medical-imaging/actions/start-dicom-import-job.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/medical-imaging/actions/tag-resource.js b/javascriptv3/example_code/medical-imaging/actions/tag-resource.js index b3bb4369509..85fb9d4c40a 100644 --- a/javascriptv3/example_code/medical-imaging/actions/tag-resource.js +++ b/javascriptv3/example_code/medical-imaging/actions/tag-resource.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/medical-imaging/actions/untag-resource.js b/javascriptv3/example_code/medical-imaging/actions/untag-resource.js index f4f5897bb15..c392d722dec 100644 --- a/javascriptv3/example_code/medical-imaging/actions/untag-resource.js +++ b/javascriptv3/example_code/medical-imaging/actions/untag-resource.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/medical-imaging/actions/update-image-set-metadata.js b/javascriptv3/example_code/medical-imaging/actions/update-image-set-metadata.js index 46696c5acd7..54007b5edb5 100644 --- a/javascriptv3/example_code/medical-imaging/actions/update-image-set-metadata.js +++ b/javascriptv3/example_code/medical-imaging/actions/update-image-set-metadata.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 diff --git a/javascriptv3/example_code/medical-imaging/hello.js b/javascriptv3/example_code/medical-imaging/hello.js index 6669ac4b0e4..a682fa3bcfe 100644 --- a/javascriptv3/example_code/medical-imaging/hello.js +++ b/javascriptv3/example_code/medical-imaging/hello.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/medical-imaging/libs/medicalImagingClient.js b/javascriptv3/example_code/medical-imaging/libs/medicalImagingClient.js index 786f40f85b4..354171f9810 100644 --- a/javascriptv3/example_code/medical-imaging/libs/medicalImagingClient.js +++ b/javascriptv3/example_code/medical-imaging/libs/medicalImagingClient.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[medical-imaging.JavaScript.createclientv3] import { MedicalImagingClient } from "@aws-sdk/client-medical-imaging"; diff --git a/javascriptv3/example_code/medical-imaging/scenarios/tagging-datastores.js b/javascriptv3/example_code/medical-imaging/scenarios/tagging-datastores.js index e211d06e4cf..cd48e1a7d07 100644 --- a/javascriptv3/example_code/medical-imaging/scenarios/tagging-datastores.js +++ b/javascriptv3/example_code/medical-imaging/scenarios/tagging-datastores.js @@ -1,9 +1,6 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -// Snippet for README link. // snippet-start:[medical-imaging.JavaScript.medical-imaging_tagging_datastores.V3] // snippet-end:[medical-imaging.JavaScript.medical-imaging_tagging_datastores.V3] diff --git a/javascriptv3/example_code/medical-imaging/scenarios/tagging-imagesets.js b/javascriptv3/example_code/medical-imaging/scenarios/tagging-imagesets.js index ac4ad4c5f56..a021a0e2602 100644 --- a/javascriptv3/example_code/medical-imaging/scenarios/tagging-imagesets.js +++ b/javascriptv3/example_code/medical-imaging/scenarios/tagging-imagesets.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/medical-imaging/tests/copy-image-set.unit.test.js b/javascriptv3/example_code/medical-imaging/tests/copy-image-set.unit.test.js index 2fe10b135b6..84a7656a9e2 100644 --- a/javascriptv3/example_code/medical-imaging/tests/copy-image-set.unit.test.js +++ b/javascriptv3/example_code/medical-imaging/tests/copy-image-set.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/medical-imaging/tests/create-delete-datastore.integration.test.js b/javascriptv3/example_code/medical-imaging/tests/create-delete-datastore.integration.test.js index a0a571a8323..e706489d4a2 100644 --- a/javascriptv3/example_code/medical-imaging/tests/create-delete-datastore.integration.test.js +++ b/javascriptv3/example_code/medical-imaging/tests/create-delete-datastore.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { wait } from "@aws-sdk-examples/libs/utils/util-timers.js"; diff --git a/javascriptv3/example_code/medical-imaging/tests/delete-image-set.unit.test.js b/javascriptv3/example_code/medical-imaging/tests/delete-image-set.unit.test.js index 1d45062a76f..2a21dc1ee58 100644 --- a/javascriptv3/example_code/medical-imaging/tests/delete-image-set.unit.test.js +++ b/javascriptv3/example_code/medical-imaging/tests/delete-image-set.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/medical-imaging/tests/get-datastore.integration.test.js b/javascriptv3/example_code/medical-imaging/tests/get-datastore.integration.test.js index ad50758e822..705b3f3a827 100644 --- a/javascriptv3/example_code/medical-imaging/tests/get-datastore.integration.test.js +++ b/javascriptv3/example_code/medical-imaging/tests/get-datastore.integration.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { getDatastore } from "../actions/get-datastore.js"; diff --git a/javascriptv3/example_code/medical-imaging/tests/get-dicom-import-job.unit.test.js b/javascriptv3/example_code/medical-imaging/tests/get-dicom-import-job.unit.test.js index 3a25c2437d5..af0f21ed92a 100644 --- a/javascriptv3/example_code/medical-imaging/tests/get-dicom-import-job.unit.test.js +++ b/javascriptv3/example_code/medical-imaging/tests/get-dicom-import-job.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/medical-imaging/tests/get-image-frame.unit.test.js b/javascriptv3/example_code/medical-imaging/tests/get-image-frame.unit.test.js index cb0d103b211..ac0fb9d455d 100644 --- a/javascriptv3/example_code/medical-imaging/tests/get-image-frame.unit.test.js +++ b/javascriptv3/example_code/medical-imaging/tests/get-image-frame.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import * as fs from "fs"; diff --git a/javascriptv3/example_code/medical-imaging/tests/get-image-set-metadata.unit.test.js b/javascriptv3/example_code/medical-imaging/tests/get-image-set-metadata.unit.test.js index 6088675a377..2e020ebd7ca 100644 --- a/javascriptv3/example_code/medical-imaging/tests/get-image-set-metadata.unit.test.js +++ b/javascriptv3/example_code/medical-imaging/tests/get-image-set-metadata.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; import * as fs from "fs"; diff --git a/javascriptv3/example_code/medical-imaging/tests/get-image-set.unit.test.js b/javascriptv3/example_code/medical-imaging/tests/get-image-set.unit.test.js index ca4e2f9e296..a28498e4a03 100644 --- a/javascriptv3/example_code/medical-imaging/tests/get-image-set.unit.test.js +++ b/javascriptv3/example_code/medical-imaging/tests/get-image-set.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/medical-imaging/tests/list-datastores.integration.test.js b/javascriptv3/example_code/medical-imaging/tests/list-datastores.integration.test.js index c997466b57e..2962377f2f7 100644 --- a/javascriptv3/example_code/medical-imaging/tests/list-datastores.integration.test.js +++ b/javascriptv3/example_code/medical-imaging/tests/list-datastores.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { listDatastores } from "../actions/list-datastores.js"; diff --git a/javascriptv3/example_code/medical-imaging/tests/list-dicom-import-jobs.unit.test.js b/javascriptv3/example_code/medical-imaging/tests/list-dicom-import-jobs.unit.test.js index 5a4c524759f..c050ce1c76f 100644 --- a/javascriptv3/example_code/medical-imaging/tests/list-dicom-import-jobs.unit.test.js +++ b/javascriptv3/example_code/medical-imaging/tests/list-dicom-import-jobs.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/medical-imaging/tests/list-image-set-versions.unit.test.js b/javascriptv3/example_code/medical-imaging/tests/list-image-set-versions.unit.test.js index e2ec8bf3c43..d593e1855f8 100644 --- a/javascriptv3/example_code/medical-imaging/tests/list-image-set-versions.unit.test.js +++ b/javascriptv3/example_code/medical-imaging/tests/list-image-set-versions.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/medical-imaging/tests/list-tags-for-resource.unit.test.js b/javascriptv3/example_code/medical-imaging/tests/list-tags-for-resource.unit.test.js index 18f6400d1d0..07bb7ec0e49 100644 --- a/javascriptv3/example_code/medical-imaging/tests/list-tags-for-resource.unit.test.js +++ b/javascriptv3/example_code/medical-imaging/tests/list-tags-for-resource.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/medical-imaging/tests/search-image-set.unit.test.js b/javascriptv3/example_code/medical-imaging/tests/search-image-set.unit.test.js index 30ddbcc6677..f380e3e0846 100644 --- a/javascriptv3/example_code/medical-imaging/tests/search-image-set.unit.test.js +++ b/javascriptv3/example_code/medical-imaging/tests/search-image-set.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/medical-imaging/tests/start-dicom-import-job.unit.test.js b/javascriptv3/example_code/medical-imaging/tests/start-dicom-import-job.unit.test.js index 05ef21f706e..347c0307c4b 100644 --- a/javascriptv3/example_code/medical-imaging/tests/start-dicom-import-job.unit.test.js +++ b/javascriptv3/example_code/medical-imaging/tests/start-dicom-import-job.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/medical-imaging/tests/tag-resource.unit.test.js b/javascriptv3/example_code/medical-imaging/tests/tag-resource.unit.test.js index 5dea842ded6..65a62b02683 100644 --- a/javascriptv3/example_code/medical-imaging/tests/tag-resource.unit.test.js +++ b/javascriptv3/example_code/medical-imaging/tests/tag-resource.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/medical-imaging/tests/untag-resource.unit.test.js b/javascriptv3/example_code/medical-imaging/tests/untag-resource.unit.test.js index 61e8516c0b3..0a85d0b3686 100644 --- a/javascriptv3/example_code/medical-imaging/tests/untag-resource.unit.test.js +++ b/javascriptv3/example_code/medical-imaging/tests/untag-resource.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/medical-imaging/tests/update-image-set-metadata.unit.test.js b/javascriptv3/example_code/medical-imaging/tests/update-image-set-metadata.unit.test.js index b48203b63ca..f390d25e5e7 100644 --- a/javascriptv3/example_code/medical-imaging/tests/update-image-set-metadata.unit.test.js +++ b/javascriptv3/example_code/medical-imaging/tests/update-image-set-metadata.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/medical-imaging/vite.config.js b/javascriptv3/example_code/medical-imaging/vite.config.js index d88efe3b2cc..548525f664d 100644 --- a/javascriptv3/example_code/medical-imaging/vite.config.js +++ b/javascriptv3/example_code/medical-imaging/vite.config.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { defineConfig } from "vitest/config"; diff --git a/javascriptv3/example_code/nodegetstarted/index.js b/javascriptv3/example_code/nodegetstarted/index.js index 8a4d309a74f..fddc638e8bd 100644 --- a/javascriptv3/example_code/nodegetstarted/index.js +++ b/javascriptv3/example_code/nodegetstarted/index.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[GettingStarted.JavaScript.NodeJS.sampleV3] // This is used for getting user input. diff --git a/javascriptv3/example_code/nodegetstarted/tests/index.integration.test.js b/javascriptv3/example_code/nodegetstarted/tests/index.integration.test.js index 0f8e95be739..6cbcbc6d693 100644 --- a/javascriptv3/example_code/nodegetstarted/tests/index.integration.test.js +++ b/javascriptv3/example_code/nodegetstarted/tests/index.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { test, vi } from "vitest"; import { main } from "../index.js"; diff --git a/javascriptv3/example_code/personalize/src/libs/personalizeClients.js b/javascriptv3/example_code/personalize/src/libs/personalizeClients.js index 4e1b144cb3e..db3001545da 100644 --- a/javascriptv3/example_code/personalize/src/libs/personalizeClients.js +++ b/javascriptv3/example_code/personalize/src/libs/personalizeClients.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { PersonalizeClient } from "@aws-sdk/client-personalize"; import { PersonalizeRuntimeClient } from "@aws-sdk/client-personalize-runtime"; import { PersonalizeEventsClient } from "@aws-sdk/client-personalize-events"; diff --git a/javascriptv3/example_code/personalize/src/personalize_createBatchInferenceJob.js b/javascriptv3/example_code/personalize/src/personalize_createBatchInferenceJob.js index df9c2a31e34..351ef878ebb 100644 --- a/javascriptv3/example_code/personalize/src/personalize_createBatchInferenceJob.js +++ b/javascriptv3/example_code/personalize/src/personalize_createBatchInferenceJob.js @@ -1,6 +1,10 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_createBatchSegmentJob.js b/javascriptv3/example_code/personalize/src/personalize_createBatchSegmentJob.js index 22234b8f724..1703b247de5 100644 --- a/javascriptv3/example_code/personalize/src/personalize_createBatchSegmentJob.js +++ b/javascriptv3/example_code/personalize/src/personalize_createBatchSegmentJob.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_createCampaign.js b/javascriptv3/example_code/personalize/src/personalize_createCampaign.js index e7899cf3925..75ee4ba669c 100644 --- a/javascriptv3/example_code/personalize/src/personalize_createCampaign.js +++ b/javascriptv3/example_code/personalize/src/personalize_createCampaign.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_createDataset.js b/javascriptv3/example_code/personalize/src/personalize_createDataset.js index 1a5fca99d22..5a821da8f27 100644 --- a/javascriptv3/example_code/personalize/src/personalize_createDataset.js +++ b/javascriptv3/example_code/personalize/src/personalize_createDataset.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_createDatasetExportJob.js b/javascriptv3/example_code/personalize/src/personalize_createDatasetExportJob.js index 621d9959b7d..f5695fc8249 100644 --- a/javascriptv3/example_code/personalize/src/personalize_createDatasetExportJob.js +++ b/javascriptv3/example_code/personalize/src/personalize_createDatasetExportJob.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_createDatasetGroup.js b/javascriptv3/example_code/personalize/src/personalize_createDatasetGroup.js index 1889a063d0c..331f06d635b 100644 --- a/javascriptv3/example_code/personalize/src/personalize_createDatasetGroup.js +++ b/javascriptv3/example_code/personalize/src/personalize_createDatasetGroup.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_createDatasetImportJob.js b/javascriptv3/example_code/personalize/src/personalize_createDatasetImportJob.js index 5cb9d4ada31..916db17f0fc 100644 --- a/javascriptv3/example_code/personalize/src/personalize_createDatasetImportJob.js +++ b/javascriptv3/example_code/personalize/src/personalize_createDatasetImportJob.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_createDomainDatasetGroup.js b/javascriptv3/example_code/personalize/src/personalize_createDomainDatasetGroup.js index a20e7fa1a72..d773d7f08ce 100644 --- a/javascriptv3/example_code/personalize/src/personalize_createDomainDatasetGroup.js +++ b/javascriptv3/example_code/personalize/src/personalize_createDomainDatasetGroup.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_createDomainSchema.js b/javascriptv3/example_code/personalize/src/personalize_createDomainSchema.js index 24de17b7f08..2f45e77f9eb 100644 --- a/javascriptv3/example_code/personalize/src/personalize_createDomainSchema.js +++ b/javascriptv3/example_code/personalize/src/personalize_createDomainSchema.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_createEventTracker.js b/javascriptv3/example_code/personalize/src/personalize_createEventTracker.js index 17263ce8eb7..6bbefeb2e04 100644 --- a/javascriptv3/example_code/personalize/src/personalize_createEventTracker.js +++ b/javascriptv3/example_code/personalize/src/personalize_createEventTracker.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_createFilter.js b/javascriptv3/example_code/personalize/src/personalize_createFilter.js index 5275b72c13c..03e0a69df95 100644 --- a/javascriptv3/example_code/personalize/src/personalize_createFilter.js +++ b/javascriptv3/example_code/personalize/src/personalize_createFilter.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_createRecommender.js b/javascriptv3/example_code/personalize/src/personalize_createRecommender.js index 1e356bd339e..a1f927742b8 100644 --- a/javascriptv3/example_code/personalize/src/personalize_createRecommender.js +++ b/javascriptv3/example_code/personalize/src/personalize_createRecommender.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_createSchema.js b/javascriptv3/example_code/personalize/src/personalize_createSchema.js index e01b4b24efe..9378c688985 100644 --- a/javascriptv3/example_code/personalize/src/personalize_createSchema.js +++ b/javascriptv3/example_code/personalize/src/personalize_createSchema.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_createSolution.js b/javascriptv3/example_code/personalize/src/personalize_createSolution.js index d1b98cd3e37..2409894e32e 100644 --- a/javascriptv3/example_code/personalize/src/personalize_createSolution.js +++ b/javascriptv3/example_code/personalize/src/personalize_createSolution.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_createSolutionVersion.js b/javascriptv3/example_code/personalize/src/personalize_createSolutionVersion.js index 2ce4b293191..7ba55371ed5 100644 --- a/javascriptv3/example_code/personalize/src/personalize_createSolutionVersion.js +++ b/javascriptv3/example_code/personalize/src/personalize_createSolutionVersion.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_getPersonalizedRanking.js b/javascriptv3/example_code/personalize/src/personalize_getPersonalizedRanking.js index 698628aca53..44814dbac5c 100644 --- a/javascriptv3/example_code/personalize/src/personalize_getPersonalizedRanking.js +++ b/javascriptv3/example_code/personalize/src/personalize_getPersonalizedRanking.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_getRecommendations.js b/javascriptv3/example_code/personalize/src/personalize_getRecommendations.js index cd409e1d754..91e4fe6fbaa 100644 --- a/javascriptv3/example_code/personalize/src/personalize_getRecommendations.js +++ b/javascriptv3/example_code/personalize/src/personalize_getRecommendations.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_getRecommendationsFromRecommender.js b/javascriptv3/example_code/personalize/src/personalize_getRecommendationsFromRecommender.js index 3642903e303..fbaa97eb971 100644 --- a/javascriptv3/example_code/personalize/src/personalize_getRecommendationsFromRecommender.js +++ b/javascriptv3/example_code/personalize/src/personalize_getRecommendationsFromRecommender.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_getRecommendationsWithFilter.js b/javascriptv3/example_code/personalize/src/personalize_getRecommendationsWithFilter.js index b082a420ee8..6577e569883 100644 --- a/javascriptv3/example_code/personalize/src/personalize_getRecommendationsWithFilter.js +++ b/javascriptv3/example_code/personalize/src/personalize_getRecommendationsWithFilter.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_putEvents.js b/javascriptv3/example_code/personalize/src/personalize_putEvents.js index 721a41fe674..ac8c3fcf3e1 100644 --- a/javascriptv3/example_code/personalize/src/personalize_putEvents.js +++ b/javascriptv3/example_code/personalize/src/personalize_putEvents.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_putItems.js b/javascriptv3/example_code/personalize/src/personalize_putItems.js index a1465a1557b..1eef6b0202c 100644 --- a/javascriptv3/example_code/personalize/src/personalize_putItems.js +++ b/javascriptv3/example_code/personalize/src/personalize_putItems.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/src/personalize_putUsers.js b/javascriptv3/example_code/personalize/src/personalize_putUsers.js index e7d99c74469..ed34662566d 100644 --- a/javascriptv3/example_code/personalize/src/personalize_putUsers.js +++ b/javascriptv3/example_code/personalize/src/personalize_putUsers.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/personalize/tests/babel.config.js b/javascriptv3/example_code/personalize/tests/babel.config.js index 9a46be1c82a..c11e6ce0817 100644 --- a/javascriptv3/example_code/personalize/tests/babel.config.js +++ b/javascriptv3/example_code/personalize/tests/babel.config.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 module.exports = { presets: ["@babel/preset-env"], }; diff --git a/javascriptv3/example_code/personalize/tests/jest.config.js b/javascriptv3/example_code/personalize/tests/jest.config.js index 465abcd1d04..6dcf812a335 100644 --- a/javascriptv3/example_code/personalize/tests/jest.config.js +++ b/javascriptv3/example_code/personalize/tests/jest.config.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 module.exports = { testEnvironment: "node", moduleDirectories: ["node_modules"], diff --git a/javascriptv3/example_code/personalize/tests/personalize_createDatasetGroup.test.js b/javascriptv3/example_code/personalize/tests/personalize_createDatasetGroup.test.js index e9f185e933c..7aa5ac101d7 100644 --- a/javascriptv3/example_code/personalize/tests/personalize_createDatasetGroup.test.js +++ b/javascriptv3/example_code/personalize/tests/personalize_createDatasetGroup.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import "dotenv/config"; // Set the schema parameters. diff --git a/javascriptv3/example_code/pinpoint/src/libs/pinClient.js b/javascriptv3/example_code/pinpoint/src/libs/pinClient.js index b62fef8b417..5284300c2d7 100644 --- a/javascriptv3/example_code/pinpoint/src/libs/pinClient.js +++ b/javascriptv3/example_code/pinpoint/src/libs/pinClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/pinpoint-examples.html. diff --git a/javascriptv3/example_code/pinpoint/src/pinpoint_send_email_message.js b/javascriptv3/example_code/pinpoint/src/pinpoint_send_email_message.js index 94a6e2a2d24..ab89b2c5497 100644 --- a/javascriptv3/example_code/pinpoint/src/pinpoint_send_email_message.js +++ b/javascriptv3/example_code/pinpoint/src/pinpoint_send_email_message.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. For more information on this example, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples.html. diff --git a/javascriptv3/example_code/pinpoint/src/pinpoint_send_sms_message.js b/javascriptv3/example_code/pinpoint/src/pinpoint_send_sms_message.js index 80463c258be..6dc5a5511e7 100644 --- a/javascriptv3/example_code/pinpoint/src/pinpoint_send_sms_message.js +++ b/javascriptv3/example_code/pinpoint/src/pinpoint_send_sms_message.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is pending release. For more information on this example, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples.html. diff --git a/javascriptv3/example_code/polly/general-examples/src/libs/pollyClient.js b/javascriptv3/example_code/polly/general-examples/src/libs/pollyClient.js index ade98ab120d..734debd5bcf 100644 --- a/javascriptv3/example_code/polly/general-examples/src/libs/pollyClient.js +++ b/javascriptv3/example_code/polly/general-examples/src/libs/pollyClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/getting-started-nodejs.html. diff --git a/javascriptv3/example_code/polly/general-examples/src/polly_synthesize_to_s3.js b/javascriptv3/example_code/polly/general-examples/src/polly_synthesize_to_s3.js index 65db18cfedf..94eb6b577da 100644 --- a/javascriptv3/example_code/polly/general-examples/src/polly_synthesize_to_s3.js +++ b/javascriptv3/example_code/polly/general-examples/src/polly_synthesize_to_s3.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/polly-examples.html. diff --git a/javascriptv3/example_code/polly/src/polly.js b/javascriptv3/example_code/polly/src/polly.js index 2a64ef5afb2..a91328f2052 100644 --- a/javascriptv3/example_code/polly/src/polly.js +++ b/javascriptv3/example_code/polly/src/polly.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/getting-started-browser.html. diff --git a/javascriptv3/example_code/reactnative/ReactNativeApp/.eslintrc.js b/javascriptv3/example_code/reactnative/ReactNativeApp/.eslintrc.js index 40c6dcd05f3..4fbfeba8655 100644 --- a/javascriptv3/example_code/reactnative/ReactNativeApp/.eslintrc.js +++ b/javascriptv3/example_code/reactnative/ReactNativeApp/.eslintrc.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 module.exports = { root: true, extends: '@react-native-community', diff --git a/javascriptv3/example_code/reactnative/ReactNativeApp/.prettierrc.js b/javascriptv3/example_code/reactnative/ReactNativeApp/.prettierrc.js index 2b540746a75..c2cbf3a025c 100644 --- a/javascriptv3/example_code/reactnative/ReactNativeApp/.prettierrc.js +++ b/javascriptv3/example_code/reactnative/ReactNativeApp/.prettierrc.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 module.exports = { arrowParens: 'avoid', bracketSameLine: true, diff --git a/javascriptv3/example_code/reactnative/ReactNativeApp/android/app/src/debug/java/com/reactnativeapp/ReactNativeFlipper.java b/javascriptv3/example_code/reactnative/ReactNativeApp/android/app/src/debug/java/com/reactnativeapp/ReactNativeFlipper.java index 664f57f1fea..8ca6411c17b 100644 --- a/javascriptv3/example_code/reactnative/ReactNativeApp/android/app/src/debug/java/com/reactnativeapp/ReactNativeFlipper.java +++ b/javascriptv3/example_code/reactnative/ReactNativeApp/android/app/src/debug/java/com/reactnativeapp/ReactNativeFlipper.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Copyright (c) Meta Platforms, Inc. and affiliates. * diff --git a/javascriptv3/example_code/reactnative/ReactNativeApp/android/app/src/main/java/com/reactnativeapp/MainActivity.java b/javascriptv3/example_code/reactnative/ReactNativeApp/android/app/src/main/java/com/reactnativeapp/MainActivity.java index 858c01a60a7..4a8a1e74ffc 100644 --- a/javascriptv3/example_code/reactnative/ReactNativeApp/android/app/src/main/java/com/reactnativeapp/MainActivity.java +++ b/javascriptv3/example_code/reactnative/ReactNativeApp/android/app/src/main/java/com/reactnativeapp/MainActivity.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.reactnativeapp; import com.facebook.react.ReactActivity; diff --git a/javascriptv3/example_code/reactnative/ReactNativeApp/android/app/src/main/java/com/reactnativeapp/MainApplication.java b/javascriptv3/example_code/reactnative/ReactNativeApp/android/app/src/main/java/com/reactnativeapp/MainApplication.java index 832b75e3ca1..29d68adc947 100644 --- a/javascriptv3/example_code/reactnative/ReactNativeApp/android/app/src/main/java/com/reactnativeapp/MainApplication.java +++ b/javascriptv3/example_code/reactnative/ReactNativeApp/android/app/src/main/java/com/reactnativeapp/MainApplication.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.reactnativeapp; import android.app.Application; diff --git a/javascriptv3/example_code/reactnative/ReactNativeApp/android/app/src/release/java/com/reactnativeapp/ReactNativeFlipper.java b/javascriptv3/example_code/reactnative/ReactNativeApp/android/app/src/release/java/com/reactnativeapp/ReactNativeFlipper.java index 83716d5ad2c..90aed193e4a 100644 --- a/javascriptv3/example_code/reactnative/ReactNativeApp/android/app/src/release/java/com/reactnativeapp/ReactNativeFlipper.java +++ b/javascriptv3/example_code/reactnative/ReactNativeApp/android/app/src/release/java/com/reactnativeapp/ReactNativeFlipper.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Copyright (c) Meta Platforms, Inc. and affiliates. * diff --git a/javascriptv3/example_code/reactnative/ReactNativeApp/babel.config.js b/javascriptv3/example_code/reactnative/ReactNativeApp/babel.config.js index f842b77fcfb..59af0dbf37b 100644 --- a/javascriptv3/example_code/reactnative/ReactNativeApp/babel.config.js +++ b/javascriptv3/example_code/reactnative/ReactNativeApp/babel.config.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 module.exports = { presets: ['module:metro-react-native-babel-preset'], }; diff --git a/javascriptv3/example_code/reactnative/ReactNativeApp/index.js b/javascriptv3/example_code/reactnative/ReactNativeApp/index.js index a850d031de7..e468e3deeff 100644 --- a/javascriptv3/example_code/reactnative/ReactNativeApp/index.js +++ b/javascriptv3/example_code/reactnative/ReactNativeApp/index.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * @format */ diff --git a/javascriptv3/example_code/reactnative/ReactNativeApp/metro.config.js b/javascriptv3/example_code/reactnative/ReactNativeApp/metro.config.js index e9722cb1b20..be088dabbb3 100644 --- a/javascriptv3/example_code/reactnative/ReactNativeApp/metro.config.js +++ b/javascriptv3/example_code/reactnative/ReactNativeApp/metro.config.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Metro configuration for React Native * https://github.com/facebook/react-native diff --git a/javascriptv3/example_code/redshift/src/libs/redshiftClient.js b/javascriptv3/example_code/redshift/src/libs/redshiftClient.js index d61a9af23ef..c7afbe1458e 100644 --- a/javascriptv3/example_code/redshift/src/libs/redshiftClient.js +++ b/javascriptv3/example_code/redshift/src/libs/redshiftClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/redshift-examples.html. diff --git a/javascriptv3/example_code/redshift/src/redshift-create-cluster.js b/javascriptv3/example_code/redshift/src/redshift-create-cluster.js index 7307abaf284..2ecc33fbf13 100644 --- a/javascriptv3/example_code/redshift/src/redshift-create-cluster.js +++ b/javascriptv3/example_code/redshift/src/redshift-create-cluster.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/redshift-examples.html. diff --git a/javascriptv3/example_code/redshift/src/redshift-delete-cluster.js b/javascriptv3/example_code/redshift/src/redshift-delete-cluster.js index e7a14504444..91dd35bf9b6 100644 --- a/javascriptv3/example_code/redshift/src/redshift-delete-cluster.js +++ b/javascriptv3/example_code/redshift/src/redshift-delete-cluster.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/redshift-examples.html. diff --git a/javascriptv3/example_code/redshift/src/redshift-describe-clusters.js b/javascriptv3/example_code/redshift/src/redshift-describe-clusters.js index 750e5873753..88e0e12dd99 100644 --- a/javascriptv3/example_code/redshift/src/redshift-describe-clusters.js +++ b/javascriptv3/example_code/redshift/src/redshift-describe-clusters.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/redshift-examples.html. diff --git a/javascriptv3/example_code/redshift/src/redshift-modify-cluster.js b/javascriptv3/example_code/redshift/src/redshift-modify-cluster.js index 5fd6166ad18..bc609b24cd8 100644 --- a/javascriptv3/example_code/redshift/src/redshift-modify-cluster.js +++ b/javascriptv3/example_code/redshift/src/redshift-modify-cluster.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/redshift-examples.html. diff --git a/javascriptv3/example_code/rekognition/estimate-age-example/src/estimate-age.js b/javascriptv3/example_code/rekognition/estimate-age-example/src/estimate-age.js index 63d40210e41..1dd9bd02f03 100644 --- a/javascriptv3/example_code/rekognition/estimate-age-example/src/estimate-age.js +++ b/javascriptv3/example_code/rekognition/estimate-age-example/src/estimate-age.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the Amazon Rekognition Developer Guide' at https://docs.aws.amazon.com/rekognition/latest/dg/image-bytes-javascript.html. diff --git a/javascriptv3/example_code/rekognition/estimate-age-example/src/libs/rekognitionClient.js b/javascriptv3/example_code/rekognition/estimate-age-example/src/libs/rekognitionClient.js index 8a07f3b55f3..725ab17cb93 100644 --- a/javascriptv3/example_code/rekognition/estimate-age-example/src/libs/rekognitionClient.js +++ b/javascriptv3/example_code/rekognition/estimate-age-example/src/libs/rekognitionClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/rekognition-estimate-age-example.html. diff --git a/javascriptv3/example_code/s3/actions/copy-object.js b/javascriptv3/example_code/s3/actions/copy-object.js index 0a6813e71a6..4b092b27825 100644 --- a/javascriptv3/example_code/s3/actions/copy-object.js +++ b/javascriptv3/example_code/s3/actions/copy-object.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/actions/create-bucket.js b/javascriptv3/example_code/s3/actions/create-bucket.js index 813e28adcd2..9edcd57c65a 100644 --- a/javascriptv3/example_code/s3/actions/create-bucket.js +++ b/javascriptv3/example_code/s3/actions/create-bucket.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/actions/delete-bucket-policy.js b/javascriptv3/example_code/s3/actions/delete-bucket-policy.js index 8032f7343f0..7960834a505 100644 --- a/javascriptv3/example_code/s3/actions/delete-bucket-policy.js +++ b/javascriptv3/example_code/s3/actions/delete-bucket-policy.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/actions/delete-bucket-website.js b/javascriptv3/example_code/s3/actions/delete-bucket-website.js index 7166ba5f581..7b9851bb5e5 100644 --- a/javascriptv3/example_code/s3/actions/delete-bucket-website.js +++ b/javascriptv3/example_code/s3/actions/delete-bucket-website.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/actions/delete-bucket.js b/javascriptv3/example_code/s3/actions/delete-bucket.js index 719e2655322..fac997038a5 100644 --- a/javascriptv3/example_code/s3/actions/delete-bucket.js +++ b/javascriptv3/example_code/s3/actions/delete-bucket.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/actions/delete-object.js b/javascriptv3/example_code/s3/actions/delete-object.js index 85df21a0c15..2b7416bc815 100644 --- a/javascriptv3/example_code/s3/actions/delete-object.js +++ b/javascriptv3/example_code/s3/actions/delete-object.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/actions/delete-objects.js b/javascriptv3/example_code/s3/actions/delete-objects.js index f15fcfba659..6e977621ed6 100644 --- a/javascriptv3/example_code/s3/actions/delete-objects.js +++ b/javascriptv3/example_code/s3/actions/delete-objects.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/actions/get-bucket-acl.js b/javascriptv3/example_code/s3/actions/get-bucket-acl.js index c1aa8d32387..b00e9b5e665 100644 --- a/javascriptv3/example_code/s3/actions/get-bucket-acl.js +++ b/javascriptv3/example_code/s3/actions/get-bucket-acl.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/actions/get-bucket-cors.js b/javascriptv3/example_code/s3/actions/get-bucket-cors.js index 8b26edde005..4caa8bccf74 100644 --- a/javascriptv3/example_code/s3/actions/get-bucket-cors.js +++ b/javascriptv3/example_code/s3/actions/get-bucket-cors.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/actions/get-bucket-policy.js b/javascriptv3/example_code/s3/actions/get-bucket-policy.js index 9a91ce107b6..07aec0deab4 100644 --- a/javascriptv3/example_code/s3/actions/get-bucket-policy.js +++ b/javascriptv3/example_code/s3/actions/get-bucket-policy.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/actions/get-bucket-website.js b/javascriptv3/example_code/s3/actions/get-bucket-website.js index ce2661dad4d..562c6ad7706 100644 --- a/javascriptv3/example_code/s3/actions/get-bucket-website.js +++ b/javascriptv3/example_code/s3/actions/get-bucket-website.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/actions/get-object.js b/javascriptv3/example_code/s3/actions/get-object.js index 9673dd30b17..58dcd8041d5 100644 --- a/javascriptv3/example_code/s3/actions/get-object.js +++ b/javascriptv3/example_code/s3/actions/get-object.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/actions/list-buckets.js b/javascriptv3/example_code/s3/actions/list-buckets.js index dab10a2cf09..42180459f95 100644 --- a/javascriptv3/example_code/s3/actions/list-buckets.js +++ b/javascriptv3/example_code/s3/actions/list-buckets.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/actions/list-objects.js b/javascriptv3/example_code/s3/actions/list-objects.js index 30c96b5950f..af0f56931a0 100644 --- a/javascriptv3/example_code/s3/actions/list-objects.js +++ b/javascriptv3/example_code/s3/actions/list-objects.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/actions/put-bucket-acl.js b/javascriptv3/example_code/s3/actions/put-bucket-acl.js index a14b63079a7..9d6ea2e5f4b 100644 --- a/javascriptv3/example_code/s3/actions/put-bucket-acl.js +++ b/javascriptv3/example_code/s3/actions/put-bucket-acl.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/actions/put-bucket-cors.js b/javascriptv3/example_code/s3/actions/put-bucket-cors.js index a75cb2d2db0..d604f553931 100644 --- a/javascriptv3/example_code/s3/actions/put-bucket-cors.js +++ b/javascriptv3/example_code/s3/actions/put-bucket-cors.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/actions/put-bucket-policy.js b/javascriptv3/example_code/s3/actions/put-bucket-policy.js index 81672f4bfbf..e7c87e1675a 100644 --- a/javascriptv3/example_code/s3/actions/put-bucket-policy.js +++ b/javascriptv3/example_code/s3/actions/put-bucket-policy.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/actions/put-bucket-website.js b/javascriptv3/example_code/s3/actions/put-bucket-website.js index 1a597848e7f..d354ff5ea9f 100644 --- a/javascriptv3/example_code/s3/actions/put-bucket-website.js +++ b/javascriptv3/example_code/s3/actions/put-bucket-website.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/actions/put-object.js b/javascriptv3/example_code/s3/actions/put-object.js index 44a4d1373b8..ff5e0dc8c2a 100644 --- a/javascriptv3/example_code/s3/actions/put-object.js +++ b/javascriptv3/example_code/s3/actions/put-object.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/client.js b/javascriptv3/example_code/s3/client.js index a681c797e05..83a25e24d65 100644 --- a/javascriptv3/example_code/s3/client.js +++ b/javascriptv3/example_code/s3/client.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[s3.JavaScript.buckets.createclientv3] import { S3Client } from "@aws-sdk/client-s3"; diff --git a/javascriptv3/example_code/s3/hello.js b/javascriptv3/example_code/s3/hello.js index 77ca9ec76a2..18eec2af9d9 100644 --- a/javascriptv3/example_code/s3/hello.js +++ b/javascriptv3/example_code/s3/hello.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/libs/s3Utils.js b/javascriptv3/example_code/s3/libs/s3Utils.js index ba7aa94f1fa..120d81b9d71 100644 --- a/javascriptv3/example_code/s3/libs/s3Utils.js +++ b/javascriptv3/example_code/s3/libs/s3Utils.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { CreateBucketCommand, PutBucketPolicyCommand, diff --git a/javascriptv3/example_code/s3/scenarios/basic.js b/javascriptv3/example_code/s3/scenarios/basic.js index 11f7675741d..b93b44ba111 100644 --- a/javascriptv3/example_code/s3/scenarios/basic.js +++ b/javascriptv3/example_code/s3/scenarios/basic.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* This example code shows you how to use Amazon S3 can be used as a core component of an application. * You'll do the following: diff --git a/javascriptv3/example_code/s3/scenarios/create-list-delete-bucket.js b/javascriptv3/example_code/s3/scenarios/create-list-delete-bucket.js index 087dbf48878..4319f320318 100644 --- a/javascriptv3/example_code/s3/scenarios/create-list-delete-bucket.js +++ b/javascriptv3/example_code/s3/scenarios/create-list-delete-bucket.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/scenarios/multipart-download.js b/javascriptv3/example_code/s3/scenarios/multipart-download.js index 81b4b6eb521..7a42ea7bec3 100644 --- a/javascriptv3/example_code/s3/scenarios/multipart-download.js +++ b/javascriptv3/example_code/s3/scenarios/multipart-download.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/scenarios/multipart-upload.js b/javascriptv3/example_code/s3/scenarios/multipart-upload.js index 940ed799675..133d98609a9 100644 --- a/javascriptv3/example_code/s3/scenarios/multipart-upload.js +++ b/javascriptv3/example_code/s3/scenarios/multipart-upload.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/scenarios/presigned-url-download.js b/javascriptv3/example_code/s3/scenarios/presigned-url-download.js index 600e4e345cd..fa49ea46807 100644 --- a/javascriptv3/example_code/s3/scenarios/presigned-url-download.js +++ b/javascriptv3/example_code/s3/scenarios/presigned-url-download.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/scenarios/presigned-url-upload.js b/javascriptv3/example_code/s3/scenarios/presigned-url-upload.js index 11084d4da7a..f9a5048022d 100644 --- a/javascriptv3/example_code/s3/scenarios/presigned-url-upload.js +++ b/javascriptv3/example_code/s3/scenarios/presigned-url-upload.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/s3/tests/basic.unit.test.js b/javascriptv3/example_code/s3/tests/basic.unit.test.js index 8993bc1e690..717ede26dda 100644 --- a/javascriptv3/example_code/s3/tests/basic.unit.test.js +++ b/javascriptv3/example_code/s3/tests/basic.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi, beforeEach } from "vitest"; diff --git a/javascriptv3/example_code/s3/tests/copy-object.unit.test.js b/javascriptv3/example_code/s3/tests/copy-object.unit.test.js index 3f18ba1480a..1f439da510b 100644 --- a/javascriptv3/example_code/s3/tests/copy-object.unit.test.js +++ b/javascriptv3/example_code/s3/tests/copy-object.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/s3/tests/create-bucket.unit.test.js b/javascriptv3/example_code/s3/tests/create-bucket.unit.test.js index dc566b572e0..815f7f35dab 100644 --- a/javascriptv3/example_code/s3/tests/create-bucket.unit.test.js +++ b/javascriptv3/example_code/s3/tests/create-bucket.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/s3/tests/delete-bucket-policy.unit.test.js b/javascriptv3/example_code/s3/tests/delete-bucket-policy.unit.test.js index 912e73e8500..a97849365c9 100644 --- a/javascriptv3/example_code/s3/tests/delete-bucket-policy.unit.test.js +++ b/javascriptv3/example_code/s3/tests/delete-bucket-policy.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/s3/tests/delete-bucket-website.unit.test.js b/javascriptv3/example_code/s3/tests/delete-bucket-website.unit.test.js index 4de7d85edf9..5206d2ed050 100644 --- a/javascriptv3/example_code/s3/tests/delete-bucket-website.unit.test.js +++ b/javascriptv3/example_code/s3/tests/delete-bucket-website.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/s3/tests/delete-bucket.unit.test.js b/javascriptv3/example_code/s3/tests/delete-bucket.unit.test.js index 80d5f53874a..5d2da2c68db 100644 --- a/javascriptv3/example_code/s3/tests/delete-bucket.unit.test.js +++ b/javascriptv3/example_code/s3/tests/delete-bucket.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/s3/tests/delete-object.unit.test.js b/javascriptv3/example_code/s3/tests/delete-object.unit.test.js index 66b4111de61..7cccda19bf5 100644 --- a/javascriptv3/example_code/s3/tests/delete-object.unit.test.js +++ b/javascriptv3/example_code/s3/tests/delete-object.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/s3/tests/delete-objects.unit.test.js b/javascriptv3/example_code/s3/tests/delete-objects.unit.test.js index ce949344940..5a6abcaac10 100644 --- a/javascriptv3/example_code/s3/tests/delete-objects.unit.test.js +++ b/javascriptv3/example_code/s3/tests/delete-objects.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/s3/tests/get-bucket-cors.unit.test.js b/javascriptv3/example_code/s3/tests/get-bucket-cors.unit.test.js index 9db05f9490a..8f4a89f4969 100644 --- a/javascriptv3/example_code/s3/tests/get-bucket-cors.unit.test.js +++ b/javascriptv3/example_code/s3/tests/get-bucket-cors.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/s3/tests/get-bucket-policy.unit.test.js b/javascriptv3/example_code/s3/tests/get-bucket-policy.unit.test.js index c7c0c7a761b..621093f1cc5 100644 --- a/javascriptv3/example_code/s3/tests/get-bucket-policy.unit.test.js +++ b/javascriptv3/example_code/s3/tests/get-bucket-policy.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/s3/tests/get-bucket-website.unit.test.js b/javascriptv3/example_code/s3/tests/get-bucket-website.unit.test.js index 23f544fb9e7..2cb83064155 100644 --- a/javascriptv3/example_code/s3/tests/get-bucket-website.unit.test.js +++ b/javascriptv3/example_code/s3/tests/get-bucket-website.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/s3/tests/get-object.unit.test.js b/javascriptv3/example_code/s3/tests/get-object.unit.test.js index 004bf73dffa..3f39b54d610 100644 --- a/javascriptv3/example_code/s3/tests/get-object.unit.test.js +++ b/javascriptv3/example_code/s3/tests/get-object.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/s3/tests/hello.integration.test.js b/javascriptv3/example_code/s3/tests/hello.integration.test.js index 074e6baac09..c11571823ce 100644 --- a/javascriptv3/example_code/s3/tests/hello.integration.test.js +++ b/javascriptv3/example_code/s3/tests/hello.integration.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { S3Client } from "@aws-sdk/client-s3"; import { describe, it, expect, beforeAll, afterAll } from "vitest"; diff --git a/javascriptv3/example_code/s3/tests/list-buckets.unit.test.js b/javascriptv3/example_code/s3/tests/list-buckets.unit.test.js index 62b376f1197..b1829898f8c 100644 --- a/javascriptv3/example_code/s3/tests/list-buckets.unit.test.js +++ b/javascriptv3/example_code/s3/tests/list-buckets.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/s3/tests/list-objects.unit.test.js b/javascriptv3/example_code/s3/tests/list-objects.unit.test.js index bd2e99b0a3d..7e872020ccb 100644 --- a/javascriptv3/example_code/s3/tests/list-objects.unit.test.js +++ b/javascriptv3/example_code/s3/tests/list-objects.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/s3/tests/multipart-download.unit.test.js b/javascriptv3/example_code/s3/tests/multipart-download.unit.test.js index bfa5f3f8154..b1655d344d1 100644 --- a/javascriptv3/example_code/s3/tests/multipart-download.unit.test.js +++ b/javascriptv3/example_code/s3/tests/multipart-download.unit.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; const send = vi.fn(() => Promise.resolve()); diff --git a/javascriptv3/example_code/s3/tests/put-bucket-acl.unit.test.js b/javascriptv3/example_code/s3/tests/put-bucket-acl.unit.test.js index 2c63fc46400..6a80b2285e2 100644 --- a/javascriptv3/example_code/s3/tests/put-bucket-acl.unit.test.js +++ b/javascriptv3/example_code/s3/tests/put-bucket-acl.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/s3/tests/put-bucket-cors.unit.test.js b/javascriptv3/example_code/s3/tests/put-bucket-cors.unit.test.js index f7dd2a3e390..c3f5ba0d3ea 100644 --- a/javascriptv3/example_code/s3/tests/put-bucket-cors.unit.test.js +++ b/javascriptv3/example_code/s3/tests/put-bucket-cors.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/s3/tests/put-bucket-policy.unit.test.js b/javascriptv3/example_code/s3/tests/put-bucket-policy.unit.test.js index 85e58c6d97c..46cf61082c3 100644 --- a/javascriptv3/example_code/s3/tests/put-bucket-policy.unit.test.js +++ b/javascriptv3/example_code/s3/tests/put-bucket-policy.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/s3/tests/put-bucket-website.unit.test.js b/javascriptv3/example_code/s3/tests/put-bucket-website.unit.test.js index 54b00f007f0..ae2bd12b75f 100644 --- a/javascriptv3/example_code/s3/tests/put-bucket-website.unit.test.js +++ b/javascriptv3/example_code/s3/tests/put-bucket-website.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/s3/tests/put-object.unit.test.js b/javascriptv3/example_code/s3/tests/put-object.unit.test.js index 342b9a3efad..3744d0251cf 100644 --- a/javascriptv3/example_code/s3/tests/put-object.unit.test.js +++ b/javascriptv3/example_code/s3/tests/put-object.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi } from "vitest"; diff --git a/javascriptv3/example_code/sagemaker/hello.js b/javascriptv3/example_code/sagemaker/hello.js index eb02ad008ac..53e5b2c02e6 100644 --- a/javascriptv3/example_code/sagemaker/hello.js +++ b/javascriptv3/example_code/sagemaker/hello.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/SageMakerPipelinesWkflw.js b/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/SageMakerPipelinesWkflw.js index 72d2efc1647..374f2bf229e 100644 --- a/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/SageMakerPipelinesWkflw.js +++ b/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/SageMakerPipelinesWkflw.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.sagemaker.wkflw.pipeline] import { retry, wait } from "@aws-sdk-examples/libs/utils/util-timers.js"; diff --git a/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/index.js b/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/index.js index d774f0600f4..08f48892a5e 100644 --- a/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/index.js +++ b/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/index.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/lambda/dist/index.mjs b/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/lambda/dist/index.mjs index 9c5ed08f4d9..9937b79717b 100644 --- a/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/lambda/dist/index.mjs +++ b/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/lambda/dist/index.mjs @@ -1,7 +1,5 @@ -import {SageMakerClient,SendPipelineExecutionStepFailureCommand,SendPipelineExecutionStepSuccessCommand}from'@aws-sdk/client-sagemaker';import {SageMakerGeospatialClient,ExportVectorEnrichmentJobCommand,GetVectorEnrichmentJobCommand,VectorEnrichmentJobStatus,StartVectorEnrichmentJobCommand}from'@aws-sdk/client-sagemaker-geospatial';/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +import {SageMakerClient,SendPipelineExecutionStepFailureCommand,SendPipelineExecutionStepSuccessCommand}from'@aws-sdk/client-sagemaker';import {SageMakerGeospatialClient,ExportVectorEnrichmentJobCommand,GetVectorEnrichmentJobCommand,VectorEnrichmentJobStatus,StartVectorEnrichmentJobCommand}from'@aws-sdk/client-sagemaker-geospatial';// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** diff --git a/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/lambda/rollup.config.js b/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/lambda/rollup.config.js index 140ce032682..7eaa025408d 100644 --- a/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/lambda/rollup.config.js +++ b/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/lambda/rollup.config.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { nodeResolve } from "@rollup/plugin-node-resolve"; import commonjs from "@rollup/plugin-commonjs"; diff --git a/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/lambda/src/index.js b/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/lambda/src/index.js index 661e5c4b027..3d08613af8a 100644 --- a/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/lambda/src/index.js +++ b/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/lambda/src/index.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.sagemaker.wkflw.pipeline.lambda.function] import { diff --git a/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/lib.js b/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/lib.js index 03bd667a9f3..3c4cd0e2281 100644 --- a/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/lib.js +++ b/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/lib.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.sagemaker.wkflw.pipeline.library] import { readFileSync } from "fs"; diff --git a/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/messages.js b/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/messages.js index 47483fedc3d..0bfc08e5e2b 100644 --- a/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/messages.js +++ b/javascriptv3/example_code/sagemaker/scenarios/wkflw-sagemaker-geospatial-pipeline/messages.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 export const MESSAGES = { greeting: `Welcome to the Amazon SageMaker pipeline example scenario. This example workflow will guide you through setting up and executing a SageMaker pipeline. The pipeline uses an AWS Lambda function and an Amazon Simple Queue Service (Amazon SQS) queue. It also runs a vector enrichment reverse geocode job to reverse geocode addresses in an input file and store the results in an export file.`, diff --git a/javascriptv3/example_code/sagemaker/tests/wkflw-sagemaker-geospatial-pipeline.integration.test.js b/javascriptv3/example_code/sagemaker/tests/wkflw-sagemaker-geospatial-pipeline.integration.test.js index ca305dfad6a..913efde5b71 100644 --- a/javascriptv3/example_code/sagemaker/tests/wkflw-sagemaker-geospatial-pipeline.integration.test.js +++ b/javascriptv3/example_code/sagemaker/tests/wkflw-sagemaker-geospatial-pipeline.integration.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, test } from "vitest"; import { SageMakerPipelinesWkflw } from "../scenarios/wkflw-sagemaker-geospatial-pipeline/SageMakerPipelinesWkflw.js"; diff --git a/javascriptv3/example_code/sagemaker/vite.config.js b/javascriptv3/example_code/sagemaker/vite.config.js index 9a7e7770d19..f621fdaa735 100644 --- a/javascriptv3/example_code/sagemaker/vite.config.js +++ b/javascriptv3/example_code/sagemaker/vite.config.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { defineConfig } from "vitest/config"; diff --git a/javascriptv3/example_code/secrets-manager/actions/get-secret-value.js b/javascriptv3/example_code/secrets-manager/actions/get-secret-value.js index 6f4c6d88e29..90372a403e1 100644 --- a/javascriptv3/example_code/secrets-manager/actions/get-secret-value.js +++ b/javascriptv3/example_code/secrets-manager/actions/get-secret-value.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; // snippet-start:[javascript.v3.secretsmanager.actions.GetSecretValue] diff --git a/javascriptv3/example_code/secrets-manager/tests/secrets-manager.integration.test.js b/javascriptv3/example_code/secrets-manager/tests/secrets-manager.integration.test.js index 2dd99edd325..ed02f7133da 100644 --- a/javascriptv3/example_code/secrets-manager/tests/secrets-manager.integration.test.js +++ b/javascriptv3/example_code/secrets-manager/tests/secrets-manager.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { CreateSecretCommand, DeleteSecretCommand, diff --git a/javascriptv3/example_code/ses/src/libs/sesClient.js b/javascriptv3/example_code/ses/src/libs/sesClient.js index a36144c39b0..e34bb88c807 100644 --- a/javascriptv3/example_code/ses/src/libs/sesClient.js +++ b/javascriptv3/example_code/ses/src/libs/sesClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples.html. diff --git a/javascriptv3/example_code/ses/src/libs/sesUtils.js b/javascriptv3/example_code/ses/src/libs/sesUtils.js index aa0bf734fed..5d9773ce60f 100644 --- a/javascriptv3/example_code/ses/src/libs/sesUtils.js +++ b/javascriptv3/example_code/ses/src/libs/sesUtils.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 * diff --git a/javascriptv3/example_code/ses/src/send-with-attachments.js b/javascriptv3/example_code/ses/src/send-with-attachments.js index 1aba330fd0d..1c6f9612800 100644 --- a/javascriptv3/example_code/ses/src/send-with-attachments.js +++ b/javascriptv3/example_code/ses/src/send-with-attachments.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/ses/src/ses_createreceiptfilter.js b/javascriptv3/example_code/ses/src/ses_createreceiptfilter.js index c4b353be7d3..38eaa9e9890 100644 --- a/javascriptv3/example_code/ses/src/ses_createreceiptfilter.js +++ b/javascriptv3/example_code/ses/src/ses_createreceiptfilter.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples-ip-filters.html. diff --git a/javascriptv3/example_code/ses/src/ses_createreceiptrule.js b/javascriptv3/example_code/ses/src/ses_createreceiptrule.js index a74cbeedf8f..cc5699482b6 100644 --- a/javascriptv3/example_code/ses/src/ses_createreceiptrule.js +++ b/javascriptv3/example_code/ses/src/ses_createreceiptrule.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples-receipt-rules.html. diff --git a/javascriptv3/example_code/ses/src/ses_createreceiptruleset.js b/javascriptv3/example_code/ses/src/ses_createreceiptruleset.js index 09d1680a837..64cd3a9915f 100644 --- a/javascriptv3/example_code/ses/src/ses_createreceiptruleset.js +++ b/javascriptv3/example_code/ses/src/ses_createreceiptruleset.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples-receipt-rules.html. diff --git a/javascriptv3/example_code/ses/src/ses_createtemplate.js b/javascriptv3/example_code/ses/src/ses_createtemplate.js index 8b6286b113c..4491e3e8ae3 100644 --- a/javascriptv3/example_code/ses/src/ses_createtemplate.js +++ b/javascriptv3/example_code/ses/src/ses_createtemplate.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples-creating-template.html. diff --git a/javascriptv3/example_code/ses/src/ses_deleteidentity.js b/javascriptv3/example_code/ses/src/ses_deleteidentity.js index d2024b7df18..6796571a36c 100644 --- a/javascriptv3/example_code/ses/src/ses_deleteidentity.js +++ b/javascriptv3/example_code/ses/src/ses_deleteidentity.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples-managing-identities.html. diff --git a/javascriptv3/example_code/ses/src/ses_deletereceiptfilter.js b/javascriptv3/example_code/ses/src/ses_deletereceiptfilter.js index dd769efbe4c..bc329f525ce 100644 --- a/javascriptv3/example_code/ses/src/ses_deletereceiptfilter.js +++ b/javascriptv3/example_code/ses/src/ses_deletereceiptfilter.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples-ip-filters.html. diff --git a/javascriptv3/example_code/ses/src/ses_deletereceiptrule.js b/javascriptv3/example_code/ses/src/ses_deletereceiptrule.js index 396e648dc31..b4d20fa9305 100644 --- a/javascriptv3/example_code/ses/src/ses_deletereceiptrule.js +++ b/javascriptv3/example_code/ses/src/ses_deletereceiptrule.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript (v3) Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples-receipt-rules.html. diff --git a/javascriptv3/example_code/ses/src/ses_deletereceiptruleset.js b/javascriptv3/example_code/ses/src/ses_deletereceiptruleset.js index 345d94b3333..6ab1c0108d7 100644 --- a/javascriptv3/example_code/ses/src/ses_deletereceiptruleset.js +++ b/javascriptv3/example_code/ses/src/ses_deletereceiptruleset.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples-receipt-rules.html. diff --git a/javascriptv3/example_code/ses/src/ses_deletetemplate.js b/javascriptv3/example_code/ses/src/ses_deletetemplate.js index 3bb4b37f644..3f6dccab897 100644 --- a/javascriptv3/example_code/ses/src/ses_deletetemplate.js +++ b/javascriptv3/example_code/ses/src/ses_deletetemplate.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples-creating-template.html. diff --git a/javascriptv3/example_code/ses/src/ses_gettemplate.js b/javascriptv3/example_code/ses/src/ses_gettemplate.js index 82fede912be..4563f202ef9 100644 --- a/javascriptv3/example_code/ses/src/ses_gettemplate.js +++ b/javascriptv3/example_code/ses/src/ses_gettemplate.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples-creating-template.html. diff --git a/javascriptv3/example_code/ses/src/ses_listidentities.js b/javascriptv3/example_code/ses/src/ses_listidentities.js index 4c93732281d..e9b1d569524 100644 --- a/javascriptv3/example_code/ses/src/ses_listidentities.js +++ b/javascriptv3/example_code/ses/src/ses_listidentities.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples-managing-identities.html. diff --git a/javascriptv3/example_code/ses/src/ses_listreceiptfilters.js b/javascriptv3/example_code/ses/src/ses_listreceiptfilters.js index 8fcaa7d3dca..fdb623d8f6d 100644 --- a/javascriptv3/example_code/ses/src/ses_listreceiptfilters.js +++ b/javascriptv3/example_code/ses/src/ses_listreceiptfilters.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples-ip-filters.html. diff --git a/javascriptv3/example_code/ses/src/ses_listtemplates.js b/javascriptv3/example_code/ses/src/ses_listtemplates.js index 993283d060b..e53b6e4ce3f 100644 --- a/javascriptv3/example_code/ses/src/ses_listtemplates.js +++ b/javascriptv3/example_code/ses/src/ses_listtemplates.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples-creating-template.html. diff --git a/javascriptv3/example_code/ses/src/ses_sendbulktemplatedemail.js b/javascriptv3/example_code/ses/src/ses_sendbulktemplatedemail.js index be0fe842bed..44f5d66f012 100644 --- a/javascriptv3/example_code/ses/src/ses_sendbulktemplatedemail.js +++ b/javascriptv3/example_code/ses/src/ses_sendbulktemplatedemail.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide//ses-examples-sending-email.html. diff --git a/javascriptv3/example_code/ses/src/ses_sendemail.js b/javascriptv3/example_code/ses/src/ses_sendemail.js index 954b1d831d0..12468b24089 100644 --- a/javascriptv3/example_code/ses/src/ses_sendemail.js +++ b/javascriptv3/example_code/ses/src/ses_sendemail.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-creating-buckets.html. diff --git a/javascriptv3/example_code/ses/src/ses_sendtemplatedemail.js b/javascriptv3/example_code/ses/src/ses_sendtemplatedemail.js index cd52726c27b..f6d4fc2925b 100644 --- a/javascriptv3/example_code/ses/src/ses_sendtemplatedemail.js +++ b/javascriptv3/example_code/ses/src/ses_sendtemplatedemail.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide//ses-examples-sending-email.html. diff --git a/javascriptv3/example_code/ses/src/ses_updatetemplate.js b/javascriptv3/example_code/ses/src/ses_updatetemplate.js index 270ba7b1846..57498823fdf 100644 --- a/javascriptv3/example_code/ses/src/ses_updatetemplate.js +++ b/javascriptv3/example_code/ses/src/ses_updatetemplate.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples-creating-template.html. diff --git a/javascriptv3/example_code/ses/src/ses_verifydomainidentity.js b/javascriptv3/example_code/ses/src/ses_verifydomainidentity.js index 1c6b6573029..5509bfead44 100644 --- a/javascriptv3/example_code/ses/src/ses_verifydomainidentity.js +++ b/javascriptv3/example_code/ses/src/ses_verifydomainidentity.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples-managing-identities.html. diff --git a/javascriptv3/example_code/ses/src/ses_verifyemailidentity.js b/javascriptv3/example_code/ses/src/ses_verifyemailidentity.js index 1ed5891468f..603ade1994f 100644 --- a/javascriptv3/example_code/ses/src/ses_verifyemailidentity.js +++ b/javascriptv3/example_code/ses/src/ses_verifyemailidentity.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples-managing-identities.html. diff --git a/javascriptv3/example_code/ses/tests/create-receipt-filter.integration.test.js b/javascriptv3/example_code/ses/tests/create-receipt-filter.integration.test.js index ca888a2cec6..76d3c3a68ec 100644 --- a/javascriptv3/example_code/ses/tests/create-receipt-filter.integration.test.js +++ b/javascriptv3/example_code/ses/tests/create-receipt-filter.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, afterAll, it, expect } from "vitest"; import { run, FILTER_NAME } from "../src/ses_createreceiptfilter"; diff --git a/javascriptv3/example_code/ses/tests/create-receipt-rule.integration.test.js b/javascriptv3/example_code/ses/tests/create-receipt-rule.integration.test.js index c6dcfaed32b..d7caa8794fe 100644 --- a/javascriptv3/example_code/ses/tests/create-receipt-rule.integration.test.js +++ b/javascriptv3/example_code/ses/tests/create-receipt-rule.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, beforeAll, afterAll, it, expect } from "vitest"; import { diff --git a/javascriptv3/example_code/ses/tests/create-receipt-ruleset.integration.test.js b/javascriptv3/example_code/ses/tests/create-receipt-ruleset.integration.test.js index f9b177539ce..e32367a8c4a 100644 --- a/javascriptv3/example_code/ses/tests/create-receipt-ruleset.integration.test.js +++ b/javascriptv3/example_code/ses/tests/create-receipt-ruleset.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, afterAll, it, expect } from "vitest"; import { RULE_SET_NAME, run } from "../src/ses_createreceiptruleset"; diff --git a/javascriptv3/example_code/ses/tests/create-template.integration.test.js b/javascriptv3/example_code/ses/tests/create-template.integration.test.js index c02df989f5d..ec63aa4f00f 100644 --- a/javascriptv3/example_code/ses/tests/create-template.integration.test.js +++ b/javascriptv3/example_code/ses/tests/create-template.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, afterAll, it, expect } from "vitest"; import { run, TEMPLATE_NAME } from "../src/ses_createtemplate"; diff --git a/javascriptv3/example_code/ses/tests/delete-identity.integration.test.js b/javascriptv3/example_code/ses/tests/delete-identity.integration.test.js index a79729b68ed..2fd34f2b50d 100644 --- a/javascriptv3/example_code/ses/tests/delete-identity.integration.test.js +++ b/javascriptv3/example_code/ses/tests/delete-identity.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, beforeAll, it, expect } from "vitest"; import { findIdentity, createIdentity } from "../src/libs/sesUtils"; diff --git a/javascriptv3/example_code/ses/tests/delete-receipt-filter.integration.test.js b/javascriptv3/example_code/ses/tests/delete-receipt-filter.integration.test.js index bd60154dbb6..fbbe3a78fb4 100644 --- a/javascriptv3/example_code/ses/tests/delete-receipt-filter.integration.test.js +++ b/javascriptv3/example_code/ses/tests/delete-receipt-filter.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, beforeAll, it, expect } from "vitest"; import { run, RECEIPT_FILTER_NAME } from "../src/ses_deletereceiptfilter"; diff --git a/javascriptv3/example_code/ses/tests/delete-receipt-rule.integration.test.js b/javascriptv3/example_code/ses/tests/delete-receipt-rule.integration.test.js index 751c53d0d2e..13c7a50f972 100644 --- a/javascriptv3/example_code/ses/tests/delete-receipt-rule.integration.test.js +++ b/javascriptv3/example_code/ses/tests/delete-receipt-rule.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, beforeAll, afterAll, it, expect } from "vitest"; import { CreateReceiptRuleCommand, TlsPolicy } from "@aws-sdk/client-ses"; diff --git a/javascriptv3/example_code/ses/tests/delete-receipt-ruleset.integration.test.js b/javascriptv3/example_code/ses/tests/delete-receipt-ruleset.integration.test.js index 79f547673c5..8ef945f2220 100644 --- a/javascriptv3/example_code/ses/tests/delete-receipt-ruleset.integration.test.js +++ b/javascriptv3/example_code/ses/tests/delete-receipt-ruleset.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, beforeAll, it, expect } from "vitest"; import { run, RULE_SET_NAME } from "../src/ses_deletereceiptruleset"; diff --git a/javascriptv3/example_code/ses/tests/delete-template.integration.test.js b/javascriptv3/example_code/ses/tests/delete-template.integration.test.js index 79c80ce0afa..bec4d5acc79 100644 --- a/javascriptv3/example_code/ses/tests/delete-template.integration.test.js +++ b/javascriptv3/example_code/ses/tests/delete-template.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, beforeAll, it, expect } from "vitest"; import { run, TEMPLATE_NAME } from "../src/ses_deletetemplate.js"; diff --git a/javascriptv3/example_code/ses/tests/get-template.integration.test.js b/javascriptv3/example_code/ses/tests/get-template.integration.test.js index e084c83ca59..72aa4fae74f 100644 --- a/javascriptv3/example_code/ses/tests/get-template.integration.test.js +++ b/javascriptv3/example_code/ses/tests/get-template.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, beforeAll, afterAll, it, expect } from "vitest"; import { run, TEMPLATE_NAME } from "../src/ses_gettemplate"; diff --git a/javascriptv3/example_code/ses/tests/list-identities.integration.test.js b/javascriptv3/example_code/ses/tests/list-identities.integration.test.js index 1ef18f9e924..09e7152271f 100644 --- a/javascriptv3/example_code/ses/tests/list-identities.integration.test.js +++ b/javascriptv3/example_code/ses/tests/list-identities.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, beforeAll, afterAll, it, expect } from "vitest"; import { diff --git a/javascriptv3/example_code/ses/tests/list-receiptfilters.integration.test.js b/javascriptv3/example_code/ses/tests/list-receiptfilters.integration.test.js index bc9d8329b51..6604eec1171 100644 --- a/javascriptv3/example_code/ses/tests/list-receiptfilters.integration.test.js +++ b/javascriptv3/example_code/ses/tests/list-receiptfilters.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, beforeAll, afterAll, it, expect } from "vitest"; import { getUniqueName } from "@aws-sdk-examples/libs/utils/util-string.js"; diff --git a/javascriptv3/example_code/ses/tests/list-templates.integration.test.js b/javascriptv3/example_code/ses/tests/list-templates.integration.test.js index ab5bcd19631..91ccd54dd68 100644 --- a/javascriptv3/example_code/ses/tests/list-templates.integration.test.js +++ b/javascriptv3/example_code/ses/tests/list-templates.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, beforeAll, afterAll, it, expect } from "vitest"; import { getUniqueName } from "@aws-sdk-examples/libs/utils/util-string.js"; diff --git a/javascriptv3/example_code/ses/tests/send-bulk-templated-email.integration.test.js b/javascriptv3/example_code/ses/tests/send-bulk-templated-email.integration.test.js index 5f47e9ebdbb..8840b59d24b 100644 --- a/javascriptv3/example_code/ses/tests/send-bulk-templated-email.integration.test.js +++ b/javascriptv3/example_code/ses/tests/send-bulk-templated-email.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, beforeAll, afterAll, it, expect } from "vitest"; import { diff --git a/javascriptv3/example_code/ses/tests/send-email.integration.test.js b/javascriptv3/example_code/ses/tests/send-email.integration.test.js index 9cc62e0e334..1f54b366dd5 100644 --- a/javascriptv3/example_code/ses/tests/send-email.integration.test.js +++ b/javascriptv3/example_code/ses/tests/send-email.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { run } from "../src/ses_sendemail"; diff --git a/javascriptv3/example_code/ses/tests/send-templated-email.integration.test.js b/javascriptv3/example_code/ses/tests/send-templated-email.integration.test.js index 60d47c18133..ec5f1ad2cc0 100644 --- a/javascriptv3/example_code/ses/tests/send-templated-email.integration.test.js +++ b/javascriptv3/example_code/ses/tests/send-templated-email.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, beforeAll, afterAll, it, expect } from "vitest"; import { diff --git a/javascriptv3/example_code/ses/tests/update-template.integration.test.js b/javascriptv3/example_code/ses/tests/update-template.integration.test.js index a9ebec7ae09..b20610ca1d5 100644 --- a/javascriptv3/example_code/ses/tests/update-template.integration.test.js +++ b/javascriptv3/example_code/ses/tests/update-template.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, beforeAll, afterAll, it, expect } from "vitest"; import { diff --git a/javascriptv3/example_code/ses/tests/verify-domain-identity.integration.test.js b/javascriptv3/example_code/ses/tests/verify-domain-identity.integration.test.js index 8cf4ecbfbc4..fbc9190aa2d 100644 --- a/javascriptv3/example_code/ses/tests/verify-domain-identity.integration.test.js +++ b/javascriptv3/example_code/ses/tests/verify-domain-identity.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, afterAll, it, expect } from "vitest"; import { run, DOMAIN_NAME } from "../src/ses_verifydomainidentity"; diff --git a/javascriptv3/example_code/ses/tests/verify-email-identity.integration.test.js b/javascriptv3/example_code/ses/tests/verify-email-identity.integration.test.js index e18d69b03fd..688c666fb27 100644 --- a/javascriptv3/example_code/ses/tests/verify-email-identity.integration.test.js +++ b/javascriptv3/example_code/ses/tests/verify-email-identity.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, afterAll, it, expect } from "vitest"; import { run, EMAIL_ADDRESS } from "../src/ses_verifyemailidentity"; diff --git a/javascriptv3/example_code/sfn/actions/start-execution.js b/javascriptv3/example_code/sfn/actions/start-execution.js index 6280ec32f2a..2b1137b7688 100644 --- a/javascriptv3/example_code/sfn/actions/start-execution.js +++ b/javascriptv3/example_code/sfn/actions/start-execution.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { SFNClient, StartExecutionCommand } from "@aws-sdk/client-sfn"; diff --git a/javascriptv3/example_code/sfn/tests/start-execution.unit.test.js b/javascriptv3/example_code/sfn/tests/start-execution.unit.test.js index d5bc550400d..200e08deb81 100644 --- a/javascriptv3/example_code/sfn/tests/start-execution.unit.test.js +++ b/javascriptv3/example_code/sfn/tests/start-execution.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, test, expect, vi } from "vitest"; import { SFNClient } from "@aws-sdk/client-sfn"; diff --git a/javascriptv3/example_code/sns/actions/check-if-phone-number-is-opted-out.js b/javascriptv3/example_code/sns/actions/check-if-phone-number-is-opted-out.js index 19fae84dca2..d5494e2ca86 100644 --- a/javascriptv3/example_code/sns/actions/check-if-phone-number-is-opted-out.js +++ b/javascriptv3/example_code/sns/actions/check-if-phone-number-is-opted-out.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sns/actions/confirm-subscription.js b/javascriptv3/example_code/sns/actions/confirm-subscription.js index 4b1354ead16..9860e4a4949 100644 --- a/javascriptv3/example_code/sns/actions/confirm-subscription.js +++ b/javascriptv3/example_code/sns/actions/confirm-subscription.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sns/actions/create-topic.js b/javascriptv3/example_code/sns/actions/create-topic.js index 93c5b2f9fba..cfdcb9cb0b9 100644 --- a/javascriptv3/example_code/sns/actions/create-topic.js +++ b/javascriptv3/example_code/sns/actions/create-topic.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sns/actions/delete-topic.js b/javascriptv3/example_code/sns/actions/delete-topic.js index 5dce66fb620..42fda89a30d 100644 --- a/javascriptv3/example_code/sns/actions/delete-topic.js +++ b/javascriptv3/example_code/sns/actions/delete-topic.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; // snippet-start:[sns.JavaScript.topics.deleteTopicV3] diff --git a/javascriptv3/example_code/sns/actions/get-sms-attributes.js b/javascriptv3/example_code/sns/actions/get-sms-attributes.js index 4c90238cc27..27cddf7bd7c 100644 --- a/javascriptv3/example_code/sns/actions/get-sms-attributes.js +++ b/javascriptv3/example_code/sns/actions/get-sms-attributes.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sns/actions/get-topic-attributes.js b/javascriptv3/example_code/sns/actions/get-topic-attributes.js index 5969ccda9a3..326129bd28b 100644 --- a/javascriptv3/example_code/sns/actions/get-topic-attributes.js +++ b/javascriptv3/example_code/sns/actions/get-topic-attributes.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; // snippet-start:[sns.JavaScript.topics.getTopicAttributesV3] diff --git a/javascriptv3/example_code/sns/actions/list-phone-numbers-opted-out.js b/javascriptv3/example_code/sns/actions/list-phone-numbers-opted-out.js index 0c2c43b6a7a..cadaa05b820 100644 --- a/javascriptv3/example_code/sns/actions/list-phone-numbers-opted-out.js +++ b/javascriptv3/example_code/sns/actions/list-phone-numbers-opted-out.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sns/actions/list-subscriptions-by-topic.js b/javascriptv3/example_code/sns/actions/list-subscriptions-by-topic.js index f647227cf86..38c1726a597 100644 --- a/javascriptv3/example_code/sns/actions/list-subscriptions-by-topic.js +++ b/javascriptv3/example_code/sns/actions/list-subscriptions-by-topic.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sns/actions/list-topics.js b/javascriptv3/example_code/sns/actions/list-topics.js index 9ad86152d0c..5d064a2ac3c 100644 --- a/javascriptv3/example_code/sns/actions/list-topics.js +++ b/javascriptv3/example_code/sns/actions/list-topics.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sns/actions/publish-sms.js b/javascriptv3/example_code/sns/actions/publish-sms.js index f7b438b0446..46f99bb0481 100644 --- a/javascriptv3/example_code/sns/actions/publish-sms.js +++ b/javascriptv3/example_code/sns/actions/publish-sms.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sns/actions/publish-topic.js b/javascriptv3/example_code/sns/actions/publish-topic.js index 9e405e1f0c5..d5714bdbd09 100644 --- a/javascriptv3/example_code/sns/actions/publish-topic.js +++ b/javascriptv3/example_code/sns/actions/publish-topic.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sns/actions/set-sms-attribute-type.js b/javascriptv3/example_code/sns/actions/set-sms-attribute-type.js index b3089227100..65c8ebe31f6 100644 --- a/javascriptv3/example_code/sns/actions/set-sms-attribute-type.js +++ b/javascriptv3/example_code/sns/actions/set-sms-attribute-type.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sns/actions/set-topic-attributes.js b/javascriptv3/example_code/sns/actions/set-topic-attributes.js index 6d2a33eed2d..a8fac07ec67 100644 --- a/javascriptv3/example_code/sns/actions/set-topic-attributes.js +++ b/javascriptv3/example_code/sns/actions/set-topic-attributes.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sns/actions/subscribe-app.js b/javascriptv3/example_code/sns/actions/subscribe-app.js index 9b87a5e41d9..ac7b171adee 100644 --- a/javascriptv3/example_code/sns/actions/subscribe-app.js +++ b/javascriptv3/example_code/sns/actions/subscribe-app.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sns/actions/subscribe-email.js b/javascriptv3/example_code/sns/actions/subscribe-email.js index 191b615381e..a41878fcb6f 100644 --- a/javascriptv3/example_code/sns/actions/subscribe-email.js +++ b/javascriptv3/example_code/sns/actions/subscribe-email.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sns/actions/subscribe-lambda.js b/javascriptv3/example_code/sns/actions/subscribe-lambda.js index a4cecbfe61f..e31728a71dc 100644 --- a/javascriptv3/example_code/sns/actions/subscribe-lambda.js +++ b/javascriptv3/example_code/sns/actions/subscribe-lambda.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sns/actions/subscribe-queue-filtered.js b/javascriptv3/example_code/sns/actions/subscribe-queue-filtered.js index c23225ed0e2..1f194a037fb 100644 --- a/javascriptv3/example_code/sns/actions/subscribe-queue-filtered.js +++ b/javascriptv3/example_code/sns/actions/subscribe-queue-filtered.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sns/actions/subscribe-queue.js b/javascriptv3/example_code/sns/actions/subscribe-queue.js index 93844426f7f..7bc0f954b03 100644 --- a/javascriptv3/example_code/sns/actions/subscribe-queue.js +++ b/javascriptv3/example_code/sns/actions/subscribe-queue.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sns/actions/unsubscribe.js b/javascriptv3/example_code/sns/actions/unsubscribe.js index ef97fb74b20..ce4762d2ddc 100644 --- a/javascriptv3/example_code/sns/actions/unsubscribe.js +++ b/javascriptv3/example_code/sns/actions/unsubscribe.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sns/hello.js b/javascriptv3/example_code/sns/hello.js index dd65021bb76..a4424120c5e 100644 --- a/javascriptv3/example_code/sns/hello.js +++ b/javascriptv3/example_code/sns/hello.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sns/libs/snsClient.js b/javascriptv3/example_code/sns/libs/snsClient.js index 6df5952b788..be16437aeaa 100644 --- a/javascriptv3/example_code/sns/libs/snsClient.js +++ b/javascriptv3/example_code/sns/libs/snsClient.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sns.JavaScript.createclientv3] import { SNSClient } from "@aws-sdk/client-sns"; diff --git a/javascriptv3/example_code/sns/tests/check-if-phone-number-is-opted-out.integration.test.js b/javascriptv3/example_code/sns/tests/check-if-phone-number-is-opted-out.integration.test.js index 289efce582b..d0e74ea193c 100644 --- a/javascriptv3/example_code/sns/tests/check-if-phone-number-is-opted-out.integration.test.js +++ b/javascriptv3/example_code/sns/tests/check-if-phone-number-is-opted-out.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { checkIfPhoneNumberIsOptedOut } from "../actions/check-if-phone-number-is-opted-out.js"; diff --git a/javascriptv3/example_code/sns/tests/confirm-subscription.integration.test.js b/javascriptv3/example_code/sns/tests/confirm-subscription.integration.test.js index ede1dd16895..7910af81aa0 100644 --- a/javascriptv3/example_code/sns/tests/confirm-subscription.integration.test.js +++ b/javascriptv3/example_code/sns/tests/confirm-subscription.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { confirmSubscription } from "../actions/confirm-subscription.js"; diff --git a/javascriptv3/example_code/sns/tests/create-delete-topic.integration.test.js b/javascriptv3/example_code/sns/tests/create-delete-topic.integration.test.js index c9ffd9192ab..28038e3a33d 100644 --- a/javascriptv3/example_code/sns/tests/create-delete-topic.integration.test.js +++ b/javascriptv3/example_code/sns/tests/create-delete-topic.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { paginateListTopics } from "@aws-sdk/client-sns"; diff --git a/javascriptv3/example_code/sns/tests/get-sms-attributes.integration.test.js b/javascriptv3/example_code/sns/tests/get-sms-attributes.integration.test.js index b905b491c50..e0493798f61 100644 --- a/javascriptv3/example_code/sns/tests/get-sms-attributes.integration.test.js +++ b/javascriptv3/example_code/sns/tests/get-sms-attributes.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { getSmsAttributes } from "../actions/get-sms-attributes.js"; import { SetSMSAttributesCommand } from "@aws-sdk/client-sns"; diff --git a/javascriptv3/example_code/sns/tests/get-topic-attributes.integration.test.js b/javascriptv3/example_code/sns/tests/get-topic-attributes.integration.test.js index 6c0abb5f937..91f04dbc14c 100644 --- a/javascriptv3/example_code/sns/tests/get-topic-attributes.integration.test.js +++ b/javascriptv3/example_code/sns/tests/get-topic-attributes.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { getTopicAttributes } from "../actions/get-topic-attributes.js"; diff --git a/javascriptv3/example_code/sns/tests/list-phone-numbers-opted-out.integration.test.js b/javascriptv3/example_code/sns/tests/list-phone-numbers-opted-out.integration.test.js index 7f881838174..c5bba105986 100644 --- a/javascriptv3/example_code/sns/tests/list-phone-numbers-opted-out.integration.test.js +++ b/javascriptv3/example_code/sns/tests/list-phone-numbers-opted-out.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { listPhoneNumbersOptedOut } from "../actions/list-phone-numbers-opted-out.js"; diff --git a/javascriptv3/example_code/sns/tests/list-subscriptions-by-topic.integration.test.js b/javascriptv3/example_code/sns/tests/list-subscriptions-by-topic.integration.test.js index 28a69d8402b..deb965698f1 100644 --- a/javascriptv3/example_code/sns/tests/list-subscriptions-by-topic.integration.test.js +++ b/javascriptv3/example_code/sns/tests/list-subscriptions-by-topic.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { listSubscriptionsByTopic } from "../actions/list-subscriptions-by-topic.js"; diff --git a/javascriptv3/example_code/sns/tests/list-topics.integration.test.js b/javascriptv3/example_code/sns/tests/list-topics.integration.test.js index 707f0868ae7..d707fd0b4a6 100644 --- a/javascriptv3/example_code/sns/tests/list-topics.integration.test.js +++ b/javascriptv3/example_code/sns/tests/list-topics.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { listTopics } from "../actions/list-topics.js"; diff --git a/javascriptv3/example_code/sns/tests/publish.integration.test.js b/javascriptv3/example_code/sns/tests/publish.integration.test.js index 17f4a01955d..932cf22322e 100644 --- a/javascriptv3/example_code/sns/tests/publish.integration.test.js +++ b/javascriptv3/example_code/sns/tests/publish.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { publish as publishSms } from "../actions/publish-sms.js"; diff --git a/javascriptv3/example_code/sns/tests/set-sms-attribute-type.integration.test.js b/javascriptv3/example_code/sns/tests/set-sms-attribute-type.integration.test.js index 80c2206ed4b..c9d87afa3d1 100644 --- a/javascriptv3/example_code/sns/tests/set-sms-attribute-type.integration.test.js +++ b/javascriptv3/example_code/sns/tests/set-sms-attribute-type.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { snsClient } from "../libs/snsClient.js"; import { setSmsType } from "../actions/set-sms-attribute-type.js"; diff --git a/javascriptv3/example_code/sns/tests/set-topic-attributes.integration.test.js b/javascriptv3/example_code/sns/tests/set-topic-attributes.integration.test.js index decc56eee53..59059afc178 100644 --- a/javascriptv3/example_code/sns/tests/set-topic-attributes.integration.test.js +++ b/javascriptv3/example_code/sns/tests/set-topic-attributes.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { setTopicAttributes } from "../actions/set-topic-attributes.js"; diff --git a/javascriptv3/example_code/sns/tests/subscribe-queue.integration.test.js b/javascriptv3/example_code/sns/tests/subscribe-queue.integration.test.js index 9c3c7488c84..1c9b3c9de51 100644 --- a/javascriptv3/example_code/sns/tests/subscribe-queue.integration.test.js +++ b/javascriptv3/example_code/sns/tests/subscribe-queue.integration.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, beforeAll, afterAll } from "vitest"; import { diff --git a/javascriptv3/example_code/sns/tests/subscribe.integration.test.js b/javascriptv3/example_code/sns/tests/subscribe.integration.test.js index 78e2d223496..a5d97ea198e 100644 --- a/javascriptv3/example_code/sns/tests/subscribe.integration.test.js +++ b/javascriptv3/example_code/sns/tests/subscribe.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect } from "vitest"; import { subscribeApp } from "../actions/subscribe-app.js"; import { subscribeEmail } from "../actions/subscribe-email.js"; diff --git a/javascriptv3/example_code/sqs/actions/change-message-visibility.js b/javascriptv3/example_code/sqs/actions/change-message-visibility.js index 20536d04feb..79cd3d9667f 100644 --- a/javascriptv3/example_code/sqs/actions/change-message-visibility.js +++ b/javascriptv3/example_code/sqs/actions/change-message-visibility.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; // snippet-start:[sqs.JavaScript.visibility.receiveMessageV3] diff --git a/javascriptv3/example_code/sqs/actions/create-queue-long-polling.js b/javascriptv3/example_code/sqs/actions/create-queue-long-polling.js index 4353443df90..b4223912e71 100644 --- a/javascriptv3/example_code/sqs/actions/create-queue-long-polling.js +++ b/javascriptv3/example_code/sqs/actions/create-queue-long-polling.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sqs/actions/create-queue.js b/javascriptv3/example_code/sqs/actions/create-queue.js index 579b58144e6..e91af6fd105 100644 --- a/javascriptv3/example_code/sqs/actions/create-queue.js +++ b/javascriptv3/example_code/sqs/actions/create-queue.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* */ import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sqs/actions/delete-queue.js b/javascriptv3/example_code/sqs/actions/delete-queue.js index f5ed3e5393d..d73b5db72b5 100644 --- a/javascriptv3/example_code/sqs/actions/delete-queue.js +++ b/javascriptv3/example_code/sqs/actions/delete-queue.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sqs/actions/get-queue-attributes.js b/javascriptv3/example_code/sqs/actions/get-queue-attributes.js index d877236d7c7..eb82712ff11 100644 --- a/javascriptv3/example_code/sqs/actions/get-queue-attributes.js +++ b/javascriptv3/example_code/sqs/actions/get-queue-attributes.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sqs/actions/get-queue-url.js b/javascriptv3/example_code/sqs/actions/get-queue-url.js index 9fd056b8aa0..6c46c6215e1 100644 --- a/javascriptv3/example_code/sqs/actions/get-queue-url.js +++ b/javascriptv3/example_code/sqs/actions/get-queue-url.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sqs/actions/list-queues.js b/javascriptv3/example_code/sqs/actions/list-queues.js index 5aec66329a9..b1ab219db84 100644 --- a/javascriptv3/example_code/sqs/actions/list-queues.js +++ b/javascriptv3/example_code/sqs/actions/list-queues.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sqs/actions/receive-delete-message.js b/javascriptv3/example_code/sqs/actions/receive-delete-message.js index 1db6dd503bf..5c80e1af5e9 100644 --- a/javascriptv3/example_code/sqs/actions/receive-delete-message.js +++ b/javascriptv3/example_code/sqs/actions/receive-delete-message.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sqs/actions/receive-long-polling.js b/javascriptv3/example_code/sqs/actions/receive-long-polling.js index 28884adb26d..16222b8bf27 100644 --- a/javascriptv3/example_code/sqs/actions/receive-long-polling.js +++ b/javascriptv3/example_code/sqs/actions/receive-long-polling.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sqs/actions/send-message.js b/javascriptv3/example_code/sqs/actions/send-message.js index b084440ce92..f94d1abff96 100644 --- a/javascriptv3/example_code/sqs/actions/send-message.js +++ b/javascriptv3/example_code/sqs/actions/send-message.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sqs/actions/set-attributes-dead-letter.js b/javascriptv3/example_code/sqs/actions/set-attributes-dead-letter.js index d655568b809..34fed13f0fc 100644 --- a/javascriptv3/example_code/sqs/actions/set-attributes-dead-letter.js +++ b/javascriptv3/example_code/sqs/actions/set-attributes-dead-letter.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sqs/actions/set-attributes-long-polling.js b/javascriptv3/example_code/sqs/actions/set-attributes-long-polling.js index 14efd576265..c42b811c5f1 100644 --- a/javascriptv3/example_code/sqs/actions/set-attributes-long-polling.js +++ b/javascriptv3/example_code/sqs/actions/set-attributes-long-polling.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sqs/actions/set-queue-attributes.js b/javascriptv3/example_code/sqs/actions/set-queue-attributes.js index d38d2d91777..672f16ab069 100644 --- a/javascriptv3/example_code/sqs/actions/set-queue-attributes.js +++ b/javascriptv3/example_code/sqs/actions/set-queue-attributes.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sqs/client.js b/javascriptv3/example_code/sqs/client.js index 6ad6ceb9ae1..8d5f42aebe8 100644 --- a/javascriptv3/example_code/sqs/client.js +++ b/javascriptv3/example_code/sqs/client.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[sqs.JavaScript.createclientv3] import { SQSClient } from "@aws-sdk/client-sqs"; diff --git a/javascriptv3/example_code/sqs/hello.js b/javascriptv3/example_code/sqs/hello.js index ce9b0b7030a..fc530248645 100644 --- a/javascriptv3/example_code/sqs/hello.js +++ b/javascriptv3/example_code/sqs/hello.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/sqs/tests/change-visibility.integration.test.js b/javascriptv3/example_code/sqs/tests/change-visibility.integration.test.js index c5710140599..87329943f14 100644 --- a/javascriptv3/example_code/sqs/tests/change-visibility.integration.test.js +++ b/javascriptv3/example_code/sqs/tests/change-visibility.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, afterAll, beforeAll } from "vitest"; import { getUniqueName } from "@aws-sdk-examples/libs/utils/util-string.js"; diff --git a/javascriptv3/example_code/sqs/tests/queue-actions.integration.test.js b/javascriptv3/example_code/sqs/tests/queue-actions.integration.test.js index 9fd0c55a981..ba50e1c1069 100644 --- a/javascriptv3/example_code/sqs/tests/queue-actions.integration.test.js +++ b/javascriptv3/example_code/sqs/tests/queue-actions.integration.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, afterAll, vi } from "vitest"; import { getUniqueName } from "@aws-sdk-examples/libs/utils/util-string.js"; diff --git a/javascriptv3/example_code/sqs/vite.config.ts b/javascriptv3/example_code/sqs/vite.config.ts index af1970c815b..e28ef8690cb 100644 --- a/javascriptv3/example_code/sqs/vite.config.ts +++ b/javascriptv3/example_code/sqs/vite.config.ts @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { defineConfig } from "vitest/config"; diff --git a/javascriptv3/example_code/sts/actions/assume-role.js b/javascriptv3/example_code/sts/actions/assume-role.js index adc6ce02f36..aad9b942fc8 100644 --- a/javascriptv3/example_code/sts/actions/assume-role.js +++ b/javascriptv3/example_code/sts/actions/assume-role.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; // snippet-start:[javascript.v3.sts.actions.AssumeRole] diff --git a/javascriptv3/example_code/sts/libs/client.js b/javascriptv3/example_code/sts/libs/client.js index 5a278c30d6e..4dcc143fae5 100644 --- a/javascriptv3/example_code/sts/libs/client.js +++ b/javascriptv3/example_code/sts/libs/client.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.sts.client] import { STSClient } from "@aws-sdk/client-sts"; diff --git a/javascriptv3/example_code/sts/tests/assume-role.unit.test.js b/javascriptv3/example_code/sts/tests/assume-role.unit.test.js index 8762cd4e4cc..4214dc92e50 100644 --- a/javascriptv3/example_code/sts/tests/assume-role.unit.test.js +++ b/javascriptv3/example_code/sts/tests/assume-role.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi, beforeEach } from "vitest"; diff --git a/javascriptv3/example_code/support/actions/add-attachments-to-set.js b/javascriptv3/example_code/support/actions/add-attachments-to-set.js index 95495d1771a..1b7596a0107 100644 --- a/javascriptv3/example_code/support/actions/add-attachments-to-set.js +++ b/javascriptv3/example_code/support/actions/add-attachments-to-set.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/support/actions/add-communication-to-case.js b/javascriptv3/example_code/support/actions/add-communication-to-case.js index a2ccfe11613..b9c450cdb71 100644 --- a/javascriptv3/example_code/support/actions/add-communication-to-case.js +++ b/javascriptv3/example_code/support/actions/add-communication-to-case.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/support/actions/create-case.js b/javascriptv3/example_code/support/actions/create-case.js index 8ae081dd981..944a31a653f 100644 --- a/javascriptv3/example_code/support/actions/create-case.js +++ b/javascriptv3/example_code/support/actions/create-case.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/support/actions/describe-attachment.js b/javascriptv3/example_code/support/actions/describe-attachment.js index c4db449bc60..05bb86a8dd1 100644 --- a/javascriptv3/example_code/support/actions/describe-attachment.js +++ b/javascriptv3/example_code/support/actions/describe-attachment.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/support/actions/describe-cases.js b/javascriptv3/example_code/support/actions/describe-cases.js index c38d9861192..399c8c0c22c 100644 --- a/javascriptv3/example_code/support/actions/describe-cases.js +++ b/javascriptv3/example_code/support/actions/describe-cases.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/support/actions/describe-communications.js b/javascriptv3/example_code/support/actions/describe-communications.js index ca1acbe46cf..cc9b0d20091 100644 --- a/javascriptv3/example_code/support/actions/describe-communications.js +++ b/javascriptv3/example_code/support/actions/describe-communications.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/support/actions/describe-services.js b/javascriptv3/example_code/support/actions/describe-services.js index 5350120512c..024ea0fb268 100644 --- a/javascriptv3/example_code/support/actions/describe-services.js +++ b/javascriptv3/example_code/support/actions/describe-services.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/support/actions/describe-severity-levels.js b/javascriptv3/example_code/support/actions/describe-severity-levels.js index 651f80f03ca..d8f5b84cc47 100644 --- a/javascriptv3/example_code/support/actions/describe-severity-levels.js +++ b/javascriptv3/example_code/support/actions/describe-severity-levels.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/support/actions/resolve-case.js b/javascriptv3/example_code/support/actions/resolve-case.js index c5fc7bcd4cf..9660e82542c 100644 --- a/javascriptv3/example_code/support/actions/resolve-case.js +++ b/javascriptv3/example_code/support/actions/resolve-case.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/support/hello.js b/javascriptv3/example_code/support/hello.js index 4d7e47946e4..d45e98cecbf 100644 --- a/javascriptv3/example_code/support/hello.js +++ b/javascriptv3/example_code/support/hello.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; diff --git a/javascriptv3/example_code/support/libs/client.js b/javascriptv3/example_code/support/libs/client.js index 37f0770f874..37c4e706cf7 100644 --- a/javascriptv3/example_code/support/libs/client.js +++ b/javascriptv3/example_code/support/libs/client.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { SupportClient } from "@aws-sdk/client-support"; diff --git a/javascriptv3/example_code/support/scenarios/basic.js b/javascriptv3/example_code/support/scenarios/basic.js index 51e45b32c50..9de2c1a0846 100644 --- a/javascriptv3/example_code/support/scenarios/basic.js +++ b/javascriptv3/example_code/support/scenarios/basic.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; // snippet-start:[javascript.v3.support.scenarios.basic] diff --git a/javascriptv3/example_code/support/tests/basic.unit.test.js b/javascriptv3/example_code/support/tests/basic.unit.test.js index 66536e3219c..f51950e226b 100644 --- a/javascriptv3/example_code/support/tests/basic.unit.test.js +++ b/javascriptv3/example_code/support/tests/basic.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi, beforeEach } from "vitest"; diff --git a/javascriptv3/example_code/support/tests/hello.unit.test.js b/javascriptv3/example_code/support/tests/hello.unit.test.js index 1eecc4e7dde..5776ba22daa 100644 --- a/javascriptv3/example_code/support/tests/hello.unit.test.js +++ b/javascriptv3/example_code/support/tests/hello.unit.test.js @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { describe, it, expect, vi, beforeEach } from "vitest"; diff --git a/javascriptv3/example_code/transcribe/src/libs/transcribeClient.js b/javascriptv3/example_code/transcribe/src/libs/transcribeClient.js index 60396087c91..b3265124e54 100644 --- a/javascriptv3/example_code/transcribe/src/libs/transcribeClient.js +++ b/javascriptv3/example_code/transcribe/src/libs/transcribeClient.js @@ -1,5 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/transcribe-examples.html. diff --git a/javascriptv3/example_code/transcribe/src/transcribe_create_job.js b/javascriptv3/example_code/transcribe/src/transcribe_create_job.js index 3b3a7170a35..9dbb8dc7d12 100644 --- a/javascriptv3/example_code/transcribe/src/transcribe_create_job.js +++ b/javascriptv3/example_code/transcribe/src/transcribe_create_job.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/transcribe/src/transcribe_create_medical_job.js b/javascriptv3/example_code/transcribe/src/transcribe_create_medical_job.js index 0a5a62d1676..3543e770499 100644 --- a/javascriptv3/example_code/transcribe/src/transcribe_create_medical_job.js +++ b/javascriptv3/example_code/transcribe/src/transcribe_create_medical_job.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/transcribe/src/transcribe_delete_job.js b/javascriptv3/example_code/transcribe/src/transcribe_delete_job.js index 43e03edcbbd..179a45a376f 100644 --- a/javascriptv3/example_code/transcribe/src/transcribe_delete_job.js +++ b/javascriptv3/example_code/transcribe/src/transcribe_delete_job.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/transcribe/src/transcribe_delete_medical_job.js b/javascriptv3/example_code/transcribe/src/transcribe_delete_medical_job.js index ecfd374e96d..a348e797f16 100644 --- a/javascriptv3/example_code/transcribe/src/transcribe_delete_medical_job.js +++ b/javascriptv3/example_code/transcribe/src/transcribe_delete_medical_job.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/transcribe/src/transcribe_list_jobs.js b/javascriptv3/example_code/transcribe/src/transcribe_list_jobs.js index a5e23b6cf91..9d55360919f 100644 --- a/javascriptv3/example_code/transcribe/src/transcribe_list_jobs.js +++ b/javascriptv3/example_code/transcribe/src/transcribe_list_jobs.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/transcribe/src/transcribe_list_medical_jobs.js b/javascriptv3/example_code/transcribe/src/transcribe_list_medical_jobs.js index e2c0db4feaf..43a72bb11cf 100644 --- a/javascriptv3/example_code/transcribe/src/transcribe_list_medical_jobs.js +++ b/javascriptv3/example_code/transcribe/src/transcribe_list_medical_jobs.js @@ -1,6 +1,7 @@ -/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. diff --git a/javascriptv3/example_code/transcribe/tests/babel.config.js b/javascriptv3/example_code/transcribe/tests/babel.config.js index 9a46be1c82a..c11e6ce0817 100644 --- a/javascriptv3/example_code/transcribe/tests/babel.config.js +++ b/javascriptv3/example_code/transcribe/tests/babel.config.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 module.exports = { presets: ["@babel/preset-env"], }; diff --git a/javascriptv3/example_code/transcribe/tests/jest.config.js b/javascriptv3/example_code/transcribe/tests/jest.config.js index 465abcd1d04..6dcf812a335 100644 --- a/javascriptv3/example_code/transcribe/tests/jest.config.js +++ b/javascriptv3/example_code/transcribe/tests/jest.config.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 module.exports = { testEnvironment: "node", moduleDirectories: ["node_modules"], diff --git a/javascriptv3/example_code/transcribe/tests/transcribe_create_job.test.js b/javascriptv3/example_code/transcribe/tests/transcribe_create_job.test.js index 2d4ef415810..82c9bb4e7ef 100644 --- a/javascriptv3/example_code/transcribe/tests/transcribe_create_job.test.js +++ b/javascriptv3/example_code/transcribe/tests/transcribe_create_job.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 jest.mock("../src/libs/transcribeClient"); jest.mock("@aws-sdk/client-transcribe"); diff --git a/javascriptv3/example_code/transcribe/tests/transcribe_create_medical_job.test.js b/javascriptv3/example_code/transcribe/tests/transcribe_create_medical_job.test.js index bd83cdf7ee2..01e9e7879c2 100644 --- a/javascriptv3/example_code/transcribe/tests/transcribe_create_medical_job.test.js +++ b/javascriptv3/example_code/transcribe/tests/transcribe_create_medical_job.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 jest.mock("../src/libs/transcribeClient"); jest.mock("@aws-sdk/client-transcribe"); diff --git a/javascriptv3/example_code/transcribe/tests/transcribe_delete_job.test.js b/javascriptv3/example_code/transcribe/tests/transcribe_delete_job.test.js index 595f2bec348..8c0510f6de2 100644 --- a/javascriptv3/example_code/transcribe/tests/transcribe_delete_job.test.js +++ b/javascriptv3/example_code/transcribe/tests/transcribe_delete_job.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 jest.mock("../src/libs/transcribeClient"); jest.mock("@aws-sdk/client-transcribe"); diff --git a/javascriptv3/example_code/transcribe/tests/transcribe_delete_medical_job.test.js b/javascriptv3/example_code/transcribe/tests/transcribe_delete_medical_job.test.js index 4d1c98b82c8..bb2cea133eb 100644 --- a/javascriptv3/example_code/transcribe/tests/transcribe_delete_medical_job.test.js +++ b/javascriptv3/example_code/transcribe/tests/transcribe_delete_medical_job.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 jest.mock("../src/libs/transcribeClient"); jest.mock("@aws-sdk/client-transcribe"); diff --git a/javascriptv3/example_code/transcribe/tests/transcribe_list_jobs.test.js b/javascriptv3/example_code/transcribe/tests/transcribe_list_jobs.test.js index bd4809ae79e..4174d894caa 100644 --- a/javascriptv3/example_code/transcribe/tests/transcribe_list_jobs.test.js +++ b/javascriptv3/example_code/transcribe/tests/transcribe_list_jobs.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 jest.mock("../src/libs/transcribeClient"); jest.mock("@aws-sdk/client-transcribe"); diff --git a/javascriptv3/example_code/transcribe/tests/transcribe_list_medical_jobs.test.js b/javascriptv3/example_code/transcribe/tests/transcribe_list_medical_jobs.test.js index 9d119cdec81..4986a4f187b 100644 --- a/javascriptv3/example_code/transcribe/tests/transcribe_list_medical_jobs.test.js +++ b/javascriptv3/example_code/transcribe/tests/transcribe_list_medical_jobs.test.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 jest.mock("../src/libs/transcribeClient"); jest.mock("@aws-sdk/client-transcribe"); diff --git a/javascriptv3/example_code/web/s3/list-objects/src/App.tsx b/javascriptv3/example_code/web/s3/list-objects/src/App.tsx index 1c9242b326e..e55621af878 100644 --- a/javascriptv3/example_code/web/s3/list-objects/src/App.tsx +++ b/javascriptv3/example_code/web/s3/list-objects/src/App.tsx @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[javascript.v3.scenarios.web.ListObjects] import { useEffect, useState } from "react"; diff --git a/javascriptv3/example_code/web/s3/list-objects/vite.config.ts b/javascriptv3/example_code/web/s3/list-objects/vite.config.ts index 9cc50ead1c0..48abbc84a33 100644 --- a/javascriptv3/example_code/web/s3/list-objects/vite.config.ts +++ b/javascriptv3/example_code/web/s3/list-objects/vite.config.ts @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; diff --git a/javascriptv3/hook_scripts/pre-commit.sh b/javascriptv3/hook_scripts/pre-commit.sh index 94357acbe5b..6fb8e675f78 100755 --- a/javascriptv3/hook_scripts/pre-commit.sh +++ b/javascriptv3/hook_scripts/pre-commit.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 set -e diff --git a/javav2/example_code/apigateway/src/main/java/com/example/gateway/CreateAPIKey.java b/javav2/example_code/apigateway/src/main/java/com/example/gateway/CreateAPIKey.java index 83e7563787e..d5a64f4e15a 100644 --- a/javav2/example_code/apigateway/src/main/java/com/example/gateway/CreateAPIKey.java +++ b/javav2/example_code/apigateway/src/main/java/com/example/gateway/CreateAPIKey.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[CreateAPIKeys.java demonstrates how to create Api keys.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon API Gateway] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.gateway; @@ -16,7 +10,8 @@ // snippet-end:[apigateway.java2.createapikeys.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -45,7 +40,7 @@ public static void createApiKey(ApiGatewayClient apiGateway) { .generateDistinctId(true) .build(); - //Creating a api key + // Creating a api key CreateApiKeyResponse response = apiGateway.createApiKey(apiKeyRequest); // If we have a plan for the api keys, we can set it for the created api key. @@ -59,8 +54,8 @@ public static void createApiKey(ApiGatewayClient apiGateway) { apiGateway.close(); } catch (ApiGatewayException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); } } // snippet-end:[apigateway.java2.createapikeys.main] diff --git a/javav2/example_code/apigateway/src/main/java/com/example/gateway/CreateDeployment.java b/javav2/example_code/apigateway/src/main/java/com/example/gateway/CreateDeployment.java index 0efd29c222e..10dcc18ae6d 100644 --- a/javav2/example_code/apigateway/src/main/java/com/example/gateway/CreateDeployment.java +++ b/javav2/example_code/apigateway/src/main/java/com/example/gateway/CreateDeployment.java @@ -1,10 +1,6 @@ -//snippet-sourcedescription:[CreateDeployment.java demonstrates how to create a deployment resource.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon API Gateway] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.gateway; // snippet-start:[apigateway.java2.create_deployment.import] @@ -16,7 +12,8 @@ // snippet-end:[apigateway.java2.create_deployment.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -26,11 +23,11 @@ public class CreateDeployment { public static void main(String[] args) { final String USAGE = "\n" + - "Usage:\n" + - " \n\n" + - "Where:\n" + - " restApiId - The string identifier of the associated RestApi. (for example, xxxx99ewyg).\n" + - " stageName - The name of the stage. \n" ; + "Usage:\n" + + " \n\n" + + "Where:\n" + + " restApiId - The string identifier of the associated RestApi. (for example, xxxx99ewyg).\n" + + " stageName - The name of the stage. \n"; if (args.length != 2) { System.out.println(USAGE); @@ -41,8 +38,8 @@ public static void main(String[] args) { String stageName = args[1]; Region region = Region.US_EAST_1; ApiGatewayClient apiGateway = ApiGatewayClient.builder() - .region(region) - .build(); + .region(region) + .build(); createNewDeployment(apiGateway, restApiId, stageName); apiGateway.close(); @@ -53,20 +50,20 @@ public static String createNewDeployment(ApiGatewayClient apiGateway, String res try { CreateDeploymentRequest request = CreateDeploymentRequest.builder() - .restApiId(restApiId) - .description("Created using the AWS API Gateway Java API") - .stageName(stageName) - .build(); + .restApiId(restApiId) + .description("Created using the AWS API Gateway Java API") + .stageName(stageName) + .build(); CreateDeploymentResponse response = apiGateway.createDeployment(request); - System.out.println("The id of the deployment is "+response.id()); + System.out.println("The id of the deployment is " + response.id()); return response.id(); } catch (ApiGatewayException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } - return "" ; + return ""; } // snippet-end:[apigateway.java2.create_deployment.main] } \ No newline at end of file diff --git a/javav2/example_code/apigateway/src/main/java/com/example/gateway/CreateRestApi.java b/javav2/example_code/apigateway/src/main/java/com/example/gateway/CreateRestApi.java index a120af4e5db..596ba029e33 100644 --- a/javav2/example_code/apigateway/src/main/java/com/example/gateway/CreateRestApi.java +++ b/javav2/example_code/apigateway/src/main/java/com/example/gateway/CreateRestApi.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[CreateRestApi.java demonstrates how to create a new RestApi resource.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon API Gateway] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.gateway; @@ -18,7 +12,8 @@ // snippet-end:[apigateway.java2.create_api.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -30,11 +25,11 @@ public class CreateRestApi { public static void main(String[] args) { final String USAGE = "\n" + - "Usage:\n" + - " CreateRestApi \n\n" + - "Where:\n" + - " restApiId - The string identifier of an existing RestApi. (for example, xxxx99ewyg).\n" + - " restApiName - The name to use for the new RestApi. \n" ; + "Usage:\n" + + " CreateRestApi \n\n" + + "Where:\n" + + " restApiId - The string identifier of an existing RestApi. (for example, xxxx99ewyg).\n" + + " restApiName - The name to use for the new RestApi. \n"; if (args.length != 2) { System.out.println(USAGE); @@ -44,25 +39,25 @@ public static void main(String[] args) { String restApiName = args[1]; Region region = Region.US_EAST_1; ApiGatewayClient apiGateway = ApiGatewayClient.builder() - .region(region) - .build(); + .region(region) + .build(); createAPI(apiGateway, restApiId, restApiName); apiGateway.close(); } // snippet-start:[apigateway.java2.create_api.main] - public static String createAPI( ApiGatewayClient apiGateway, String restApiId, String restApiName) { + public static String createAPI(ApiGatewayClient apiGateway, String restApiId, String restApiName) { try { CreateRestApiRequest request = CreateRestApiRequest.builder() - .cloneFrom(restApiId) - .description("Created using the Gateway Java API") - .name(restApiName) - .build(); + .cloneFrom(restApiId) + .description("Created using the Gateway Java API") + .name(restApiName) + .build(); CreateRestApiResponse response = apiGateway.createRestApi(request); - System.out.println("The id of the new api is "+response.id()); + System.out.println("The id of the new api is " + response.id()); return response.id(); } catch (ApiGatewayException e) { @@ -73,4 +68,3 @@ public static String createAPI( ApiGatewayClient apiGateway, String restApiId, S } // snippet-end:[apigateway.java2.create_api.main] } - diff --git a/javav2/example_code/apigateway/src/main/java/com/example/gateway/DeleteDeployment.java b/javav2/example_code/apigateway/src/main/java/com/example/gateway/DeleteDeployment.java index 202b86765db..3a230e62e89 100644 --- a/javav2/example_code/apigateway/src/main/java/com/example/gateway/DeleteDeployment.java +++ b/javav2/example_code/apigateway/src/main/java/com/example/gateway/DeleteDeployment.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DeleteDeployment.java demonstrates how to delete a deployment.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon API Gateway] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.gateway; @@ -17,7 +11,8 @@ // snippet-end:[apigateway.java2.delete_deployment.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -33,7 +28,7 @@ public static void main(String[] args) { " DeleteDeployment \n\n" + "Where:\n" + " restApiId - The string identifier of an existing RestApi. (for example, xxxx99ewyg).\n" + - " deploymentId - The string identifier of an existing deployment. \n" ; + " deploymentId - The string identifier of an existing deployment. \n"; if (args.length != 2) { System.out.println(USAGE); @@ -41,7 +36,7 @@ public static void main(String[] args) { } String restApiId = args[0]; - String deploymentId = args[1]; + String deploymentId = args[1]; Region region = Region.US_EAST_1; ApiGatewayClient apiGateway = ApiGatewayClient.builder() .region(region) @@ -49,19 +44,19 @@ public static void main(String[] args) { deleteSpecificDeployment(apiGateway, restApiId, deploymentId); apiGateway.close(); - } + } // snippet-start:[apigateway.java2.delete_deployment.main] public static void deleteSpecificDeployment(ApiGatewayClient apiGateway, String restApiId, String deploymentId) { try { DeleteDeploymentRequest request = DeleteDeploymentRequest.builder() - .restApiId(restApiId) - .deploymentId(deploymentId) - .build(); + .restApiId(restApiId) + .deploymentId(deploymentId) + .build(); apiGateway.deleteDeployment(request); - System.out.println("Deployment was deleted" ); + System.out.println("Deployment was deleted"); } catch (ApiGatewayException e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/apigateway/src/main/java/com/example/gateway/DeleteRestApi.java b/javav2/example_code/apigateway/src/main/java/com/example/gateway/DeleteRestApi.java index 6d0a130d240..f5d953da4c3 100644 --- a/javav2/example_code/apigateway/src/main/java/com/example/gateway/DeleteRestApi.java +++ b/javav2/example_code/apigateway/src/main/java/com/example/gateway/DeleteRestApi.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DeleteRestApi.java demonstrates how to delete an existing RestApi resource.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon API Gateway] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.gateway; @@ -16,9 +10,9 @@ import software.amazon.awssdk.services.apigateway.model.DeleteRestApiRequest; // snippet-end:[apigateway.java2.delete_api.import] - /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -33,7 +27,7 @@ public static void main(String[] args) { "Usage:\n" + " DeleteRestApi \n\n" + "Where:\n" + - " restApiId - The string identifier of an existing RestApi. (for example, xxxx99ewyg).\n" ; + " restApiId - The string identifier of an existing RestApi. (for example, xxxx99ewyg).\n"; if (args.length != 1) { System.out.println(USAGE); @@ -51,12 +45,12 @@ public static void main(String[] args) { } // snippet-start:[apigateway.java2.delete_api.main] - public static void deleteAPI( ApiGatewayClient apiGateway, String restApiId) { + public static void deleteAPI(ApiGatewayClient apiGateway, String restApiId) { try { DeleteRestApiRequest request = DeleteRestApiRequest.builder() - .restApiId(restApiId) - .build(); + .restApiId(restApiId) + .build(); apiGateway.deleteRestApi(request); System.out.println("The API was successfully deleted"); @@ -68,4 +62,3 @@ public static void deleteAPI( ApiGatewayClient apiGateway, String restApiId) { } // snippet-end:[apigateway.java2.delete_api.main] } - diff --git a/javav2/example_code/apigateway/src/main/java/com/example/gateway/GetAPIKeys.java b/javav2/example_code/apigateway/src/main/java/com/example/gateway/GetAPIKeys.java index d9cf10d4c1d..d16a3084868 100644 --- a/javav2/example_code/apigateway/src/main/java/com/example/gateway/GetAPIKeys.java +++ b/javav2/example_code/apigateway/src/main/java/com/example/gateway/GetAPIKeys.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[GetAPIKeys.java demonstrates how to obtain information about the current ApiKeys resource.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon API Gateway] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.gateway; @@ -18,7 +13,8 @@ // snippet-end:[apigateway.java2.get_apikeys.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -44,9 +40,9 @@ public static void getKeys(ApiGatewayClient apiGateway) { try { GetApiKeysResponse response = apiGateway.getApiKeys(); List keys = response.items(); - for (ApiKey key: keys) { - System.out.println("key id is: "+key.id()); - System.out.println("key name is: "+key.name()); + for (ApiKey key : keys) { + System.out.println("key id is: " + key.id()); + System.out.println("key name is: " + key.name()); } } catch (ApiGatewayException e) { diff --git a/javav2/example_code/apigateway/src/main/java/com/example/gateway/GetDeployments.java b/javav2/example_code/apigateway/src/main/java/com/example/gateway/GetDeployments.java index f48e9675a2a..3a14e487ade 100644 --- a/javav2/example_code/apigateway/src/main/java/com/example/gateway/GetDeployments.java +++ b/javav2/example_code/apigateway/src/main/java/com/example/gateway/GetDeployments.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[GetDeployments.java demonstrates how to get information about a deployment collection.] -//snippet-keyword:[SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon API Gateway] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.gateway; @@ -21,7 +14,8 @@ // snippet-end:[apigateway.java2.get_deployments.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -36,36 +30,36 @@ public static void main(String[] args) { "Usage:\n" + " GetDeployments \n\n" + "Where:\n" + - " restApiId - The string identifier of an existing RestApi. (for example, xxxx99ewyg).\n" ; + " restApiId - The string identifier of an existing RestApi. (for example, xxxx99ewyg).\n"; - if (args.length != 1) { - System.out.println(USAGE); - System.exit(1); + if (args.length != 1) { + System.out.println(USAGE); + System.exit(1); } - String restApiId = "inx39975"; // args[0]; - Region region = Region.US_EAST_1; - ApiGatewayClient apiGateway = ApiGatewayClient.builder() - .region(region) - .build(); + String restApiId = "inx39975"; // args[0]; + Region region = Region.US_EAST_1; + ApiGatewayClient apiGateway = ApiGatewayClient.builder() + .region(region) + .build(); - getAllDeployments(apiGateway, restApiId); - apiGateway.close(); + getAllDeployments(apiGateway, restApiId); + apiGateway.close(); } // snippet-start:[apigateway.java2.get_deployments.main] - public static void getAllDeployments(ApiGatewayClient apiGateway, String restApiId) { + public static void getAllDeployments(ApiGatewayClient apiGateway, String restApiId) { try { GetDeploymentsRequest request = GetDeploymentsRequest.builder() - .restApiId(restApiId) - .build(); + .restApiId(restApiId) + .build(); GetDeploymentsResponse response = apiGateway.getDeployments(request); List deployments = response.items(); - for (Deployment deployment: deployments) { - System.out.println("The deployment id is "+deployment.id()); - System.out.println("The deployment description is "+deployment.description()); + for (Deployment deployment : deployments) { + System.out.println("The deployment id is " + deployment.id()); + System.out.println("The deployment description is " + deployment.description()); } } catch (ApiGatewayException e) { diff --git a/javav2/example_code/apigateway/src/main/java/com/example/gateway/GetMethod.java b/javav2/example_code/apigateway/src/main/java/com/example/gateway/GetMethod.java index 57bc25849f7..0df22f3fda0 100644 --- a/javav2/example_code/apigateway/src/main/java/com/example/gateway/GetMethod.java +++ b/javav2/example_code/apigateway/src/main/java/com/example/gateway/GetMethod.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[GetMethod.java demonstrates how to describe an existing method resource..] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon API Gateway] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.gateway; @@ -20,7 +14,8 @@ // snippet-end:[apigateway.java2.get_method.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -32,26 +27,25 @@ public class GetMethod { public static void main(String[] args) { final String USAGE = "\n" + - "Usage:\n" + - " GetMethod \n\n" + - "Where:\n" + - " restApiId - The string identifier of an existing RestApi. (for example, xxxx99ewyg).\n" + - " resourceId - The string identifier of an resource. (for example, xxxx99ewyg).\n" + - " httpMethod - The HTTP method. (for example, GET).\n" ; + "Usage:\n" + + " GetMethod \n\n" + + "Where:\n" + + " restApiId - The string identifier of an existing RestApi. (for example, xxxx99ewyg).\n" + + " resourceId - The string identifier of an resource. (for example, xxxx99ewyg).\n" + + " httpMethod - The HTTP method. (for example, GET).\n"; if (args.length != 3) { System.out.println(USAGE); System.exit(1); } - String restApiId = args[0]; + String restApiId = args[0]; String resourceId = args[1]; String httpMethod = args[2]; Region region = Region.US_EAST_1; ApiGatewayClient apiGateway = ApiGatewayClient.builder() - .region(region) - .build(); - + .region(region) + .build(); getSpecificMethod(apiGateway, restApiId, resourceId, httpMethod); apiGateway.close(); @@ -59,22 +53,22 @@ public static void main(String[] args) { // snippet-start:[apigateway.java2.get_method.main] public static void getSpecificMethod(ApiGatewayClient apiGateway, - String restApiId, - String resourceId, - String httpMethod) { + String restApiId, + String resourceId, + String httpMethod) { try { GetMethodRequest methodRequest = GetMethodRequest.builder() - .httpMethod(httpMethod) - .restApiId(restApiId) - .resourceId(resourceId) - .build(); + .httpMethod(httpMethod) + .restApiId(restApiId) + .resourceId(resourceId) + .build(); GetMethodResponse response = apiGateway.getMethod(methodRequest); // Retrieve a method response associated with a given HTTP status code. Map details = response.methodResponses(); - for (Map.Entry entry : details.entrySet()) + for (Map.Entry entry : details.entrySet()) System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); diff --git a/javav2/example_code/apigateway/src/main/java/com/example/gateway/GetStages.java b/javav2/example_code/apigateway/src/main/java/com/example/gateway/GetStages.java index 8c01d3976ab..916d5d9f798 100644 --- a/javav2/example_code/apigateway/src/main/java/com/example/gateway/GetStages.java +++ b/javav2/example_code/apigateway/src/main/java/com/example/gateway/GetStages.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[GetStages.java demonstrates how to get information about stages.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon API Gateway] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.gateway; @@ -17,7 +11,8 @@ // snippet-end:[apigateway.java2.get_stages.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -28,10 +23,10 @@ public class GetStages { public static void main(String[] args) { final String USAGE = "\n" + - "Usage:\n" + - " GetStages \n\n" + - "Where:\n" + - " restApiId - The string identifier of an existing RestApi. (for example, xxxx99ewyg).\n" ; + "Usage:\n" + + " GetStages \n\n" + + "Where:\n" + + " restApiId - The string identifier of an existing RestApi. (for example, xxxx99ewyg).\n"; if (args.length != 1) { System.out.println(USAGE); @@ -41,8 +36,8 @@ public static void main(String[] args) { String restApiId = args[0]; Region region = Region.US_EAST_1; ApiGatewayClient apiGateway = ApiGatewayClient.builder() - .region(region) - .build(); + .region(region) + .build(); getAllStages(apiGateway, restApiId); apiGateway.close(); @@ -53,13 +48,13 @@ public static void getAllStages(ApiGatewayClient apiGateway, String restApiId) { try { GetStagesRequest stagesRequest = GetStagesRequest.builder() - .restApiId(restApiId) - .build(); + .restApiId(restApiId) + .build(); GetStagesResponse response = apiGateway.getStages(stagesRequest); List stages = response.item(); - for (Stage stage: stages) { - System.out.println("Stage name is: "+stage.stageName()); + for (Stage stage : stages) { + System.out.println("Stage name is: " + stage.stageName()); } } catch (ApiGatewayException e) { @@ -69,4 +64,3 @@ public static void getAllStages(ApiGatewayClient apiGateway, String restApiId) { } // snippet-end:[apigateway.java2.get_stages.main] } - diff --git a/javav2/example_code/apigateway/src/main/java/com/example/gateway/ImportRestApi.java b/javav2/example_code/apigateway/src/main/java/com/example/gateway/ImportRestApi.java index 0b33f5f25b5..677eff61279 100644 --- a/javav2/example_code/apigateway/src/main/java/com/example/gateway/ImportRestApi.java +++ b/javav2/example_code/apigateway/src/main/java/com/example/gateway/ImportRestApi.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[ImportRestApi.java demonstrates how to import a new RestApi resource from a swagger / open api specifications.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon API Gateway] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.gateway; @@ -25,7 +19,8 @@ // snippet-end:[apigateway.java2.import_api.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -37,58 +32,55 @@ public class ImportRestApi { public static void main(String[] args) { final String USAGE = "\n" + - "Usage:\n" + - " ImportRestApi \n\n" + - "Where:\n" + - " swaggerFilePath - The file path of a swagger specifications file. (for example, example-api.json - also provided in the project - from the console example api).\n" + - " If swaggerFilePath is not provided it will default to example-api.json. \n" + - " If constructing own api.json files might need to improve the json file. \n" + - " Also useful to add x-amazon-apigateway-integration as shown in the example-api.json. \n" ; - String swaggerFilePath="example-api.json"; + "Usage:\n" + + " ImportRestApi \n\n" + + "Where:\n" + + " swaggerFilePath - The file path of a swagger specifications file. (for example, example-api.json - also provided in the project - from the console example api).\n" + + + " If swaggerFilePath is not provided it will default to example-api.json. \n" + + " If constructing own api.json files might need to improve the json file. \n" + + " Also useful to add x-amazon-apigateway-integration as shown in the example-api.json. \n"; + String swaggerFilePath = "example-api.json"; if (args.length == 0) { System.out.println(USAGE); - - } - else - { - swaggerFilePath = args[0]; + + } else { + swaggerFilePath = args[0]; } - System.out.println("Using swaggerFilePath="+swaggerFilePath); - - + System.out.println("Using swaggerFilePath=" + swaggerFilePath); + Region region = Region.US_EAST_1; ApiGatewayClient apiGateway = ApiGatewayClient.builder() - .region(region) - .build(); + .region(region) + .build(); importAPI(apiGateway, swaggerFilePath); apiGateway.close(); } // snippet-start:[apigateway.java2.import_api.main] - public static String importAPI( ApiGatewayClient apiGateway, String swaggerFilePath) { - Map parameters= new HashMap<>(); - parameters.put("endpointConfigurationTypes", "REGIONAL"); - try( FileInputStream fis=new FileInputStream(new File(swaggerFilePath))) { - ImportRestApiRequest request = ImportRestApiRequest.builder() - .failOnWarnings(true) - .parameters(parameters) - .body(SdkBytes.fromInputStream(fis)) - .build(); + public static String importAPI(ApiGatewayClient apiGateway, String swaggerFilePath) { + Map parameters = new HashMap<>(); + parameters.put("endpointConfigurationTypes", "REGIONAL"); + try (FileInputStream fis = new FileInputStream(new File(swaggerFilePath))) { + ImportRestApiRequest request = ImportRestApiRequest.builder() + .failOnWarnings(true) + .parameters(parameters) + .body(SdkBytes.fromInputStream(fis)) + .build(); - ImportRestApiResponse response = apiGateway.importRestApi(request); - System.out.println("The id of the new api is "+response.id()); + ImportRestApiResponse response = apiGateway.importRestApi(request); + System.out.println("The id of the new api is " + response.id()); return response.id(); } catch (ApiGatewayException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } catch (IOException e) { - System.err.println(e.getMessage()); + System.err.println(e.getMessage()); System.exit(1); - } + } return ""; } // snippet-end:[apigateway.java2.import_api.main] } - diff --git a/javav2/example_code/apigateway/src/test/java/APIGatewayTest.java b/javav2/example_code/apigateway/src/test/java/APIGatewayTest.java index 3a0116ba59c..16bb2472742 100644 --- a/javav2/example_code/apigateway/src/test/java/APIGatewayTest.java +++ b/javav2/example_code/apigateway/src/test/java/APIGatewayTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.gateway.*; import com.google.gson.Gson; @@ -45,34 +43,37 @@ public static void setUp() throws IOException { SecretValues values = gson.fromJson(json, SecretValues.class); restApiId = values.getRestApiId(); httpMethod = values.getHttpMethod(); - restApiName = values.getRestApiName()+randomNum; + restApiName = values.getRestApiName() + randomNum; stageName = values.getStageName(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - try (InputStream input = APIGatewayTest.class.getClassLoader().getResourceAsStream("config.properties")) { - - Properties prop = new Properties(); - - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - //load a properties file from class path, inside static method - prop.load(input); - - // Populate the data members required for all tests - restApiId = prop.getProperty("restApiId"); - resourceId = prop.getProperty("resourceId"); - httpMethod = prop.getProperty("httpMethod"); - restApiName = prop.getProperty("restApiName"); - stageName = prop.getProperty("stageName"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * try (InputStream input = + * APIGatewayTest.class.getClassLoader().getResourceAsStream("config.properties" + * )) { + * + * Properties prop = new Properties(); + * + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * //load a properties file from class path, inside static method + * prop.load(input); + * + * // Populate the data members required for all tests + * restApiId = prop.getProperty("restApiId"); + * resourceId = prop.getProperty("resourceId"); + * httpMethod = prop.getProperty("httpMethod"); + * restApiName = prop.getProperty("restApiName"); + * stageName = prop.getProperty("stageName"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @@ -94,33 +95,34 @@ public void CreateDeployment() { @Test @Order(3) public void GetDeployments() { - assertDoesNotThrow(() ->GetDeployments.getAllDeployments(apiGateway, newApiId)); + assertDoesNotThrow(() -> GetDeployments.getAllDeployments(apiGateway, newApiId)); System.out.println("Test 4 passed"); } @Test @Order(4) public void GetStages() { - assertDoesNotThrow(() ->GetStages.getAllStages(apiGateway, newApiId)); + assertDoesNotThrow(() -> GetStages.getAllStages(apiGateway, newApiId)); System.out.println("Test 7 passed"); } @Test @Order(5) public void DeleteRestApi() { - assertDoesNotThrow(() ->DeleteRestApi.deleteAPI(apiGateway, newApiId)); + assertDoesNotThrow(() -> DeleteRestApi.deleteAPI(apiGateway, newApiId)); System.out.println("Test 9 passed"); } + private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/apigateway"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -152,4 +154,3 @@ public String getStageName() { } } } - diff --git a/javav2/example_code/appsync/src/main/java/com/example/appsync/CreateApiKey.java b/javav2/example_code/appsync/src/main/java/com/example/appsync/CreateApiKey.java index 91db7ae143d..8130f795a05 100644 --- a/javav2/example_code/appsync/src/main/java/com/example/appsync/CreateApiKey.java +++ b/javav2/example_code/appsync/src/main/java/com/example/appsync/CreateApiKey.java @@ -1,24 +1,20 @@ -// snippet-sourcedescription:[CreateApiKey.java demonstrates how to create a unique key.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS AppSync] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.appsync; -//snippet-start:[appsync.java2.create_key.main] -//snippet-start:[appsync.java2.create_key.import] +// snippet-start:[appsync.java2.create_key.main] +// snippet-start:[appsync.java2.create_key.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.appsync.AppSyncClient; import software.amazon.awssdk.services.appsync.model.AppSyncException; import software.amazon.awssdk.services.appsync.model.CreateApiKeyRequest; import software.amazon.awssdk.services.appsync.model.CreateApiKeyResponse; -//snippet-end:[appsync.java2.create_key.import] +// snippet-end:[appsync.java2.create_key.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +24,12 @@ public class CreateApiKey { public static void main(String[] args) { final String usage = """ - Usage: \s + Usage: \s - Where: - apiId - the id of the API (You can get this value from the AWS Management Console).\s + Where: + apiId - the id of the API (You can get this value from the AWS Management Console).\s - """; + """; if (args.length != 1) { System.out.println(usage); @@ -45,16 +41,16 @@ public static void main(String[] args) { .region(Region.US_EAST_1) .build(); - String id = createKey(appSyncClient, apiId) ; - System.out.println("The Id of the new Key is "+id); + String id = createKey(appSyncClient, apiId); + System.out.println("The Id of the new Key is " + id); } public static String createKey(AppSyncClient appSyncClient, String apiId) { try { CreateApiKeyRequest apiKeyRequest = CreateApiKeyRequest.builder() - .apiId(apiId) - .description("Created using the AWS SDK for Java") - .build(); + .apiId(apiId) + .description("Created using the AWS SDK for Java") + .build(); CreateApiKeyResponse response = appSyncClient.createApiKey(apiKeyRequest); return response.apiKey().id(); @@ -66,4 +62,4 @@ public static String createKey(AppSyncClient appSyncClient, String apiId) { return ""; } } -//snippet-end:[appsync.java2.create_key.main] +// snippet-end:[appsync.java2.create_key.main] diff --git a/javav2/example_code/appsync/src/main/java/com/example/appsync/CreateDataSource.java b/javav2/example_code/appsync/src/main/java/com/example/appsync/CreateDataSource.java index a8e83c7c41f..d3d2b9b6522 100644 --- a/javav2/example_code/appsync/src/main/java/com/example/appsync/CreateDataSource.java +++ b/javav2/example_code/appsync/src/main/java/com/example/appsync/CreateDataSource.java @@ -1,16 +1,10 @@ -// snippet-sourcedescription:[CreateDataSource.java demonstrates how to create an AWS AppSync data source that uses Amazon DynamoDB.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS AppSync] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.appsync; -//snippet-start:[appsync.java2.create_ds.main] -//snippet-start:[appsync.java2.create_ds.import] +// snippet-start:[appsync.java2.create_ds.main] +// snippet-start:[appsync.java2.create_ds.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.appsync.AppSyncClient; import software.amazon.awssdk.services.appsync.model.DynamodbDataSourceConfig; @@ -18,10 +12,11 @@ import software.amazon.awssdk.services.appsync.model.DataSourceType; import software.amazon.awssdk.services.appsync.model.CreateDataSourceResponse; import software.amazon.awssdk.services.appsync.model.AppSyncException; -//snippet-end:[appsync.java2.create_ds.import] +// snippet-end:[appsync.java2.create_ds.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,19 +27,19 @@ public class CreateDataSource { public static void main(String[] args) { final String USAGE = """ - Usage: + Usage: - Where: - apiId - The id of the API (You can get this value from the AWS Management Console).\s - name - The name of the data source.\s - dsRole - The AWS Identity and Access Management (IAM) service role for the data source.\s - tableName - The name of the Amazon DynamoDB table used as the data source.\s - """; + Where: + apiId - The id of the API (You can get this value from the AWS Management Console).\s + name - The name of the data source.\s + dsRole - The AWS Identity and Access Management (IAM) service role for the data source.\s + tableName - The name of the Amazon DynamoDB table used as the data source.\s + """; if (args.length != 4) { - System.out.println(USAGE); - System.exit(1); - } + System.out.println(USAGE); + System.exit(1); + } String apiId = args[0]; String name = args[1]; @@ -55,10 +50,11 @@ public static void main(String[] args) { .build(); String dsARN = createDS(appSyncClient, name, String.valueOf(Region.US_EAST_1), dsRole, apiId, tableName); - System.out.println("The ARN of the data source is "+dsARN); + System.out.println("The ARN of the data source is " + dsARN); } - public static String createDS(AppSyncClient appSyncClient, String name, String reg, String dsRole, String apiVal, String tableName) { + public static String createDS(AppSyncClient appSyncClient, String name, String reg, String dsRole, String apiVal, + String tableName) { try { DynamodbDataSourceConfig config = DynamodbDataSourceConfig.builder() .awsRegion(reg) @@ -85,4 +81,4 @@ public static String createDS(AppSyncClient appSyncClient, String name, String r return ""; } } -//snippet-end:[appsync.java2.create_ds.main] +// snippet-end:[appsync.java2.create_ds.main] diff --git a/javav2/example_code/appsync/src/main/java/com/example/appsync/DeleteApiKey.java b/javav2/example_code/appsync/src/main/java/com/example/appsync/DeleteApiKey.java index 6b0c9a0560e..76fda301621 100644 --- a/javav2/example_code/appsync/src/main/java/com/example/appsync/DeleteApiKey.java +++ b/javav2/example_code/appsync/src/main/java/com/example/appsync/DeleteApiKey.java @@ -1,23 +1,19 @@ -// snippet-sourcedescription:[DeleteApiKey.java demonstrates how to delete a key.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS AppSync] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.appsync; -//snippet-start:[appsync.java2.del_key.main] -//snippet-start:[appsync.java2.del_key.import] +// snippet-start:[appsync.java2.del_key.main] +// snippet-start:[appsync.java2.del_key.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.appsync.AppSyncClient; import software.amazon.awssdk.services.appsync.model.AppSyncException; import software.amazon.awssdk.services.appsync.model.DeleteApiKeyRequest; -//snippet-end:[appsync.java2.del_key.import] +// snippet-end:[appsync.java2.del_key.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +24,12 @@ public class DeleteApiKey { public static void main(String[] args) { final String usage = """ - Usage: \s + Usage: \s - Where: - apiId - the id of the API (You can get this value from the AWS Management Console).\s - keyId - The Id of the key to delete. - """; + Where: + apiId - the id of the API (You can get this value from the AWS Management Console).\s + keyId - The Id of the key to delete. + """; if (args.length != 2) { System.out.println(usage); @@ -45,7 +41,7 @@ public static void main(String[] args) { AppSyncClient appSyncClient = AppSyncClient.builder() .region(Region.US_EAST_1) .build(); - deleteKey(appSyncClient, keyId, apiId) ; + deleteKey(appSyncClient, keyId, apiId); } public static void deleteKey(AppSyncClient appSyncClient, String keyId, String apiId) { @@ -64,4 +60,4 @@ public static void deleteKey(AppSyncClient appSyncClient, String keyId, String a } } } -//snippet-end:[appsync.java2.del_key.main] +// snippet-end:[appsync.java2.del_key.main] diff --git a/javav2/example_code/appsync/src/main/java/com/example/appsync/DeleteDataSource.java b/javav2/example_code/appsync/src/main/java/com/example/appsync/DeleteDataSource.java index ceb89c1ecae..7c1e9635920 100644 --- a/javav2/example_code/appsync/src/main/java/com/example/appsync/DeleteDataSource.java +++ b/javav2/example_code/appsync/src/main/java/com/example/appsync/DeleteDataSource.java @@ -1,23 +1,19 @@ -// snippet-sourcedescription:[DeleteDataSource.java demonstrates how to delete an AWS AppSync data source.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS AppSync] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.appsync; -//snippet-start:[appsync.java2.del_ds.main] -//snippet-start:[appsync.java2.del_ds.import] +// snippet-start:[appsync.java2.del_ds.main] +// snippet-start:[appsync.java2.del_ds.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.appsync.AppSyncClient; import software.amazon.awssdk.services.appsync.model.AppSyncException; import software.amazon.awssdk.services.appsync.model.DeleteDataSourceRequest; -//snippet-end:[appsync.java2.del_ds.import] +// snippet-end:[appsync.java2.del_ds.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,13 +23,13 @@ public class DeleteDataSource { public static void main(String[] args) { final String usage = """ - Usage: \s + Usage: \s - Where: - apiId - the id of the API (You can get this value from the AWS Management Console).\s + Where: + apiId - the id of the API (You can get this value from the AWS Management Console).\s - dsName - The name of the data source to delete. - """; + dsName - The name of the data source to delete. + """; if (args.length != 2) { System.out.println(usage); @@ -45,15 +41,15 @@ public static void main(String[] args) { AppSyncClient appSyncClient = AppSyncClient.builder() .region(Region.US_EAST_1) .build(); - deleteDS(appSyncClient, apiId, dsName) ; + deleteDS(appSyncClient, apiId, dsName); } - public static void deleteDS( AppSyncClient appSyncClient, String apiId, String dsName) { + public static void deleteDS(AppSyncClient appSyncClient, String apiId, String dsName) { try { DeleteDataSourceRequest request = DeleteDataSourceRequest.builder() - .apiId(apiId) - .name(dsName) - .build(); + .apiId(apiId) + .name(dsName) + .build(); appSyncClient.deleteDataSource(request); System.out.println("The data source was deleted."); @@ -64,4 +60,4 @@ public static void deleteDS( AppSyncClient appSyncClient, String apiId, String d } } } -//snippet-end:[appsync.java2.del_ds.main] +// snippet-end:[appsync.java2.del_ds.main] diff --git a/javav2/example_code/appsync/src/main/java/com/example/appsync/GetDataSource.java b/javav2/example_code/appsync/src/main/java/com/example/appsync/GetDataSource.java index 6e75a987275..25dcc431b19 100644 --- a/javav2/example_code/appsync/src/main/java/com/example/appsync/GetDataSource.java +++ b/javav2/example_code/appsync/src/main/java/com/example/appsync/GetDataSource.java @@ -1,25 +1,20 @@ -// snippet-sourcedescription:[GetDataSource.java demonstrates how to retrieve an AWS AppSync data source.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS AppSync] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.appsync; -//snippet-start:[appsync.java2.get_ds.main] -//snippet-start:[appsync.java2.get_ds.import] +// snippet-start:[appsync.java2.get_ds.main] +// snippet-start:[appsync.java2.get_ds.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.appsync.AppSyncClient; import software.amazon.awssdk.services.appsync.model.GetDataSourceRequest; import software.amazon.awssdk.services.appsync.model.GetDataSourceResponse; import software.amazon.awssdk.services.appsync.model.AppSyncException; -//snippet-end:[appsync.java2.get_ds.import] +// snippet-end:[appsync.java2.get_ds.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,16 +24,16 @@ public class GetDataSource { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - apiId - The id of the API (You can get this value from the AWS Management Console).\s - name - The name of the data source.\s - """; + Where: + apiId - The id of the API (You can get this value from the AWS Management Console).\s + name - The name of the data source.\s + """; if (args.length != 2) { - System.out.println(usage); - System.exit(1); + System.out.println(usage); + System.exit(1); } String apiId = args[0]; @@ -50,15 +45,15 @@ public static void main(String[] args) { getDS(appSyncClient, apiId, name); } - public static void getDS(AppSyncClient appSyncClient, String apiId, String name ) { + public static void getDS(AppSyncClient appSyncClient, String apiId, String name) { try { GetDataSourceRequest request = GetDataSourceRequest.builder() - .apiId(apiId) - .name(name) - .build(); + .apiId(apiId) + .name(name) + .build(); GetDataSourceResponse response = appSyncClient.getDataSource(request); - System.out.println("The DataSource ARN is "+response.dataSource().dataSourceArn()); + System.out.println("The DataSource ARN is " + response.dataSource().dataSourceArn()); } catch (AppSyncException e) { System.out.println(e.getMessage()); @@ -66,4 +61,4 @@ public static void getDS(AppSyncClient appSyncClient, String apiId, String name } } } -//snippet-end:[appsync.java2.get_ds.main] +// snippet-end:[appsync.java2.get_ds.main] diff --git a/javav2/example_code/appsync/src/main/java/com/example/appsync/ListApiKeys.java b/javav2/example_code/appsync/src/main/java/com/example/appsync/ListApiKeys.java index 7c4313e5ebe..07fb94853e3 100644 --- a/javav2/example_code/appsync/src/main/java/com/example/appsync/ListApiKeys.java +++ b/javav2/example_code/appsync/src/main/java/com/example/appsync/ListApiKeys.java @@ -1,16 +1,10 @@ -// snippet-sourcedescription:[ListApiKeys.java demonstrates how to get API keys.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS AppSync] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.appsync; -//snippet-start:[appsync.java.get_keys.main] -//snippet-start:[appsync.java.get_keys.import] +// snippet-start:[appsync.java.get_keys.main] +// snippet-start:[appsync.java.get_keys.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.appsync.AppSyncClient; import software.amazon.awssdk.services.appsync.model.ApiKey; @@ -18,17 +12,17 @@ import software.amazon.awssdk.services.appsync.model.ListApiKeysRequest; import software.amazon.awssdk.services.appsync.model.ListApiKeysResponse; import java.util.List; -//snippet-end:[appsync.java.get_keys.import] +// snippet-end:[appsync.java.get_keys.import] public class ListApiKeys { public static void main(String[] args) { final String usage = """ - Usage: \s + Usage: \s - Where: - apiId - The id of the API (You can get this value from the AWS Management Console).\s - """; + Where: + apiId - The id of the API (You can get this value from the AWS Management Console).\s + """; if (args.length != 1) { System.out.println(usage); @@ -37,8 +31,8 @@ public static void main(String[] args) { String apiId = args[0]; AppSyncClient appSyncClient = AppSyncClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); getKeys(appSyncClient, apiId); } @@ -46,13 +40,13 @@ public static void main(String[] args) { public static void getKeys(AppSyncClient appSyncClient, String apiId) { try { ListApiKeysRequest request = ListApiKeysRequest.builder() - .apiId(apiId) - .build(); + .apiId(apiId) + .build(); ListApiKeysResponse response = appSyncClient.listApiKeys(request); List keys = response.apiKeys(); - for (ApiKey key: keys) { - System.out.println("The key Id is : "+key.id()); + for (ApiKey key : keys) { + System.out.println("The key Id is : " + key.id()); } } catch (AppSyncException e) { @@ -61,4 +55,4 @@ public static void getKeys(AppSyncClient appSyncClient, String apiId) { } } } -//snippet-end:[appsync.java.get_keys.main] \ No newline at end of file +// snippet-end:[appsync.java.get_keys.main] \ No newline at end of file diff --git a/javav2/example_code/appsync/src/main/java/com/example/appsync/ListGraphqlApis.java b/javav2/example_code/appsync/src/main/java/com/example/appsync/ListGraphqlApis.java index c18dd69f1c2..dd9284107c5 100644 --- a/javav2/example_code/appsync/src/main/java/com/example/appsync/ListGraphqlApis.java +++ b/javav2/example_code/appsync/src/main/java/com/example/appsync/ListGraphqlApis.java @@ -1,26 +1,21 @@ -// snippet-sourcedescription:[ListGraphqlApis.java demonstrates how to list your AWS AppSync API operations.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS AppSync] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.appsync; -//snippet-start:[appsync.java2.get_apis.main] -//snippet-start:[appsync.java2.get_apis.import] +// snippet-start:[appsync.java2.get_apis.main] +// snippet-start:[appsync.java2.get_apis.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.appsync.AppSyncClient; import software.amazon.awssdk.services.appsync.model.AppSyncException; import software.amazon.awssdk.services.appsync.model.GraphqlApi; import software.amazon.awssdk.services.appsync.model.ListGraphqlApisResponse; import java.util.List; -//snippet-end:[appsync.java2.get_apis.import] +// snippet-end:[appsync.java2.get_apis.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,8 +24,8 @@ public class ListGraphqlApis { public static void main(String[] args) { AppSyncClient appSyncClient = AppSyncClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); getApis(appSyncClient); } @@ -51,4 +46,4 @@ public static void getApis(AppSyncClient appSyncClient) { } } } -//snippet-end:[appsync.java2.get_apis.main] \ No newline at end of file +// snippet-end:[appsync.java2.get_apis.main] \ No newline at end of file diff --git a/javav2/example_code/appsync/src/test/java/AppSyncTest.java b/javav2/example_code/appsync/src/test/java/AppSyncTest.java index 5166b000897..65fb0e31993 100644 --- a/javav2/example_code/appsync/src/test/java/AppSyncTest.java +++ b/javav2/example_code/appsync/src/test/java/AppSyncTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.appsync.*; import com.google.gson.Gson; @@ -11,7 +9,7 @@ import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.services.appsync.AppSyncClient; import java.io.*; -import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; @@ -24,11 +22,11 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AppSyncTest { private static AppSyncClient appSyncClient; - private static String apiId=""; - private static String dsName=""; - private static String dsRole=""; - private static String tableName=""; - private static String keyId = ""; // Gets dynamically set in a test. + private static String apiId = ""; + private static String dsName = ""; + private static String dsRole = ""; + private static String tableName = ""; + private static String keyId = ""; // Gets dynamically set in a test. private static String dsARN = ""; // Gets dynamically set in a test. private static String reg = ""; @@ -37,9 +35,9 @@ public static void setUp() throws IOException { Region region = Region.US_EAST_1; reg = region.toString(); appSyncClient = AppSyncClient.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -47,28 +45,31 @@ public static void setUp() throws IOException { SecretValues values = gson.fromJson(json, SecretValues.class); apiId = values.getApiId(); dsName = values.getDsName(); - dsRole= values.getDsRole(); - tableName= values.getTableName(); - - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - try (InputStream input = AppSyncTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - prop.load(input); - apiId = prop.getProperty("apiId"); - dsName = prop.getProperty("dsName"); - dsRole= prop.getProperty("dsRole"); - tableName= prop.getProperty("tableName"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + dsRole = values.getDsRole(); + tableName = values.getTableName(); + + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * try (InputStream input = + * AppSyncTest.class.getClassLoader().getResourceAsStream("config.properties")) + * { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * prop.load(input); + * apiId = prop.getProperty("apiId"); + * dsName = prop.getProperty("dsName"); + * dsRole= prop.getProperty("dsRole"); + * tableName= prop.getProperty("tableName"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @@ -93,7 +94,7 @@ public void CreateDataSource() { @Tag("IntegrationTest") @Order(3) public void GetDataSource() { - assertDoesNotThrow(()->GetDataSource.getDS(appSyncClient, apiId, dsName)); + assertDoesNotThrow(() -> GetDataSource.getDS(appSyncClient, apiId, dsName)); System.out.println("Test 4 passed"); } @@ -101,7 +102,7 @@ public void GetDataSource() { @Tag("IntegrationTest") @Order(4) public void ListGraphqlApis() { - assertDoesNotThrow(()->ListGraphqlApis.getApis(appSyncClient)); + assertDoesNotThrow(() -> ListGraphqlApis.getApis(appSyncClient)); System.out.println("Test 5 passed"); } @@ -109,36 +110,36 @@ public void ListGraphqlApis() { @Tag("IntegrationTest") @Order(5) public void ListApiKeys() { - assertDoesNotThrow(()->ListApiKeys.getKeys(appSyncClient,apiId)); + assertDoesNotThrow(() -> ListApiKeys.getKeys(appSyncClient, apiId)); System.out.println("Test 6 passed"); } @Test @Tag("IntegrationTest") @Order(6) - public void DeleteDataSource() { - assertDoesNotThrow(()->DeleteDataSource.deleteDS(appSyncClient, apiId, dsName)); + public void DeleteDataSource() { + assertDoesNotThrow(() -> DeleteDataSource.deleteDS(appSyncClient, apiId, dsName)); System.out.println("Test 7 passed"); - } + } @Test @Tag("IntegrationTest") @Order(7) - public void DeleteApiKey() { - assertDoesNotThrow(()->DeleteApiKey.deleteKey(appSyncClient, keyId, apiId)) ; - System.out.println("Test 8 passed"); - } + public void DeleteApiKey() { + assertDoesNotThrow(() -> DeleteApiKey.deleteKey(appSyncClient, keyId, apiId)); + System.out.println("Test 8 passed"); + } private static String getSecretValues() { - SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + SecretsManagerClient secretClient = SecretsManagerClient.builder() + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/appsync"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); diff --git a/javav2/example_code/athena/run_example.sh b/javav2/example_code/athena/run_example.sh index 1e0dad43bc7..59144db5b3a 100644 --- a/javav2/example_code/athena/run_example.sh +++ b/javav2/example_code/athena/run_example.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 if [[ -z $* ]] ; then echo 'Supply the name of one of the example classes as an argument.' echo 'If there are arguments to the class, put them in quotes after the class name.' diff --git a/javav2/example_code/athena/src/main/java/aws/example/athena/AthenaClientFactory.java b/javav2/example_code/athena/src/main/java/aws/example/athena/AthenaClientFactory.java index ddec219857d..6f4261ba29b 100644 --- a/javav2/example_code/athena/src/main/java/aws/example/athena/AthenaClientFactory.java +++ b/javav2/example_code/athena/src/main/java/aws/example/athena/AthenaClientFactory.java @@ -1,32 +1,27 @@ -//snippet-sourcedescription:[AthenaClientFactory.java demonstrates how to create and configure an Amazon Athena client.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Athena] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ -//snippet-start:[athena.java2.AthenaClientFactory.client] -//snippet-start:[athena.java.AthenaClientFactory.client] +// snippet-start:[athena.java2.AthenaClientFactory.client] +// snippet-start:[athena.java.AthenaClientFactory.client] package aws.example.athena; -//snippet-start:[athena.java2.AthenaClientFactory.client.import] +// snippet-start:[athena.java2.AthenaClientFactory.client.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.athena.AthenaClient; import software.amazon.awssdk.services.athena.AthenaClientBuilder; -//snippet-end:[athena.java2.AthenaClientFactory.client.import] +// snippet-end:[athena.java2.AthenaClientFactory.client.import] -//snippet-start:[athena.java2.AthenaClientFactory.client.main] +// snippet-start:[athena.java2.AthenaClientFactory.client.main] public class AthenaClientFactory { - private final AthenaClientBuilder builder = AthenaClient.builder() + private final AthenaClientBuilder builder = AthenaClient.builder() .region(Region.US_WEST_2) .credentialsProvider(ProfileCredentialsProvider.create()); public AthenaClient createClient() { return builder.build(); } - //snippet-end:[athena.java2.AthenaClientFactory.client.main] + // snippet-end:[athena.java2.AthenaClientFactory.client.main] } -//snippet-end:[athena.java.AthenaClientFactory.client] -//snippet-end:[athena.java2.AthenaClientFactory.client] \ No newline at end of file +// snippet-end:[athena.java.AthenaClientFactory.client] +// snippet-end:[athena.java2.AthenaClientFactory.client] \ No newline at end of file diff --git a/javav2/example_code/athena/src/main/java/aws/example/athena/CreateNamedQueryExample.java b/javav2/example_code/athena/src/main/java/aws/example/athena/CreateNamedQueryExample.java index 95db60cdfd9..298b1e11c9c 100644 --- a/javav2/example_code/athena/src/main/java/aws/example/athena/CreateNamedQueryExample.java +++ b/javav2/example_code/athena/src/main/java/aws/example/athena/CreateNamedQueryExample.java @@ -1,26 +1,21 @@ -//snippet-sourcedescription:[CreateNamedQueryExample.java demonstrates how to create a named query.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Athena] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - -//snippet-start:[athena.java2.CreateNamedQueryExample.complete] -//snippet-start:[athena.java.CreateNamedQueryExample.complete] +// snippet-start:[athena.java2.CreateNamedQueryExample.complete] +// snippet-start:[athena.java.CreateNamedQueryExample.complete] package aws.example.athena; -//snippet-start:[athena.java2.CreateNamedQueryExample.main] -//snippet-start:[athena.java2.CreateNamedQueryExample.import] +// snippet-start:[athena.java2.CreateNamedQueryExample.main] +// snippet-start:[athena.java2.CreateNamedQueryExample.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.athena.AthenaClient; import software.amazon.awssdk.services.athena.model.AthenaException; import software.amazon.awssdk.services.athena.model.CreateNamedQueryRequest; -//snippet-end:[athena.java2.CreateNamedQueryExample.import] +// snippet-end:[athena.java2.CreateNamedQueryExample.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,12 +26,12 @@ public class CreateNamedQueryExample { public static void main(String[] args) { final String USAGE = """ - Usage: - + Usage: + - Where: - name - the name of the Amazon Athena query.\s - """; + Where: + name - the name of the Amazon Athena query.\s + """; if (args.length != 1) { System.out.println(USAGE); @@ -45,8 +40,8 @@ public static void main(String[] args) { String name = args[0]; AthenaClient athenaClient = AthenaClient.builder() - .region(Region.US_WEST_2) - .build(); + .region(Region.US_WEST_2) + .build(); createNamedQuery(athenaClient, name); athenaClient.close(); @@ -56,11 +51,11 @@ public static void createNamedQuery(AthenaClient athenaClient, String name) { try { // Create the named query request. CreateNamedQueryRequest createNamedQueryRequest = CreateNamedQueryRequest.builder() - .database(ExampleConstants.ATHENA_DEFAULT_DATABASE) - .queryString(ExampleConstants.ATHENA_SAMPLE_QUERY) - .description("Sample Description") - .name(name) - .build(); + .database(ExampleConstants.ATHENA_DEFAULT_DATABASE) + .queryString(ExampleConstants.ATHENA_SAMPLE_QUERY) + .description("Sample Description") + .name(name) + .build(); athenaClient.createNamedQuery(createNamedQueryRequest); System.out.println("Done"); @@ -71,6 +66,6 @@ public static void createNamedQuery(AthenaClient athenaClient, String name) { } } } -//snippet-end:[athena.java2.CreateNamedQueryExample.main] -//snippet-end:[athena.java.CreateNamedQueryExample.complete] -//snippet-end:[athena.java2.CreateNamedQueryExample.complete] \ No newline at end of file +// snippet-end:[athena.java2.CreateNamedQueryExample.main] +// snippet-end:[athena.java.CreateNamedQueryExample.complete] +// snippet-end:[athena.java2.CreateNamedQueryExample.complete] \ No newline at end of file diff --git a/javav2/example_code/athena/src/main/java/aws/example/athena/DeleteNamedQueryExample.java b/javav2/example_code/athena/src/main/java/aws/example/athena/DeleteNamedQueryExample.java index 12560d14d22..6542976bae4 100644 --- a/javav2/example_code/athena/src/main/java/aws/example/athena/DeleteNamedQueryExample.java +++ b/javav2/example_code/athena/src/main/java/aws/example/athena/DeleteNamedQueryExample.java @@ -1,28 +1,22 @@ -//snippet-sourcedescription:[DeleteNamedQueryExample.java demonstrates how to delete a named query by using the named query Id value.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Athena] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - - -//snippet-start:[athena.java2.DeleteNamedQueryExample.complete] -//snippet-start:[athena.java.DeleteNamedQueryExample.complete] +// snippet-start:[athena.java2.DeleteNamedQueryExample.complete] +// snippet-start:[athena.java.DeleteNamedQueryExample.complete] package aws.example.athena; -//snippet-start:[athena.java2.DeleteNamedQueryExample.import] +// snippet-start:[athena.java2.DeleteNamedQueryExample.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.athena.AthenaClient; import software.amazon.awssdk.services.athena.model.DeleteNamedQueryRequest; import software.amazon.awssdk.services.athena.model.AthenaException; import software.amazon.awssdk.services.athena.model.CreateNamedQueryRequest; import software.amazon.awssdk.services.athena.model.CreateNamedQueryResponse; -//snippet-end:[athena.java2.DeleteNamedQueryExample.import] +// snippet-end:[athena.java2.DeleteNamedQueryExample.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,12 +26,12 @@ public class DeleteNamedQueryExample { public static void main(String[] args) { final String USAGE = """ - Usage: - + Usage: + - Where: - name - the name of the Amazon Athena query.\s - """; + Where: + name - the name of the Amazon Athena query.\s + """; if (args.length != 1) { System.out.println(USAGE); @@ -46,48 +40,48 @@ public static void main(String[] args) { String name = args[0]; AthenaClient athenaClient = AthenaClient.builder() - .region(Region.US_WEST_2) - .build(); + .region(Region.US_WEST_2) + .build(); String sampleNamedQueryId = getNamedQueryId(athenaClient, name); deleteQueryName(athenaClient, sampleNamedQueryId); athenaClient.close(); } - //snippet-start:[athena.java2.DeleteNamedQueryExample.main] - public static void deleteQueryName(AthenaClient athenaClient, String sampleNamedQueryId) { - try { - DeleteNamedQueryRequest deleteNamedQueryRequest = DeleteNamedQueryRequest.builder() - .namedQueryId(sampleNamedQueryId) - .build(); + // snippet-start:[athena.java2.DeleteNamedQueryExample.main] + public static void deleteQueryName(AthenaClient athenaClient, String sampleNamedQueryId) { + try { + DeleteNamedQueryRequest deleteNamedQueryRequest = DeleteNamedQueryRequest.builder() + .namedQueryId(sampleNamedQueryId) + .build(); athenaClient.deleteNamedQuery(deleteNamedQueryRequest); - } catch (AthenaException e) { - e.printStackTrace(); - System.exit(1); - } - } + } catch (AthenaException e) { + e.printStackTrace(); + System.exit(1); + } + } - public static String getNamedQueryId(AthenaClient athenaClient, String name) { - try { - CreateNamedQueryRequest createNamedQueryRequest = CreateNamedQueryRequest.builder() - .database(ExampleConstants.ATHENA_DEFAULT_DATABASE) - .queryString(ExampleConstants.ATHENA_SAMPLE_QUERY) - .name(name) - .description("Sample description") - .build(); + public static String getNamedQueryId(AthenaClient athenaClient, String name) { + try { + CreateNamedQueryRequest createNamedQueryRequest = CreateNamedQueryRequest.builder() + .database(ExampleConstants.ATHENA_DEFAULT_DATABASE) + .queryString(ExampleConstants.ATHENA_SAMPLE_QUERY) + .name(name) + .description("Sample description") + .build(); - CreateNamedQueryResponse createNamedQueryResponse = athenaClient.createNamedQuery(createNamedQueryRequest); - return createNamedQueryResponse.namedQueryId(); + CreateNamedQueryResponse createNamedQueryResponse = athenaClient.createNamedQuery(createNamedQueryRequest); + return createNamedQueryResponse.namedQueryId(); - } catch (AthenaException e) { - e.printStackTrace(); - System.exit(1); - } - return null; - } + } catch (AthenaException e) { + e.printStackTrace(); + System.exit(1); + } + return null; + } } -//snippet-end:[athena.java2.DeleteNamedQueryExample.main] -//snippet-end:[athena.java.DeleteNamedQueryExample.complete] -//snippet-end:[athena.java2.DeleteNamedQueryExample.complete] +// snippet-end:[athena.java2.DeleteNamedQueryExample.main] +// snippet-end:[athena.java.DeleteNamedQueryExample.complete] +// snippet-end:[athena.java2.DeleteNamedQueryExample.complete] diff --git a/javav2/example_code/athena/src/main/java/aws/example/athena/ExampleConstants.java b/javav2/example_code/athena/src/main/java/aws/example/athena/ExampleConstants.java index 728dc922cb9..bb8a9937f7b 100644 --- a/javav2/example_code/athena/src/main/java/aws/example/athena/ExampleConstants.java +++ b/javav2/example_code/athena/src/main/java/aws/example/athena/ExampleConstants.java @@ -1,25 +1,23 @@ -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Athena] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - -//snippet-start:[athena.java2.ExampleConstants.complete] -//snippet-start:[athena.java.ExampleConstants.complete] +// snippet-start:[athena.java2.ExampleConstants.complete] +// snippet-start:[athena.java.ExampleConstants.complete] package aws.example.athena; public class ExampleConstants { public static final int CLIENT_EXECUTION_TIMEOUT = 100000; - public static final String ATHENA_OUTPUT_BUCKET = "s3://bucketscott2"; // change the Amazon S3 bucket name to match your environment - // Demonstrates how to query a table with a comma-separated value (CSV) table. For information, see - //https://docs.aws.amazon.com/athena/latest/ug/work-with-data.html - public static final String ATHENA_SAMPLE_QUERY = "SELECT * FROM scott2;"; // change the Query statement to match your environment + public static final String ATHENA_OUTPUT_BUCKET = "s3://bucketscott2"; // change the Amazon S3 bucket name to match + // your environment + // Demonstrates how to query a table with a comma-separated value (CSV) table. + // For information, see + // https://docs.aws.amazon.com/athena/latest/ug/work-with-data.html + public static final String ATHENA_SAMPLE_QUERY = "SELECT * FROM scott2;"; // change the Query statement to match + // your environment public static final long SLEEP_AMOUNT_IN_MS = 1000; public static final String ATHENA_DEFAULT_DATABASE = "mydatabase"; // change the database to match your database } -//snippet-end:[athena.java.ExampleConstants.complete] -//snippet-end:[athena.java2.ExampleConstants.complete] \ No newline at end of file +// snippet-end:[athena.java.ExampleConstants.complete] +// snippet-end:[athena.java2.ExampleConstants.complete] \ No newline at end of file diff --git a/javav2/example_code/athena/src/main/java/aws/example/athena/ListNamedQueryExample.java b/javav2/example_code/athena/src/main/java/aws/example/athena/ListNamedQueryExample.java index 959f468ed3e..f7449890198 100644 --- a/javav2/example_code/athena/src/main/java/aws/example/athena/ListNamedQueryExample.java +++ b/javav2/example_code/athena/src/main/java/aws/example/athena/ListNamedQueryExample.java @@ -1,18 +1,12 @@ -//snippet-sourcedescription:[ListNamedQueryExample.java demonstrates how to obtain a list of named query Id values.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Athena] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - -//snippet-start:[athena.java2.ListNamedQueryExample.complete] -//snippet-start:[athena.java.ListNamedQueryExample.complete] +// snippet-start:[athena.java2.ListNamedQueryExample.complete] +// snippet-start:[athena.java.ListNamedQueryExample.complete] package aws.example.athena; -//snippet-start:[athena.java2.ListNamedQueryExample.main] -//snippet-start:[athena.java2.ListNamedQueryExample.import] +// snippet-start:[athena.java2.ListNamedQueryExample.main] +// snippet-start:[athena.java2.ListNamedQueryExample.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.athena.AthenaClient; import software.amazon.awssdk.services.athena.model.AthenaException; @@ -20,10 +14,11 @@ import software.amazon.awssdk.services.athena.model.ListNamedQueriesResponse; import software.amazon.awssdk.services.athena.paginators.ListNamedQueriesIterable; import java.util.List; -//snippet-end:[athena.java2.ListNamedQueryExample.import] +// snippet-end:[athena.java2.ListNamedQueryExample.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,31 +27,31 @@ public class ListNamedQueryExample { public static void main(String[] args) { AthenaClient athenaClient = AthenaClient.builder() - .region(Region.US_WEST_2) - .build(); + .region(Region.US_WEST_2) + .build(); - listNamedQueries(athenaClient) ; + listNamedQueries(athenaClient); athenaClient.close(); } - public static void listNamedQueries(AthenaClient athenaClient) { - try{ + try { ListNamedQueriesRequest listNamedQueriesRequest = ListNamedQueriesRequest.builder() - .build(); + .build(); - ListNamedQueriesIterable listNamedQueriesResponses = athenaClient.listNamedQueriesPaginator(listNamedQueriesRequest); + ListNamedQueriesIterable listNamedQueriesResponses = athenaClient + .listNamedQueriesPaginator(listNamedQueriesRequest); for (ListNamedQueriesResponse listNamedQueriesResponse : listNamedQueriesResponses) { List namedQueryIds = listNamedQueriesResponse.namedQueryIds(); System.out.println(namedQueryIds); } } catch (AthenaException e) { - e.printStackTrace(); - System.exit(1); + e.printStackTrace(); + System.exit(1); } } } -//snippet-end:[athena.java2.ListNamedQueryExample.main] -//snippet-end:[athena.java.ListNamedQueryExample.complete] -//snippet-end:[athena.java2.ListNamedQueryExample.complete] \ No newline at end of file +// snippet-end:[athena.java2.ListNamedQueryExample.main] +// snippet-end:[athena.java.ListNamedQueryExample.complete] +// snippet-end:[athena.java2.ListNamedQueryExample.complete] \ No newline at end of file diff --git a/javav2/example_code/athena/src/main/java/aws/example/athena/ListQueryExecutionsExample.java b/javav2/example_code/athena/src/main/java/aws/example/athena/ListQueryExecutionsExample.java index a9a191d59b4..f61f6cecc0d 100644 --- a/javav2/example_code/athena/src/main/java/aws/example/athena/ListQueryExecutionsExample.java +++ b/javav2/example_code/athena/src/main/java/aws/example/athena/ListQueryExecutionsExample.java @@ -1,18 +1,12 @@ -//snippet-sourcedescription:[ListQueryExecutionsExample.java demonstrates how to obtain a list of query execution Id values.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Athena] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - -//snippet-start:[athena.java2.ListNamedQueryExecutionsExample.complete] -//snippet-start:[athena.java.ListNamedQueryExecutionsExample.complete] +// snippet-start:[athena.java2.ListNamedQueryExecutionsExample.complete] +// snippet-start:[athena.java.ListNamedQueryExecutionsExample.complete] package aws.example.athena; -//snippet-start:[athena.java2.ListNamedQueryExecutionsExample.main] -//snippet-start:[athena.java2.ListNamedQueryExecutionsExample.import] +// snippet-start:[athena.java2.ListNamedQueryExecutionsExample.main] +// snippet-start:[athena.java2.ListNamedQueryExecutionsExample.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.athena.AthenaClient; import software.amazon.awssdk.services.athena.model.AthenaException; @@ -20,10 +14,11 @@ import software.amazon.awssdk.services.athena.model.ListQueryExecutionsResponse; import software.amazon.awssdk.services.athena.paginators.ListQueryExecutionsIterable; import java.util.List; -//snippet-end:[athena.java2.ListNamedQueryExecutionsExample.import] +// snippet-end:[athena.java2.ListNamedQueryExecutionsExample.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,8 +27,8 @@ public class ListQueryExecutionsExample { public static void main(String[] args) { AthenaClient athenaClient = AthenaClient.builder() - .region(Region.US_WEST_2) - .build(); + .region(Region.US_WEST_2) + .build(); listQueryIds(athenaClient); athenaClient.close(); @@ -42,10 +37,11 @@ public static void main(String[] args) { public static void listQueryIds(AthenaClient athenaClient) { try { ListQueryExecutionsRequest listQueryExecutionsRequest = ListQueryExecutionsRequest.builder().build(); - ListQueryExecutionsIterable listQueryExecutionResponses = athenaClient.listQueryExecutionsPaginator(listQueryExecutionsRequest); + ListQueryExecutionsIterable listQueryExecutionResponses = athenaClient + .listQueryExecutionsPaginator(listQueryExecutionsRequest); for (ListQueryExecutionsResponse listQueryExecutionResponse : listQueryExecutionResponses) { List queryExecutionIds = listQueryExecutionResponse.queryExecutionIds(); - System.out.println("\n" +queryExecutionIds); + System.out.println("\n" + queryExecutionIds); } } catch (AthenaException e) { @@ -54,6 +50,6 @@ public static void listQueryIds(AthenaClient athenaClient) { } } } -//snippet-end:[athena.java2.ListNamedQueryExecutionsExample.main] -//snippet-end:[athena.java.ListNamedQueryExecutionsExample.complete] -//snippet-end:[athena.java2.ListNamedQueryExecutionsExample.complete] \ No newline at end of file +// snippet-end:[athena.java2.ListNamedQueryExecutionsExample.main] +// snippet-end:[athena.java.ListNamedQueryExecutionsExample.complete] +// snippet-end:[athena.java2.ListNamedQueryExecutionsExample.complete] \ No newline at end of file diff --git a/javav2/example_code/athena/src/main/java/aws/example/athena/StartQueryExample.java b/javav2/example_code/athena/src/main/java/aws/example/athena/StartQueryExample.java index 19d5aadd541..bdadf874146 100644 --- a/javav2/example_code/athena/src/main/java/aws/example/athena/StartQueryExample.java +++ b/javav2/example_code/athena/src/main/java/aws/example/athena/StartQueryExample.java @@ -1,17 +1,12 @@ -//snippet-sourcedescription:[StartQueryExample.java demonstrates how to submit a query to Amazon Athena for execution, wait until the results are available, and then process the results.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Athena] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - -//snippet-start:[athena.java2.StartQueryExample.complete] -//snippet-start:[athena.java.StartQueryExample.complete] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[athena.java2.StartQueryExample.complete] +// snippet-start:[athena.java.StartQueryExample.complete] package aws.example.athena; -//snippet-start:[athena.java2.StartQueryExample.main] -//snippet-start:[athena.java2.StartQueryExample.import] +// snippet-start:[athena.java2.StartQueryExample.main] +// snippet-start:[athena.java2.StartQueryExample.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.athena.AthenaClient; import software.amazon.awssdk.services.athena.model.QueryExecutionContext; @@ -29,10 +24,11 @@ import software.amazon.awssdk.services.athena.model.Datum; import software.amazon.awssdk.services.athena.paginators.GetQueryResultsIterable; import java.util.List; -//snippet-end:[athena.java2.StartQueryExample.import] +// snippet-end:[athena.java2.StartQueryExample.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -42,8 +38,8 @@ public class StartQueryExample { public static void main(String[] args) throws InterruptedException { AthenaClient athenaClient = AthenaClient.builder() - .region(Region.US_WEST_2) - .build(); + .region(Region.US_WEST_2) + .build(); String queryExecutionId = submitAthenaQuery(athenaClient); waitForQueryToComplete(athenaClient, queryExecutionId); @@ -51,26 +47,28 @@ public static void main(String[] args) throws InterruptedException { athenaClient.close(); } - // Submits a sample query to Amazon Athena and returns the execution ID of the query. + // Submits a sample query to Amazon Athena and returns the execution ID of the + // query. public static String submitAthenaQuery(AthenaClient athenaClient) { try { // The QueryExecutionContext allows us to set the database. QueryExecutionContext queryExecutionContext = QueryExecutionContext.builder() - .database(ExampleConstants.ATHENA_DEFAULT_DATABASE) - .build(); + .database(ExampleConstants.ATHENA_DEFAULT_DATABASE) + .build(); // The result configuration specifies where the results of the query should go. ResultConfiguration resultConfiguration = ResultConfiguration.builder() - .outputLocation(ExampleConstants.ATHENA_OUTPUT_BUCKET) - .build(); + .outputLocation(ExampleConstants.ATHENA_OUTPUT_BUCKET) + .build(); StartQueryExecutionRequest startQueryExecutionRequest = StartQueryExecutionRequest.builder() - .queryString(ExampleConstants.ATHENA_SAMPLE_QUERY) - .queryExecutionContext(queryExecutionContext) - .resultConfiguration(resultConfiguration) - .build(); + .queryString(ExampleConstants.ATHENA_SAMPLE_QUERY) + .queryExecutionContext(queryExecutionContext) + .resultConfiguration(resultConfiguration) + .build(); - StartQueryExecutionResponse startQueryExecutionResponse = athenaClient.startQueryExecution(startQueryExecutionRequest); + StartQueryExecutionResponse startQueryExecutionResponse = athenaClient + .startQueryExecution(startQueryExecutionRequest); return startQueryExecutionResponse.queryExecutionId(); } catch (AthenaException e) { @@ -81,10 +79,11 @@ public static String submitAthenaQuery(AthenaClient athenaClient) { } // Wait for an Amazon Athena query to complete, fail or to be cancelled. - public static void waitForQueryToComplete(AthenaClient athenaClient, String queryExecutionId) throws InterruptedException { + public static void waitForQueryToComplete(AthenaClient athenaClient, String queryExecutionId) + throws InterruptedException { GetQueryExecutionRequest getQueryExecutionRequest = GetQueryExecutionRequest.builder() - .queryExecutionId(queryExecutionId) - .build(); + .queryExecutionId(queryExecutionId) + .build(); GetQueryExecutionResponse getQueryExecutionResponse; boolean isQueryStillRunning = true; @@ -92,8 +91,9 @@ public static void waitForQueryToComplete(AthenaClient athenaClient, String quer getQueryExecutionResponse = athenaClient.getQueryExecution(getQueryExecutionRequest); String queryState = getQueryExecutionResponse.queryExecution().status().state().toString(); if (queryState.equals(QueryExecutionState.FAILED.toString())) { - throw new RuntimeException("The Amazon Athena query failed to run with error message: " + getQueryExecutionResponse - .queryExecution().status().stateChangeReason()); + throw new RuntimeException( + "The Amazon Athena query failed to run with error message: " + getQueryExecutionResponse + .queryExecution().status().stateChangeReason()); } else if (queryState.equals(QueryExecutionState.CANCELLED.toString())) { throw new RuntimeException("The Amazon Athena query was cancelled."); } else if (queryState.equals(QueryExecutionState.SUCCEEDED.toString())) { @@ -112,10 +112,11 @@ public static void processResultRows(AthenaClient athenaClient, String queryExec // Max Results can be set but if its not set, // it will choose the maximum page size. GetQueryResultsRequest getQueryResultsRequest = GetQueryResultsRequest.builder() - .queryExecutionId(queryExecutionId) - .build(); + .queryExecutionId(queryExecutionId) + .build(); - GetQueryResultsIterable getQueryResultsResults = athenaClient.getQueryResultsPaginator(getQueryResultsRequest); + GetQueryResultsIterable getQueryResultsResults = athenaClient + .getQueryResultsPaginator(getQueryResultsRequest); for (GetQueryResultsResponse result : getQueryResultsResults) { List columnInfoList = result.resultSet().resultSetMetadata().columnInfo(); List results = result.resultSet().rows(); @@ -123,20 +124,20 @@ public static void processResultRows(AthenaClient athenaClient, String queryExec } } catch (AthenaException e) { - e.printStackTrace(); - System.exit(1); - } + e.printStackTrace(); + System.exit(1); + } } private static void processRow(List row, List columnInfoList) { for (Row myRow : row) { List allData = myRow.data(); for (Datum data : allData) { - System.out.println("The value of the column is "+data.varCharValue()); + System.out.println("The value of the column is " + data.varCharValue()); } } } } -//snippet-end:[athena.java2.StartQueryExample.main] -//snippet-end:[athena.java.StartQueryExample.complete] -//snippet-end:[athena.java2.StartQueryExample.complete] \ No newline at end of file +// snippet-end:[athena.java2.StartQueryExample.main] +// snippet-end:[athena.java.StartQueryExample.complete] +// snippet-end:[athena.java2.StartQueryExample.complete] \ No newline at end of file diff --git a/javav2/example_code/athena/src/main/java/aws/example/athena/StopQueryExecutionExample.java b/javav2/example_code/athena/src/main/java/aws/example/athena/StopQueryExecutionExample.java index 11ebc9b5b95..33232b6967d 100644 --- a/javav2/example_code/athena/src/main/java/aws/example/athena/StopQueryExecutionExample.java +++ b/javav2/example_code/athena/src/main/java/aws/example/athena/StopQueryExecutionExample.java @@ -1,18 +1,12 @@ -//snippet-sourcedescription:[StopQueryExecutionExample.java demonstrates how to stop a query and check its status.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Athena] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - -//snippet-start:[athena.java2.StopQueryExecutionExample.complete] -//snippet-start:[athena.java.StopQueryExecutionExample.complete] +// snippet-start:[athena.java2.StopQueryExecutionExample.complete] +// snippet-start:[athena.java.StopQueryExecutionExample.complete] package aws.example.athena; -//snippet-start:[athena.java2.StopQueryExecutionExample.main] -//snippet-start:[athena.java2.StopQueryExecutionExample.import] +// snippet-start:[athena.java2.StopQueryExecutionExample.main] +// snippet-start:[athena.java2.StopQueryExecutionExample.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.athena.AthenaClient; import software.amazon.awssdk.services.athena.model.StopQueryExecutionRequest; @@ -24,10 +18,11 @@ import software.amazon.awssdk.services.athena.model.ResultConfiguration; import software.amazon.awssdk.services.athena.model.StartQueryExecutionRequest; import software.amazon.awssdk.services.athena.model.StartQueryExecutionResponse; -//snippet-end:[athena.java2.StopQueryExecutionExample.import] +// snippet-end:[athena.java2.StopQueryExecutionExample.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -36,67 +31,69 @@ public class StopQueryExecutionExample { public static void main(String[] args) { AthenaClient athenaClient = AthenaClient.builder() - .region(Region.US_WEST_2) - .build(); + .region(Region.US_WEST_2) + .build(); String sampleQueryExecutionId = submitAthenaQuery(athenaClient); stopAthenaQuery(athenaClient, sampleQueryExecutionId); athenaClient.close(); } - public static void stopAthenaQuery(AthenaClient athenaClient, String sampleQueryExecutionId){ + public static void stopAthenaQuery(AthenaClient athenaClient, String sampleQueryExecutionId) { try { StopQueryExecutionRequest stopQueryExecutionRequest = StopQueryExecutionRequest.builder() - .queryExecutionId(sampleQueryExecutionId) - .build(); + .queryExecutionId(sampleQueryExecutionId) + .build(); athenaClient.stopQueryExecution(stopQueryExecutionRequest); GetQueryExecutionRequest getQueryExecutionRequest = GetQueryExecutionRequest.builder() - .queryExecutionId(sampleQueryExecutionId) - .build(); + .queryExecutionId(sampleQueryExecutionId) + .build(); - GetQueryExecutionResponse getQueryExecutionResponse = athenaClient.getQueryExecution(getQueryExecutionRequest); + GetQueryExecutionResponse getQueryExecutionResponse = athenaClient + .getQueryExecution(getQueryExecutionRequest); if (getQueryExecutionResponse.queryExecution() - .status() - .state() - .equals(QueryExecutionState.CANCELLED)) { + .status() + .state() + .equals(QueryExecutionState.CANCELLED)) { System.out.println("The Amazon Athena query has been cancelled!"); } - } catch (AthenaException e) { + } catch (AthenaException e) { e.printStackTrace(); System.exit(1); - } + } } // Submits an example query and returns a query execution Id value public static String submitAthenaQuery(AthenaClient athenaClient) { try { QueryExecutionContext queryExecutionContext = QueryExecutionContext.builder() - .database(ExampleConstants.ATHENA_DEFAULT_DATABASE) - .build(); + .database(ExampleConstants.ATHENA_DEFAULT_DATABASE) + .build(); ResultConfiguration resultConfiguration = ResultConfiguration.builder() - .outputLocation(ExampleConstants.ATHENA_OUTPUT_BUCKET) - .build(); + .outputLocation(ExampleConstants.ATHENA_OUTPUT_BUCKET) + .build(); StartQueryExecutionRequest startQueryExecutionRequest = StartQueryExecutionRequest.builder() - .queryExecutionContext(queryExecutionContext) - .queryString(ExampleConstants.ATHENA_SAMPLE_QUERY) - .resultConfiguration(resultConfiguration).build(); + .queryExecutionContext(queryExecutionContext) + .queryString(ExampleConstants.ATHENA_SAMPLE_QUERY) + .resultConfiguration(resultConfiguration).build(); - StartQueryExecutionResponse startQueryExecutionResponse = athenaClient.startQueryExecution(startQueryExecutionRequest); + StartQueryExecutionResponse startQueryExecutionResponse = athenaClient + .startQueryExecution(startQueryExecutionRequest); return startQueryExecutionResponse.queryExecutionId(); } catch (AthenaException e) { e.printStackTrace(); - System.exit(1); + System.exit(1); } return null; } } -//snippet-end:[athena.java2.StopQueryExecutionExample.main] -//snippet-end:[athena.java.StopQueryExecutionExample.complete] -//snippet-end:[athena.java2.StopQueryExecutionExample.complete] \ No newline at end of file +// snippet-end:[athena.java2.StopQueryExecutionExample.main] +// snippet-end:[athena.java.StopQueryExecutionExample.complete] +// snippet-end:[athena.java2.StopQueryExecutionExample.complete] \ No newline at end of file diff --git a/javav2/example_code/athena/src/test/java/AmazonAthenaTest.java b/javav2/example_code/athena/src/test/java/AmazonAthenaTest.java index d51157cf5fd..5dce09233fd 100644 --- a/javav2/example_code/athena/src/test/java/AmazonAthenaTest.java +++ b/javav2/example_code/athena/src/test/java/AmazonAthenaTest.java @@ -1,112 +1,114 @@ -import aws.example.athena.*; -import org.junit.jupiter.api.*; -import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.athena.AthenaClient; - -import java.io.*; -import java.util.Properties; - -import static org.junit.jupiter.api.Assertions.*; - -@TestInstance(TestInstance.Lifecycle.PER_METHOD) -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) -public class AmazonAthenaTest { - - private static AthenaClient athenaClient; - private static String nameQuery; - - @BeforeAll - public static void setUp() throws IOException { - athenaClient = AthenaClient.builder() - .region(Region.US_WEST_2) - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); - - try (InputStream input = AmazonAthenaTest.class.getClassLoader().getResourceAsStream("config.properties")) { - - Properties prop = new Properties(); - - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - //load a properties file from class path, inside static method - prop.load(input); - - // Populate the data members required for all tests - nameQuery = prop.getProperty("nameQuery"); - - - } catch (IOException ex) { - ex.printStackTrace(); - } - } - @Test - @Order(1) - public void whenInitializingAWSAthenaService_thenNotNull() { - assertNotNull(athenaClient); - System.out.println("Test 1 passed"); - } - - @Test - @Order(2) - public void CreateNamedQueryExample() { - - CreateNamedQueryExample.createNamedQuery(athenaClient, nameQuery); - System.out.println("Test 2 passed"); - } - - @Test - @Order(3) - public void ListNamedQueryExample() { - - ListNamedQueryExample.listNamedQueries(athenaClient); - System.out.println("Test 3 passed"); - } - - @Test - @Order(4) - public void ListQueryExecutionsExample() { - - ListQueryExecutionsExample.listQueryIds(athenaClient); - System.out.println("Test 4 passed"); - } - - @Test - @Order(5) - public void DeleteNamedQueryExample() - { - String sampleNamedQueryId = DeleteNamedQueryExample.getNamedQueryId(athenaClient, nameQuery); - DeleteNamedQueryExample.deleteQueryName(athenaClient, sampleNamedQueryId); - System.out.println("Test 5 passed"); - - } - - - @Test - @Order(6) - public void StartQueryExample() { - - try { - String queryExecutionId = StartQueryExample.submitAthenaQuery(athenaClient); - StartQueryExample.waitForQueryToComplete(athenaClient, queryExecutionId); - StartQueryExample.processResultRows(athenaClient, queryExecutionId); - System.out.println("Test 6 passed"); - - }catch (InterruptedException e) { - e.getMessage(); - } - } - - @Test - @Order(7) - public void StopQueryExecutionExample() { - - String sampleQueryExecutionId = StopQueryExecutionExample.submitAthenaQuery(athenaClient); - StopQueryExecutionExample.stopAthenaQuery(athenaClient, sampleQueryExecutionId); - System.out.println("Test 7 passed"); - } -} - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +import aws.example.athena.*; +import org.junit.jupiter.api.*; +import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.athena.AthenaClient; + +import java.io.*; +import java.util.Properties; + +import static org.junit.jupiter.api.Assertions.*; + +@TestInstance(TestInstance.Lifecycle.PER_METHOD) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +public class AmazonAthenaTest { + + private static AthenaClient athenaClient; + private static String nameQuery; + + @BeforeAll + public static void setUp() throws IOException { + athenaClient = AthenaClient.builder() + .region(Region.US_WEST_2) + .credentialsProvider(ProfileCredentialsProvider.create()) + .build(); + + try (InputStream input = AmazonAthenaTest.class.getClassLoader().getResourceAsStream("config.properties")) { + + Properties prop = new Properties(); + + if (input == null) { + System.out.println("Sorry, unable to find config.properties"); + return; + } + + //load a properties file from class path, inside static method + prop.load(input); + + // Populate the data members required for all tests + nameQuery = prop.getProperty("nameQuery"); + + + } catch (IOException ex) { + ex.printStackTrace(); + } + } + @Test + @Order(1) + public void whenInitializingAWSAthenaService_thenNotNull() { + assertNotNull(athenaClient); + System.out.println("Test 1 passed"); + } + + @Test + @Order(2) + public void CreateNamedQueryExample() { + + CreateNamedQueryExample.createNamedQuery(athenaClient, nameQuery); + System.out.println("Test 2 passed"); + } + + @Test + @Order(3) + public void ListNamedQueryExample() { + + ListNamedQueryExample.listNamedQueries(athenaClient); + System.out.println("Test 3 passed"); + } + + @Test + @Order(4) + public void ListQueryExecutionsExample() { + + ListQueryExecutionsExample.listQueryIds(athenaClient); + System.out.println("Test 4 passed"); + } + + @Test + @Order(5) + public void DeleteNamedQueryExample() + { + String sampleNamedQueryId = DeleteNamedQueryExample.getNamedQueryId(athenaClient, nameQuery); + DeleteNamedQueryExample.deleteQueryName(athenaClient, sampleNamedQueryId); + System.out.println("Test 5 passed"); + + } + + + @Test + @Order(6) + public void StartQueryExample() { + + try { + String queryExecutionId = StartQueryExample.submitAthenaQuery(athenaClient); + StartQueryExample.waitForQueryToComplete(athenaClient, queryExecutionId); + StartQueryExample.processResultRows(athenaClient, queryExecutionId); + System.out.println("Test 6 passed"); + + }catch (InterruptedException e) { + e.getMessage(); + } + } + + @Test + @Order(7) + public void StopQueryExecutionExample() { + + String sampleQueryExecutionId = StopQueryExecutionExample.submitAthenaQuery(athenaClient); + StopQueryExecutionExample.stopAthenaQuery(athenaClient, sampleQueryExecutionId); + System.out.println("Test 7 passed"); + } +} + diff --git a/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/AutoScalingScenario.java b/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/AutoScalingScenario.java index bf1b725fd45..c4c2f98c3c6 100644 --- a/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/AutoScalingScenario.java +++ b/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/AutoScalingScenario.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[AutoScalingScenario.java performs multiple Auto Scaling operations.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2 Auto Scaling] - - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.autoscaling; @@ -40,15 +33,17 @@ // snippet-start:[autoscale.java2.create_scaling_scenario.main] /** - * Before running this SDK for Java (v2) code example, set up your development environment, including your credentials. + * Before running this SDK for Java (v2) code example, set up your development + * environment, including your credentials. * - * For more information, see the following documentation: + * For more information, see the following documentation: * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * In addition, create a launch template. For more information, see the following topic: + * In addition, create a launch template. For more information, see the + * following topic: * - * https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html#create-launch-template + * https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html#create-launch-template * * This code example performs the following operations: * 1. Creates an Auto Scaling group using an AutoScalingWaiter. @@ -68,17 +63,18 @@ public class AutoScalingScenario { public static final String DASHES = new String(new char[80]).replace("\0", "-"); + public static void main(String[] args) throws InterruptedException { final String usage = """ - Usage: - + Usage: + - Where: - groupName - The name of the Auto Scaling group. - launchTemplateName - The name of the launch template.\s - vpcZoneId - A subnet Id for a virtual private cloud (VPC) where instances in the Auto Scaling group can be created. - """; + Where: + groupName - The name of the Auto Scaling group. + launchTemplateName - The name of the launch template.\s + vpcZoneId - A subnet Id for a virtual private cloud (VPC) where instances in the Auto Scaling group can be created. + """; if (args.length != 3) { System.out.println(usage); @@ -89,38 +85,39 @@ public static void main(String[] args) throws InterruptedException { String launchTemplateName = args[1]; String vpcZoneId = args[2]; AutoScalingClient autoScalingClient = AutoScalingClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); System.out.println(DASHES); System.out.println("Welcome to the Amazon EC2 Auto Scaling example scenario."); System.out.println(DASHES); System.out.println(DASHES); - System.out.println("1. Create an Auto Scaling group named "+groupName); + System.out.println("1. Create an Auto Scaling group named " + groupName); createAutoScalingGroup(autoScalingClient, groupName, launchTemplateName, vpcZoneId); - System.out.println("Wait 1 min for the resources, including the instance. Otherwise, an empty instance Id is returned"); + System.out.println( + "Wait 1 min for the resources, including the instance. Otherwise, an empty instance Id is returned"); Thread.sleep(60000); System.out.println(DASHES); System.out.println(DASHES); System.out.println("2. Get Auto Scale group Id value"); String instanceId = getSpecificAutoScalingGroups(autoScalingClient, groupName); - if (instanceId.compareTo("") ==0) { + if (instanceId.compareTo("") == 0) { System.out.println("Error - no instance Id value"); System.exit(1); } else { - System.out.println("The instance Id value is "+instanceId); + System.out.println("The instance Id value is " + instanceId); } System.out.println(DASHES); System.out.println(DASHES); - System.out.println("3. Describe Auto Scaling with the Id value "+instanceId); - describeAutoScalingInstance( autoScalingClient, instanceId); + System.out.println("3. Describe Auto Scaling with the Id value " + instanceId); + describeAutoScalingInstance(autoScalingClient, instanceId); System.out.println(DASHES); System.out.println(DASHES); - System.out.println("4. Enable metrics collection "+instanceId); + System.out.println("4. Enable metrics collection " + instanceId); enableMetricsCollection(autoScalingClient, groupName); System.out.println(DASHES); @@ -137,7 +134,8 @@ public static void main(String[] args) throws InterruptedException { System.out.println(DASHES); System.out.println("7. Describe account details"); describeAccountLimits(autoScalingClient); - System.out.println("Wait 1 min for the resources, including the instance. Otherwise, an empty instance Id is returned"); + System.out.println( + "Wait 1 min for the resources, including the instance. Otherwise, an empty instance Id is returned"); Thread.sleep(60000); System.out.println(DASHES); @@ -172,7 +170,7 @@ public static void main(String[] args) throws InterruptedException { System.out.println(DASHES); System.out.println(DASHES); - System.out.println("The Scenario has successfully completed." ); + System.out.println("The Scenario has successfully completed."); System.out.println(DASHES); autoScalingClient.close(); @@ -182,15 +180,16 @@ public static void main(String[] args) throws InterruptedException { public static void describeScalingActivities(AutoScalingClient autoScalingClient, String groupName) { try { DescribeScalingActivitiesRequest scalingActivitiesRequest = DescribeScalingActivitiesRequest.builder() - .autoScalingGroupName(groupName) - .maxRecords(10) - .build(); + .autoScalingGroupName(groupName) + .maxRecords(10) + .build(); - DescribeScalingActivitiesResponse response = autoScalingClient.describeScalingActivities(scalingActivitiesRequest); + DescribeScalingActivitiesResponse response = autoScalingClient + .describeScalingActivities(scalingActivitiesRequest); List activities = response.activities(); - for (Activity activity: activities) { - System.out.println("The activity Id is "+activity.activityId()); - System.out.println("The activity details are "+activity.details()); + for (Activity activity : activities) { + System.out.println("The activity Id is " + activity.activityId()); + System.out.println("The activity details are " + activity.details()); } } catch (AutoScalingException e) { @@ -204,9 +203,9 @@ public static void describeScalingActivities(AutoScalingClient autoScalingClient public static void setDesiredCapacity(AutoScalingClient autoScalingClient, String groupName) { try { SetDesiredCapacityRequest capacityRequest = SetDesiredCapacityRequest.builder() - .autoScalingGroupName(groupName) - .desiredCapacity(2) - .build(); + .autoScalingGroupName(groupName) + .desiredCapacity(2) + .build(); autoScalingClient.setDesiredCapacity(capacityRequest); System.out.println("You have set the DesiredCapacity to 2"); @@ -220,30 +219,31 @@ public static void setDesiredCapacity(AutoScalingClient autoScalingClient, Strin // snippet-start:[autoscale.java2.create_autoscalinggroup.main] public static void createAutoScalingGroup(AutoScalingClient autoScalingClient, - String groupName, - String launchTemplateName, - String vpcZoneId) { + String groupName, + String launchTemplateName, + String vpcZoneId) { try { AutoScalingWaiter waiter = autoScalingClient.waiter(); LaunchTemplateSpecification templateSpecification = LaunchTemplateSpecification.builder() - .launchTemplateName(launchTemplateName) - .build(); + .launchTemplateName(launchTemplateName) + .build(); CreateAutoScalingGroupRequest request = CreateAutoScalingGroupRequest.builder() - .autoScalingGroupName(groupName) - .availabilityZones("us-east-1a") - .launchTemplate(templateSpecification) - .maxSize(1) - .minSize(1) - .vpcZoneIdentifier(vpcZoneId) - .build(); + .autoScalingGroupName(groupName) + .availabilityZones("us-east-1a") + .launchTemplate(templateSpecification) + .maxSize(1) + .minSize(1) + .vpcZoneIdentifier(vpcZoneId) + .build(); autoScalingClient.createAutoScalingGroup(request); DescribeAutoScalingGroupsRequest groupsRequest = DescribeAutoScalingGroupsRequest.builder() - .autoScalingGroupNames(groupName) - .build(); + .autoScalingGroupNames(groupName) + .build(); - WaiterResponse waiterResponse = waiter.waitUntilGroupExists(groupsRequest); + WaiterResponse waiterResponse = waiter + .waitUntilGroupExists(groupsRequest); waiterResponse.matched().response().ifPresent(System.out::println); System.out.println("Auto Scaling Group created"); @@ -255,16 +255,18 @@ public static void createAutoScalingGroup(AutoScalingClient autoScalingClient, // snippet-end:[autoscale.java2.create_autoscalinggroup.main] // snippet-start:[autoscale.java2.describe_autoscalinggroup.main] - public static void describeAutoScalingInstance( AutoScalingClient autoScalingClient, String id) { + public static void describeAutoScalingInstance(AutoScalingClient autoScalingClient, String id) { try { - DescribeAutoScalingInstancesRequest describeAutoScalingInstancesRequest = DescribeAutoScalingInstancesRequest.builder() - .instanceIds(id) - .build(); + DescribeAutoScalingInstancesRequest describeAutoScalingInstancesRequest = DescribeAutoScalingInstancesRequest + .builder() + .instanceIds(id) + .build(); - DescribeAutoScalingInstancesResponse response = autoScalingClient.describeAutoScalingInstances(describeAutoScalingInstancesRequest); + DescribeAutoScalingInstancesResponse response = autoScalingClient + .describeAutoScalingInstances(describeAutoScalingInstancesRequest); List instances = response.autoScalingInstances(); - for (AutoScalingInstanceDetails instance:instances ) { - System.out.println("The instance lifecycle state is: "+instance.lifecycleState()); + for (AutoScalingInstanceDetails instance : instances) { + System.out.println("The instance lifecycle state is: " + instance.lifecycleState()); } } catch (AutoScalingException e) { @@ -278,14 +280,14 @@ public static void describeAutoScalingInstance( AutoScalingClient autoScalingCli public static void describeAutoScalingGroups(AutoScalingClient autoScalingClient, String groupName) { try { DescribeAutoScalingGroupsRequest groupsRequest = DescribeAutoScalingGroupsRequest.builder() - .autoScalingGroupNames(groupName) - .maxRecords(10) - .build(); + .autoScalingGroupNames(groupName) + .maxRecords(10) + .build(); DescribeAutoScalingGroupsResponse response = autoScalingClient.describeAutoScalingGroups(groupsRequest); List groups = response.autoScalingGroups(); - for (AutoScalingGroup group: groups) { - System.out.println("*** The service to use for the health checks: "+ group.healthCheckType()); + for (AutoScalingGroup group : groups) { + System.out.println("*** The service to use for the health checks: " + group.healthCheckType()); } } catch (AutoScalingException e) { @@ -297,15 +299,16 @@ public static void describeAutoScalingGroups(AutoScalingClient autoScalingClient // snippet-start:[autoscale.java2.get_autoscalinggroup.main] public static String getSpecificAutoScalingGroups(AutoScalingClient autoScalingClient, String groupName) { - try{ + try { String instanceId = ""; DescribeAutoScalingGroupsRequest scalingGroupsRequest = DescribeAutoScalingGroupsRequest.builder() - .autoScalingGroupNames(groupName) - .build(); + .autoScalingGroupNames(groupName) + .build(); - DescribeAutoScalingGroupsResponse response = autoScalingClient.describeAutoScalingGroups(scalingGroupsRequest); + DescribeAutoScalingGroupsResponse response = autoScalingClient + .describeAutoScalingGroups(scalingGroupsRequest); List groups = response.autoScalingGroups(); - for (AutoScalingGroup group: groups) { + for (AutoScalingGroup group : groups) { System.out.println("The group name is " + group.autoScalingGroupName()); System.out.println("The group ARN is " + group.autoScalingGroupARN()); List instances = group.instances(); @@ -313,16 +316,16 @@ public static String getSpecificAutoScalingGroups(AutoScalingClient autoScalingC for (Instance instance : instances) { instanceId = instance.instanceId(); System.out.println("The instance id is " + instanceId); - System.out.println("The lifecycle state is " +instance.lifecycleState()); + System.out.println("The lifecycle state is " + instance.lifecycleState()); } } - return instanceId ; + return instanceId; } catch (AutoScalingException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } - return "" ; + return ""; } // snippet-end:[autoscale.java2.get_autoscalinggroup.main] @@ -330,10 +333,10 @@ public static String getSpecificAutoScalingGroups(AutoScalingClient autoScalingC public static void enableMetricsCollection(AutoScalingClient autoScalingClient, String groupName) { try { EnableMetricsCollectionRequest collectionRequest = EnableMetricsCollectionRequest.builder() - .autoScalingGroupName(groupName) - .metrics("GroupMaxSize") - .granularity("1Minute") - .build(); + .autoScalingGroupName(groupName) + .metrics("GroupMaxSize") + .granularity("1Minute") + .build(); autoScalingClient.enableMetricsCollection(collectionRequest); System.out.println("The enable metrics collection operation was successful"); @@ -349,9 +352,9 @@ public static void enableMetricsCollection(AutoScalingClient autoScalingClient, public static void disableMetricsCollection(AutoScalingClient autoScalingClient, String groupName) { try { DisableMetricsCollectionRequest disableMetricsCollectionRequest = DisableMetricsCollectionRequest.builder() - .autoScalingGroupName(groupName) - .metrics("GroupMaxSize") - .build(); + .autoScalingGroupName(groupName) + .metrics("GroupMaxSize") + .build(); autoScalingClient.disableMetricsCollection(disableMetricsCollectionRequest); System.out.println("The disable metrics collection operation was successful"); @@ -367,8 +370,8 @@ public static void disableMetricsCollection(AutoScalingClient autoScalingClient, public static void describeAccountLimits(AutoScalingClient autoScalingClient) { try { DescribeAccountLimitsResponse response = autoScalingClient.describeAccountLimits(); - System.out.println("The max number of auto scaling groups is "+response.maxNumberOfAutoScalingGroups()); - System.out.println("The current number of auto scaling groups is "+response.numberOfAutoScalingGroups()); + System.out.println("The max number of auto scaling groups is " + response.maxNumberOfAutoScalingGroups()); + System.out.println("The current number of auto scaling groups is " + response.numberOfAutoScalingGroups()); } catch (AutoScalingException e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -378,27 +381,29 @@ public static void describeAccountLimits(AutoScalingClient autoScalingClient) { // snippet-end:[autoscale.java2.describe_account.main] // snippet-start:[autoscale.java2.update_autoscalinggroup.main] - public static void updateAutoScalingGroup(AutoScalingClient autoScalingClient, String groupName, String launchTemplateName) { + public static void updateAutoScalingGroup(AutoScalingClient autoScalingClient, String groupName, + String launchTemplateName) { try { AutoScalingWaiter waiter = autoScalingClient.waiter(); LaunchTemplateSpecification templateSpecification = LaunchTemplateSpecification.builder() - .launchTemplateName(launchTemplateName) - .build(); + .launchTemplateName(launchTemplateName) + .build(); UpdateAutoScalingGroupRequest groupRequest = UpdateAutoScalingGroupRequest.builder() - .maxSize(3) - .autoScalingGroupName(groupName) - .launchTemplate(templateSpecification) - .build(); + .maxSize(3) + .autoScalingGroupName(groupName) + .launchTemplate(templateSpecification) + .build(); autoScalingClient.updateAutoScalingGroup(groupRequest); DescribeAutoScalingGroupsRequest groupsRequest = DescribeAutoScalingGroupsRequest.builder() - .autoScalingGroupNames(groupName) - .build(); + .autoScalingGroupNames(groupName) + .build(); - WaiterResponse waiterResponse = waiter.waitUntilGroupInService(groupsRequest); + WaiterResponse waiterResponse = waiter + .waitUntilGroupInService(groupsRequest); waiterResponse.matched().response().ifPresent(System.out::println); - System.out.println("You successfully updated the auto scaling group "+groupName); + System.out.println("You successfully updated the auto scaling group " + groupName); } catch (AutoScalingException e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -408,15 +413,15 @@ public static void updateAutoScalingGroup(AutoScalingClient autoScalingClient, S // snippet-end:[autoscale.java2.update_autoscalinggroup.main] // snippet-start:[autoscale.java2.terminate_instance.main] - public static void terminateInstanceInAutoScalingGroup(AutoScalingClient autoScalingClient, String instanceId){ + public static void terminateInstanceInAutoScalingGroup(AutoScalingClient autoScalingClient, String instanceId) { try { TerminateInstanceInAutoScalingGroupRequest request = TerminateInstanceInAutoScalingGroupRequest.builder() - .instanceId(instanceId) - .shouldDecrementDesiredCapacity(false) - .build(); + .instanceId(instanceId) + .shouldDecrementDesiredCapacity(false) + .build(); autoScalingClient.terminateInstanceInAutoScalingGroup(request); - System.out.println("You have terminated instance "+instanceId); + System.out.println("You have terminated instance " + instanceId); } catch (AutoScalingException e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -429,12 +434,12 @@ public static void terminateInstanceInAutoScalingGroup(AutoScalingClient autoSca public static void deleteAutoScalingGroup(AutoScalingClient autoScalingClient, String groupName) { try { DeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest = DeleteAutoScalingGroupRequest.builder() - .autoScalingGroupName(groupName) - .forceDelete(true) - .build() ; + .autoScalingGroupName(groupName) + .forceDelete(true) + .build(); - autoScalingClient.deleteAutoScalingGroup(deleteAutoScalingGroupRequest) ; - System.out.println("You successfully deleted "+groupName); + autoScalingClient.deleteAutoScalingGroup(deleteAutoScalingGroupRequest); + System.out.println("You successfully deleted " + groupName); } catch (AutoScalingException e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/CreateAutoScalingGroup.java b/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/CreateAutoScalingGroup.java index 04d578a3064..de5b9f78d2f 100644 --- a/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/CreateAutoScalingGroup.java +++ b/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/CreateAutoScalingGroup.java @@ -1,12 +1,8 @@ -//snippet-sourcedescription:[CreateAutoScalingGroup.java creates an Auto Scaling group with the specified name and attributes using a waiter.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2 Auto Scaling] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.autoscaling; + // snippet-start:[autoscale.java2.create_scaling_group.main] // snippet-start:[autoscale.java2.create_scaling_group.import] import software.amazon.awssdk.core.waiters.WaiterResponse; @@ -21,7 +17,8 @@ // snippet-end:[autoscale.java2.create_scaling_group.import] /** - * Before running this SDK for Java (v2) code example, set up your development environment, including your credentials. + * Before running this SDK for Java (v2) code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation: * @@ -31,14 +28,14 @@ public class CreateAutoScalingGroup { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - groupName - The name of the Auto Scaling group. - launchTemplateName - The name of the launch template.\s - vpcZoneId - A subnet Id for a virtual private cloud (VPC) where instances in the Auto Scaling group can be created. - """; + Where: + groupName - The name of the Auto Scaling group. + launchTemplateName - The name of the launch template.\s + vpcZoneId - A subnet Id for a virtual private cloud (VPC) where instances in the Auto Scaling group can be created. + """; if (args.length != 3) { System.out.println(usage); @@ -49,39 +46,40 @@ public static void main(String[] args) { String launchTemplateName = args[1]; String vpcZoneId = args[2]; AutoScalingClient autoScalingClient = AutoScalingClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); createAutoScalingGroup(autoScalingClient, groupName, launchTemplateName, vpcZoneId); autoScalingClient.close(); } public static void createAutoScalingGroup(AutoScalingClient autoScalingClient, - String groupName, - String launchTemplateName, - String vpcZoneId) { + String groupName, + String launchTemplateName, + String vpcZoneId) { try { AutoScalingWaiter waiter = autoScalingClient.waiter(); LaunchTemplateSpecification templateSpecification = LaunchTemplateSpecification.builder() - .launchTemplateName(launchTemplateName) - .build(); + .launchTemplateName(launchTemplateName) + .build(); CreateAutoScalingGroupRequest request = CreateAutoScalingGroupRequest.builder() - .autoScalingGroupName(groupName) - .availabilityZones("us-east-1a") - .launchTemplate(templateSpecification) - .maxSize(1) - .minSize(1) - .vpcZoneIdentifier(vpcZoneId) - .build(); + .autoScalingGroupName(groupName) + .availabilityZones("us-east-1a") + .launchTemplate(templateSpecification) + .maxSize(1) + .minSize(1) + .vpcZoneIdentifier(vpcZoneId) + .build(); autoScalingClient.createAutoScalingGroup(request); DescribeAutoScalingGroupsRequest groupsRequest = DescribeAutoScalingGroupsRequest.builder() - .autoScalingGroupNames(groupName) - .build(); + .autoScalingGroupNames(groupName) + .build(); - WaiterResponse waiterResponse = waiter.waitUntilGroupExists(groupsRequest); + WaiterResponse waiterResponse = waiter + .waitUntilGroupExists(groupsRequest); waiterResponse.matched().response().ifPresent(System.out::println); System.out.println("Auto Scaling Group created"); diff --git a/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/DeleteAutoScalingGroup.java b/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/DeleteAutoScalingGroup.java index 2d9f74b047d..6d2a393265f 100644 --- a/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/DeleteAutoScalingGroup.java +++ b/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/DeleteAutoScalingGroup.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DeleteAutoScalingGroup.java deletes an Auto Scaling group.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2 Auto Scaling] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.autoscaling; @@ -18,7 +12,8 @@ // snippet-end:[autoscale.java2.del_scaling_group.import] /** - * Before running this SDK for Java (v2) code example, set up your development environment, including your credentials. + * Before running this SDK for Java (v2) code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation: * @@ -28,12 +23,12 @@ public class DeleteAutoScalingGroup { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - groupName - The name of the Auto Scaling group. - """; + Where: + groupName - The name of the Auto Scaling group. + """; if (args.length != 1) { System.out.println(usage); @@ -42,8 +37,8 @@ public static void main(String[] args) { String groupName = args[0]; AutoScalingClient autoScalingClient = AutoScalingClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); deleteAutoScalingGroup(autoScalingClient, groupName); autoScalingClient.close(); @@ -52,12 +47,12 @@ public static void main(String[] args) { public static void deleteAutoScalingGroup(AutoScalingClient autoScalingClient, String groupName) { try { DeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest = DeleteAutoScalingGroupRequest.builder() - .autoScalingGroupName(groupName) - .forceDelete(true) - .build() ; + .autoScalingGroupName(groupName) + .forceDelete(true) + .build(); - autoScalingClient.deleteAutoScalingGroup(deleteAutoScalingGroupRequest) ; - System.out.println("You successfully deleted "+groupName); + autoScalingClient.deleteAutoScalingGroup(deleteAutoScalingGroupRequest); + System.out.println("You successfully deleted " + groupName); } catch (AutoScalingException e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/DescribeAutoScalingGroups.java b/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/DescribeAutoScalingGroups.java index 5e38c972dbd..440f568b249 100644 --- a/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/DescribeAutoScalingGroups.java +++ b/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/DescribeAutoScalingGroups.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeAutoScalingGroups.java describes Auto Scaling groups.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2 Auto Scaling] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.autoscaling; @@ -17,7 +11,8 @@ import java.util.List; /** - * Before running this SDK for Java (v2) code example, set up your development environment, including your credentials. + * Before running this SDK for Java (v2) code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation: * @@ -26,18 +21,18 @@ public class DescribeAutoScalingGroups { public static void main(String[] args) throws InterruptedException { AutoScalingClient autoScalingClient = AutoScalingClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); describeGroups(autoScalingClient); } - public static void describeGroups(AutoScalingClient autoScalingClient){ + public static void describeGroups(AutoScalingClient autoScalingClient) { DescribeAutoScalingGroupsResponse response = autoScalingClient.describeAutoScalingGroups(); List groups = response.autoScalingGroups(); groups.forEach(group -> { System.out.println("Group Name: " + group.autoScalingGroupName()); - System.out.println("Group ARN: "+group.autoScalingGroupARN()); + System.out.println("Group ARN: " + group.autoScalingGroupARN()); }); } } diff --git a/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/DescribeAutoScalingInstances.java b/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/DescribeAutoScalingInstances.java index 56f2b40eab7..d25096afc8e 100644 --- a/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/DescribeAutoScalingInstances.java +++ b/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/DescribeAutoScalingInstances.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeAutoScalingInstances.java gets information about the Auto Scaling groups in the account and Region.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2 Auto Scaling] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.autoscaling; @@ -22,7 +16,8 @@ // snippet-end:[autoscale.java2.describe_instances.import] /** - * Before running this SDK for Java (v2) code example, set up your development environment, including your credentials. + * Before running this SDK for Java (v2) code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation: * @@ -32,12 +27,12 @@ public class DescribeAutoScalingInstances { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - groupName - The name of the Auto Scaling group. - """; + Where: + groupName - The name of the Auto Scaling group. + """; if (args.length != 1) { System.out.println(usage); @@ -46,24 +41,25 @@ public static void main(String[] args) { String groupName = args[0]; AutoScalingClient autoScalingClient = AutoScalingClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); String instanceId = getAutoScaling(autoScalingClient, groupName); System.out.println(instanceId); autoScalingClient.close(); } - public static String getAutoScaling( AutoScalingClient autoScalingClient, String groupName) { - try{ + public static String getAutoScaling(AutoScalingClient autoScalingClient, String groupName) { + try { String instanceId = ""; DescribeAutoScalingGroupsRequest scalingGroupsRequest = DescribeAutoScalingGroupsRequest.builder() - .autoScalingGroupNames(groupName) - .build(); + .autoScalingGroupNames(groupName) + .build(); - DescribeAutoScalingGroupsResponse response = autoScalingClient.describeAutoScalingGroups(scalingGroupsRequest); + DescribeAutoScalingGroupsResponse response = autoScalingClient + .describeAutoScalingGroups(scalingGroupsRequest); List groups = response.autoScalingGroups(); - for (AutoScalingGroup group: groups) { + for (AutoScalingGroup group : groups) { System.out.println("The group name is " + group.autoScalingGroupName()); System.out.println("The group ARN is " + group.autoScalingGroupARN()); diff --git a/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/DetachInstances.java b/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/DetachInstances.java index 462d3294938..89619f1ab24 100644 --- a/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/DetachInstances.java +++ b/javav2/example_code/autoscale/src/main/java/com/example/autoscaling/DetachInstances.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[DetachInstances.java removes one or more instances from the specified Auto Scaling group.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2 Auto Scaling] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.autoscaling; @@ -17,7 +12,8 @@ // snippet-end:[autoscale.java2.detach.import] /** - * Before running this SDK for Java (v2) code example, set up your development environment, including your credentials. + * Before running this SDK for Java (v2) code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation: * @@ -27,13 +23,13 @@ public class DetachInstances { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - groupName - The name of the Auto Scaling group. - instanceId - The instance Id value. - """; + Where: + groupName - The name of the Auto Scaling group. + instanceId - The instance Id value. + """; if (args.length != 2) { System.out.println(usage); @@ -43,8 +39,8 @@ public static void main(String[] args) { String groupName = args[0]; String instanceId = args[1]; AutoScalingClient autoScalingClient = AutoScalingClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); detachInstance(autoScalingClient, groupName, instanceId); autoScalingClient.close(); @@ -53,13 +49,13 @@ public static void main(String[] args) { public static void detachInstance(AutoScalingClient autoScalingClient, String groupName, String instanceId) { try { DetachInstancesRequest detachInstancesRequest = DetachInstancesRequest.builder() - .autoScalingGroupName(groupName) - .shouldDecrementDesiredCapacity(false) - .instanceIds(instanceId) - .build(); + .autoScalingGroupName(groupName) + .shouldDecrementDesiredCapacity(false) + .instanceIds(instanceId) + .build(); autoScalingClient.detachInstances(detachInstancesRequest); - System.out.println("You have detached instance "+instanceId +" from "+groupName); + System.out.println("You have detached instance " + instanceId + " from " + groupName); } catch (AutoScalingException e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/autoscale/src/test/java/AutoScaleTest.java b/javav2/example_code/autoscale/src/test/java/AutoScaleTest.java index b11e58b562d..a4192a8724a 100644 --- a/javav2/example_code/autoscale/src/test/java/AutoScaleTest.java +++ b/javav2/example_code/autoscale/src/test/java/AutoScaleTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -36,19 +34,19 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AutoScaleTest { private static AutoScalingClient autoScalingClient; - private static String groupName=""; - private static String groupNameSc=""; - private static String instanceId=""; - private static String instanceId2=""; - private static String launchTemplateName=""; - private static String vpcZoneId=""; + private static String groupName = ""; + private static String groupNameSc = ""; + private static String instanceId = ""; + private static String instanceId2 = ""; + private static String launchTemplateName = ""; + private static String vpcZoneId = ""; @BeforeAll public static void setUp() throws IOException { autoScalingClient = AutoScalingClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); Random random = new Random(); int randomNum = random.nextInt((10000 - 1) + 1) + 1; @@ -56,36 +54,40 @@ public static void setUp() throws IOException { // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); TestValues myValues = gson.fromJson(String.valueOf(getSecretValues()), TestValues.class); - groupName = myValues.getGroupName()+randomNum; + groupName = myValues.getGroupName() + randomNum; launchTemplateName = myValues.getLaunchTemplateName(); vpcZoneId = myValues.getVpcZoneId(); - groupNameSc = myValues.getGroupNameSc()+randomNum; - - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for the tests. - /* - try (InputStream input = AutoScaleTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - prop.load(input); - groupName = prop.getProperty("groupName")+randomNum; - launchTemplateName = prop.getProperty("launchTemplateName"); - vpcZoneId = prop.getProperty("vpcZoneId"); - groupNameSc = prop.getProperty("groupNameSc")+randomNum; - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + groupNameSc = myValues.getGroupNameSc() + randomNum; + + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for the tests. + /* + * try (InputStream input = + * AutoScaleTest.class.getClassLoader().getResourceAsStream("config.properties") + * ) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * prop.load(input); + * groupName = prop.getProperty("groupName")+randomNum; + * launchTemplateName = prop.getProperty("launchTemplateName"); + * vpcZoneId = prop.getProperty("vpcZoneId"); + * groupNameSc = prop.getProperty("groupNameSc")+randomNum; + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @Order(1) public void createAutoScalingGroup() { - assertDoesNotThrow(() -> CreateAutoScalingGroup.createAutoScalingGroup(autoScalingClient, groupName, launchTemplateName, vpcZoneId)); + assertDoesNotThrow(() -> CreateAutoScalingGroup.createAutoScalingGroup(autoScalingClient, groupName, + launchTemplateName, vpcZoneId)); System.out.println("Test 1 passed"); } @@ -102,7 +104,7 @@ public void describeAutoScalingInstances() throws InterruptedException { @Test @Order(3) - public void detachInstances()throws InterruptedException { + public void detachInstances() throws InterruptedException { System.out.println("Wait 1 min for the resources, including the instance"); Thread.sleep(60000); assertDoesNotThrow(() -> DetachInstances.detachInstance(autoScalingClient, groupName, instanceId2)); @@ -119,20 +121,21 @@ public void deleteAutoScalingGroup() { @Test @Order(5) public void autoScalingScenario() throws InterruptedException { - System.out.println("**** Create an Auto Scaling group named "+groupName); + System.out.println("**** Create an Auto Scaling group named " + groupName); AutoScalingScenario.createAutoScalingGroup(autoScalingClient, groupNameSc, launchTemplateName, vpcZoneId); - System.out.println("Wait 1 min for the resources, including the instance. Otherwise, an empty instance Id is returned"); + System.out.println( + "Wait 1 min for the resources, including the instance. Otherwise, an empty instance Id is returned"); Thread.sleep(60000); System.out.println("**** Get Auto Scale group Id value"); String instanceId = AutoScalingScenario.getSpecificAutoScalingGroups(autoScalingClient, groupNameSc); assertFalse(instanceId.isEmpty()); - System.out.println("**** Describe Auto Scaling with the Id value "+instanceId); - AutoScalingScenario.describeAutoScalingInstance( autoScalingClient, instanceId); + System.out.println("**** Describe Auto Scaling with the Id value " + instanceId); + AutoScalingScenario.describeAutoScalingInstance(autoScalingClient, instanceId); - System.out.println("**** Enable metrics collection "+instanceId); + System.out.println("**** Enable metrics collection " + instanceId); AutoScalingScenario.enableMetricsCollection(autoScalingClient, groupNameSc); System.out.println("**** Update an Auto Scaling group to update max size to 3"); @@ -144,7 +147,8 @@ public void autoScalingScenario() throws InterruptedException { System.out.println("**** Describe account details"); AutoScalingScenario.describeAccountLimits(autoScalingClient); - System.out.println("Wait 1 min for the resources, including the instance. Otherwise, an empty instance Id is returned"); + System.out.println( + "Wait 1 min for the resources, including the instance. Otherwise, an empty instance Id is returned"); Thread.sleep(60000); System.out.println("**** Set desired capacity to 2"); @@ -165,16 +169,17 @@ public void autoScalingScenario() throws InterruptedException { System.out.println("**** Delete the Auto Scaling group"); AutoScalingScenario.deleteAutoScalingGroup(autoScalingClient, groupNameSc); } + private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/autoscale"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -193,21 +198,20 @@ class TestValues { TestValues() { } - String getGroupName(){ + String getGroupName() { return this.groupName; } - String getGroupNameSc(){ + String getGroupNameSc() { return this.groupNameSc; } - String getLaunchTemplateName(){ + String getLaunchTemplateName() { return this.launchTemplateName; } - String getVpcZoneId(){ + String getVpcZoneId() { return this.vpcZoneId; } } } - diff --git a/javav2/example_code/bedrock-runtime/src/main/java/com/example/bedrockruntime/BedrockRuntimeUsageDemo.java b/javav2/example_code/bedrock-runtime/src/main/java/com/example/bedrockruntime/BedrockRuntimeUsageDemo.java index 8c6b6295f81..9a3833a5b42 100644 --- a/javav2/example_code/bedrock-runtime/src/main/java/com/example/bedrockruntime/BedrockRuntimeUsageDemo.java +++ b/javav2/example_code/bedrock-runtime/src/main/java/com/example/bedrockruntime/BedrockRuntimeUsageDemo.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.bedrockruntime; @@ -19,7 +17,8 @@ /** * Demonstrates the invocation of the following models: - * Anthropic Claude 2, AI21 Labs Jurassic-2, Meta Llama 2 Chat, and Stability.ai Stable Diffusion XL. + * Anthropic Claude 2, AI21 Labs Jurassic-2, Meta Llama 2 Chat, and Stability.ai + * Stable Diffusion XL. */ public class BedrockRuntimeUsageDemo { diff --git a/javav2/example_code/bedrock-runtime/src/main/java/com/example/bedrockruntime/InvokeModel.java b/javav2/example_code/bedrock-runtime/src/main/java/com/example/bedrockruntime/InvokeModel.java index 2b5c03b7fb0..346b3e593c3 100644 --- a/javav2/example_code/bedrock-runtime/src/main/java/com/example/bedrockruntime/InvokeModel.java +++ b/javav2/example_code/bedrock-runtime/src/main/java/com/example/bedrockruntime/InvokeModel.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[InvokeModel.java demonstrates how to invoke models with Amazon Bedrock.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Bedrock] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.bedrockruntime; @@ -24,9 +17,9 @@ import java.util.List; // snippet-end:[bedrock-runtime.java2.invoke_model.import] - /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -34,254 +27,266 @@ */ public class InvokeModel { - // snippet-start:[bedrock-runtime.java2.invoke_claude.main] - /** - * Invokes the Anthropic Claude 2 model to run an inference based on the provided input. - * - * @param prompt The prompt for Claude to complete. - * @return The generated response. - */ - public static String invokeClaude(String prompt) { - /* - The different model providers have individual request and response formats. - For the format, ranges, and default values for Anthropic Claude, refer to: - https://docs.anthropic.com/claude/reference/complete_post + // snippet-start:[bedrock-runtime.java2.invoke_claude.main] + /** + * Invokes the Anthropic Claude 2 model to run an inference based on the + * provided input. + * + * @param prompt The prompt for Claude to complete. + * @return The generated response. */ + public static String invokeClaude(String prompt) { + /* + * The different model providers have individual request and response formats. + * For the format, ranges, and default values for Anthropic Claude, refer to: + * https://docs.anthropic.com/claude/reference/complete_post + */ - String claudeModelId = "anthropic.claude-v2"; - - // Claude requires you to enclose the prompt as follows: - String enclosedPrompt = "Human: " + prompt + "\n\nAssistant:"; - - BedrockRuntimeClient client = BedrockRuntimeClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); - - String payload = new JSONObject() - .put("prompt", enclosedPrompt) - .put("max_tokens_to_sample", 200) - .put("temperature", 0.5) - .put("stop_sequences", List.of("\n\nHuman:")) - .toString(); - - InvokeModelRequest request = InvokeModelRequest.builder() - .body(SdkBytes.fromUtf8String(payload)) - .modelId(claudeModelId) - .contentType("application/json") - .accept("application/json") - .build(); - - - InvokeModelResponse response = client.invokeModel(request); - - JSONObject responseBody = new JSONObject(response.body().asUtf8String()); - - String generatedText = responseBody.getString("completion"); - - return generatedText; - } - // snippet-end:[bedrock-runtime.java2.invoke_claude.main] - - // snippet-start:[bedrock-runtime.java2.invoke_jurassic2.main] - /** - * Invokes the AI21 Labs Jurassic-2 model to run an inference based on the provided input. - * - * @param prompt The prompt for Jurassic to complete. - * @return The generated response. - */ - public static String invokeJurassic2(String prompt) { - /* - The different model providers have individual request and response formats. - For the format, ranges, and default values for AI21 Labs Jurassic-2, refer to: - https://docs.ai21.com/reference/j2-complete-ref - */ + String claudeModelId = "anthropic.claude-v2"; - String jurassic2ModelId = "ai21.j2-mid-v1"; - - BedrockRuntimeClient client = BedrockRuntimeClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); - - String payload = new JSONObject() - .put("prompt", prompt) - .put("temperature", 0.5) - .put("maxTokens", 200) - .toString(); - - InvokeModelRequest request = InvokeModelRequest.builder() - .body(SdkBytes.fromUtf8String(payload)) - .modelId(jurassic2ModelId) - .contentType("application/json") - .accept("application/json") - .build(); - - InvokeModelResponse response = client.invokeModel(request); - - JSONObject responseBody = new JSONObject(response.body().asUtf8String()); - - String generatedText = responseBody - .getJSONArray("completions") - .getJSONObject(0) - .getJSONObject("data") - .getString("text"); - - return generatedText; - } - // snippet-end:[bedrock-runtime.java2.invoke_jurassic2.main] - - // snippet-start:[bedrock-runtime.java2.invoke_llama2.main] - /** - * Invokes the Meta Llama 2 Chat model to run an inference based on the provided input. - * - * @param prompt The prompt for Llama 2 to complete. - * @return The generated response. - */ - public static String invokeLlama2(String prompt) { - /* - The different model providers have individual request and response formats. - For the format, ranges, and default values for Meta Llama 2 Chat, refer to: - https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-meta.html - */ + // Claude requires you to enclose the prompt as follows: + String enclosedPrompt = "Human: " + prompt + "\n\nAssistant:"; - String llama2ModelId = "meta.llama2-13b-chat-v1"; - - BedrockRuntimeClient client = BedrockRuntimeClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); - - String payload = new JSONObject() - .put("prompt", prompt) - .put("max_gen_len", 512) - .put("temperature", 0.5) - .put("top_p", 0.9) - .toString(); - - InvokeModelRequest request = InvokeModelRequest.builder() - .body(SdkBytes.fromUtf8String(payload)) - .modelId(llama2ModelId) - .contentType("application/json") - .accept("application/json") - .build(); - - InvokeModelResponse response = client.invokeModel(request); - - JSONObject responseBody = new JSONObject(response.body().asUtf8String()); - - String generatedText = responseBody.getString("generation"); - - return generatedText; - } - // snippet-end:[bedrock-runtime.java2.invoke_llama2.main] - - // snippet-start:[bedrock-runtime.java2.invoke_stable_diffusion.main] - /** - * Invokes the Stability.ai Stable Diffusion XL model to create an image based on the provided input. - * - * @param prompt The prompt that guides the Stable Diffusion model. - * @param seed The random noise seed for image generation (use 0 or omit for a random seed). - * @param stylePreset The style preset to guide the image model towards a specific style. - * @return A Base64-encoded string representing the generated image. - */ - public static String invokeStableDiffusion(String prompt, long seed, String stylePreset) { - /* - The different model providers have individual request and response formats. - For the format, ranges, and available style_presets of Stable Diffusion models refer to: - https://platform.stability.ai/docs/api-reference#tag/v1generation - */ + BedrockRuntimeClient client = BedrockRuntimeClient.builder() + .region(Region.US_EAST_1) + .credentialsProvider(ProfileCredentialsProvider.create()) + .build(); + + String payload = new JSONObject() + .put("prompt", enclosedPrompt) + .put("max_tokens_to_sample", 200) + .put("temperature", 0.5) + .put("stop_sequences", List.of("\n\nHuman:")) + .toString(); - String stableDiffusionModelId = "stability.stable-diffusion-xl"; + InvokeModelRequest request = InvokeModelRequest.builder() + .body(SdkBytes.fromUtf8String(payload)) + .modelId(claudeModelId) + .contentType("application/json") + .accept("application/json") + .build(); - BedrockRuntimeClient client = BedrockRuntimeClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); + InvokeModelResponse response = client.invokeModel(request); - JSONArray wrappedPrompt = new JSONArray().put(new JSONObject().put("text", prompt)); + JSONObject responseBody = new JSONObject(response.body().asUtf8String()); - JSONObject payload = new JSONObject() - .put("text_prompts", wrappedPrompt) - .put("seed", seed); + String generatedText = responseBody.getString("completion"); - if (!(stylePreset == null || stylePreset.isEmpty())) { - payload.put("style_preset", stylePreset); + return generatedText; } + // snippet-end:[bedrock-runtime.java2.invoke_claude.main] + + // snippet-start:[bedrock-runtime.java2.invoke_jurassic2.main] + /** + * Invokes the AI21 Labs Jurassic-2 model to run an inference based on the + * provided input. + * + * @param prompt The prompt for Jurassic to complete. + * @return The generated response. + */ + public static String invokeJurassic2(String prompt) { + /* + * The different model providers have individual request and response formats. + * For the format, ranges, and default values for AI21 Labs Jurassic-2, refer + * to: + * https://docs.ai21.com/reference/j2-complete-ref + */ + + String jurassic2ModelId = "ai21.j2-mid-v1"; + + BedrockRuntimeClient client = BedrockRuntimeClient.builder() + .region(Region.US_EAST_1) + .credentialsProvider(ProfileCredentialsProvider.create()) + .build(); + + String payload = new JSONObject() + .put("prompt", prompt) + .put("temperature", 0.5) + .put("maxTokens", 200) + .toString(); + + InvokeModelRequest request = InvokeModelRequest.builder() + .body(SdkBytes.fromUtf8String(payload)) + .modelId(jurassic2ModelId) + .contentType("application/json") + .accept("application/json") + .build(); + + InvokeModelResponse response = client.invokeModel(request); + + JSONObject responseBody = new JSONObject(response.body().asUtf8String()); + + String generatedText = responseBody + .getJSONArray("completions") + .getJSONObject(0) + .getJSONObject("data") + .getString("text"); + + return generatedText; + } + // snippet-end:[bedrock-runtime.java2.invoke_jurassic2.main] + + // snippet-start:[bedrock-runtime.java2.invoke_llama2.main] + /** + * Invokes the Meta Llama 2 Chat model to run an inference based on the provided + * input. + * + * @param prompt The prompt for Llama 2 to complete. + * @return The generated response. + */ + public static String invokeLlama2(String prompt) { + /* + * The different model providers have individual request and response formats. + * For the format, ranges, and default values for Meta Llama 2 Chat, refer to: + * https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-meta. + * html + */ + + String llama2ModelId = "meta.llama2-13b-chat-v1"; + + BedrockRuntimeClient client = BedrockRuntimeClient.builder() + .region(Region.US_EAST_1) + .credentialsProvider(ProfileCredentialsProvider.create()) + .build(); + + String payload = new JSONObject() + .put("prompt", prompt) + .put("max_gen_len", 512) + .put("temperature", 0.5) + .put("top_p", 0.9) + .toString(); + + InvokeModelRequest request = InvokeModelRequest.builder() + .body(SdkBytes.fromUtf8String(payload)) + .modelId(llama2ModelId) + .contentType("application/json") + .accept("application/json") + .build(); + + InvokeModelResponse response = client.invokeModel(request); + + JSONObject responseBody = new JSONObject(response.body().asUtf8String()); + + String generatedText = responseBody.getString("generation"); + + return generatedText; + } + // snippet-end:[bedrock-runtime.java2.invoke_llama2.main] + + // snippet-start:[bedrock-runtime.java2.invoke_stable_diffusion.main] + /** + * Invokes the Stability.ai Stable Diffusion XL model to create an image based + * on the provided input. + * + * @param prompt The prompt that guides the Stable Diffusion model. + * @param seed The random noise seed for image generation (use 0 or omit + * for a random seed). + * @param stylePreset The style preset to guide the image model towards a + * specific style. + * @return A Base64-encoded string representing the generated image. + */ + public static String invokeStableDiffusion(String prompt, long seed, String stylePreset) { + /* + * The different model providers have individual request and response formats. + * For the format, ranges, and available style_presets of Stable Diffusion + * models refer to: + * https://platform.stability.ai/docs/api-reference#tag/v1generation + */ + + String stableDiffusionModelId = "stability.stable-diffusion-xl"; - InvokeModelRequest request = InvokeModelRequest.builder() - .body(SdkBytes.fromUtf8String(payload.toString())) - .modelId(stableDiffusionModelId) - .contentType("application/json") - .accept("application/json") - .build(); - - InvokeModelResponse response = client.invokeModel(request); - - JSONObject responseBody = new JSONObject(response.body().asUtf8String()); - - String base64ImageData = responseBody - .getJSONArray("artifacts") - .getJSONObject(0) - .getString("base64"); - - return base64ImageData; - } - // snippet-end:[bedrock-runtime.java2.invoke_stable_diffusion.main] - - // snippet-start:[bedrock-runtime.java2.invoke_titan_image.main] - /** - * Invokes the Amazon Titan image generation model to create an image using the input - * provided in the request body. - * - * @param prompt The prompt that you want Amazon Titan to use for image generation. - * @param seed The random noise seed for image generation (Range: 0 to 2147483647). - * @return A Base64-encoded string representing the generated image. - */ - public static String invokeTitanImage(String prompt, long seed) { - /* - The different model providers have individual request and response formats. - For the format, ranges, and default values for Titan Image models refer to: - https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-titan-image.html - */ - String titanImageModelId = "amazon.titan-image-generator-v1"; - - BedrockRuntimeClient client = BedrockRuntimeClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); - - var textToImageParams = new JSONObject().put("text", prompt); - - var imageGenerationConfig = new JSONObject() - .put("numberOfImages", 1) - .put("quality", "standard") - .put("cfgScale", 8.0) - .put("height", 512) - .put("width", 512) - .put("seed", seed); - - JSONObject payload = new JSONObject() - .put("taskType", "TEXT_IMAGE") - .put("textToImageParams", textToImageParams) - .put("imageGenerationConfig", imageGenerationConfig); - - InvokeModelRequest request = InvokeModelRequest.builder() - .body(SdkBytes.fromUtf8String(payload.toString())) - .modelId(titanImageModelId) - .contentType("application/json") - .accept("application/json") - .build(); - - InvokeModelResponse response = client.invokeModel(request); - - JSONObject responseBody = new JSONObject(response.body().asUtf8String()); - - String base64ImageData = responseBody - .getJSONArray("images") - .getString(0); - - return base64ImageData; - } - // snippet-end:[bedrock-runtime.java2.invoke_titan_image.main] + BedrockRuntimeClient client = BedrockRuntimeClient.builder() + .region(Region.US_EAST_1) + .credentialsProvider(ProfileCredentialsProvider.create()) + .build(); + + JSONArray wrappedPrompt = new JSONArray().put(new JSONObject().put("text", prompt)); + + JSONObject payload = new JSONObject() + .put("text_prompts", wrappedPrompt) + .put("seed", seed); + + if (!(stylePreset == null || stylePreset.isEmpty())) { + payload.put("style_preset", stylePreset); + } + + InvokeModelRequest request = InvokeModelRequest.builder() + .body(SdkBytes.fromUtf8String(payload.toString())) + .modelId(stableDiffusionModelId) + .contentType("application/json") + .accept("application/json") + .build(); + + InvokeModelResponse response = client.invokeModel(request); + + JSONObject responseBody = new JSONObject(response.body().asUtf8String()); + + String base64ImageData = responseBody + .getJSONArray("artifacts") + .getJSONObject(0) + .getString("base64"); + + return base64ImageData; + } + // snippet-end:[bedrock-runtime.java2.invoke_stable_diffusion.main] + + // snippet-start:[bedrock-runtime.java2.invoke_titan_image.main] + /** + * Invokes the Amazon Titan image generation model to create an image using the + * input + * provided in the request body. + * + * @param prompt The prompt that you want Amazon Titan to use for image + * generation. + * @param seed The random noise seed for image generation (Range: 0 to + * 2147483647). + * @return A Base64-encoded string representing the generated image. + */ + public static String invokeTitanImage(String prompt, long seed) { + /* + * The different model providers have individual request and response formats. + * For the format, ranges, and default values for Titan Image models refer to: + * https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-titan- + * image.html + */ + String titanImageModelId = "amazon.titan-image-generator-v1"; + + BedrockRuntimeClient client = BedrockRuntimeClient.builder() + .region(Region.US_EAST_1) + .credentialsProvider(ProfileCredentialsProvider.create()) + .build(); + + var textToImageParams = new JSONObject().put("text", prompt); + + var imageGenerationConfig = new JSONObject() + .put("numberOfImages", 1) + .put("quality", "standard") + .put("cfgScale", 8.0) + .put("height", 512) + .put("width", 512) + .put("seed", seed); + + JSONObject payload = new JSONObject() + .put("taskType", "TEXT_IMAGE") + .put("textToImageParams", textToImageParams) + .put("imageGenerationConfig", imageGenerationConfig); + + InvokeModelRequest request = InvokeModelRequest.builder() + .body(SdkBytes.fromUtf8String(payload.toString())) + .modelId(titanImageModelId) + .contentType("application/json") + .accept("application/json") + .build(); + + InvokeModelResponse response = client.invokeModel(request); + + JSONObject responseBody = new JSONObject(response.body().asUtf8String()); + + String base64ImageData = responseBody + .getJSONArray("images") + .getString(0); + + return base64ImageData; + } + // snippet-end:[bedrock-runtime.java2.invoke_titan_image.main] } diff --git a/javav2/example_code/bedrock-runtime/src/main/java/com/example/bedrockruntime/InvokeModelAsync.java b/javav2/example_code/bedrock-runtime/src/main/java/com/example/bedrockruntime/InvokeModelAsync.java index 648a91d1e05..eabe1ebbe89 100644 --- a/javav2/example_code/bedrock-runtime/src/main/java/com/example/bedrockruntime/InvokeModelAsync.java +++ b/javav2/example_code/bedrock-runtime/src/main/java/com/example/bedrockruntime/InvokeModelAsync.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[InvokeModelAsync.java demonstrates how to asynchronously invoke models with Amazon Bedrock.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Bedrock] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.bedrockruntime; @@ -27,7 +20,8 @@ // snippet-end:[bedrock-runtime.java2.invoke_model_async.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -37,16 +31,17 @@ public class InvokeModelAsync { // snippet-start:[bedrock-runtime.java2.invoke_claude_async.main] /** - * Asynchronously invokes the Anthropic Claude 2 model to run an inference based on the provided input. + * Asynchronously invokes the Anthropic Claude 2 model to run an inference based + * on the provided input. * * @param prompt The prompt that you want Claude to complete. * @return The inference response from the model. */ public static String invokeClaude(String prompt) { /* - The different model providers have individual request and response formats. - For the format, ranges, and default values for Anthropic Claude, refer to: - https://docs.anthropic.com/claude/reference/complete_post + * The different model providers have individual request and response formats. + * For the format, ranges, and default values for Anthropic Claude, refer to: + * https://docs.anthropic.com/claude/reference/complete_post */ String claudeModelId = "anthropic.claude-v2"; @@ -98,16 +93,17 @@ public static String invokeClaude(String prompt) { // snippet-start:[bedrock-runtime.java2.invoke_jurassic-2_async.main] /** - * Asynchronously invokes the AI21 Labs Jurassic-2 model to run an inference based on the provided input. + * Asynchronously invokes the AI21 Labs Jurassic-2 model to run an inference + * based on the provided input. * * @param prompt The prompt that you want Jurassic to complete. * @return The inference response generated by the model. */ public static String invokeJurassic2(String prompt) { /* - The different model providers have individual request and response formats. - For the format, ranges, and default values for Anthropic Claude, refer to: - https://docs.anthropic.com/claude/reference/complete_post + * The different model providers have individual request and response formats. + * For the format, ranges, and default values for Anthropic Claude, refer to: + * https://docs.anthropic.com/claude/reference/complete_post */ String jurassic2ModelId = "ai21.j2-mid-v1"; @@ -160,16 +156,18 @@ public static String invokeJurassic2(String prompt) { // snippet-start:[bedrock-runtime.java2.invoke_llama2_async.main] /** - * Asynchronously invokes the Meta Llama 2 Chat model to run an inference based on the provided input. + * Asynchronously invokes the Meta Llama 2 Chat model to run an inference based + * on the provided input. * * @param prompt The prompt that you want Llama 2 to complete. * @return The inference response generated by the model. */ public static String invokeLlama2(String prompt) { /* - The different model providers have individual request and response formats. - For the format, ranges, and default values for Meta Llama 2 Chat, refer to: - https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-meta.html + * The different model providers have individual request and response formats. + * For the format, ranges, and default values for Meta Llama 2 Chat, refer to: + * https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-meta. + * html */ String llama2ModelId = "meta.llama2-13b-chat-v1"; @@ -219,18 +217,22 @@ public static String invokeLlama2(String prompt) { // snippet-start:[bedrock-runtime.java2.invoke_stable_diffusion_async.main] /** - * Asynchronously invokes the Stability.ai Stable Diffusion XL model to create an image based on the provided input. + * Asynchronously invokes the Stability.ai Stable Diffusion XL model to create + * an image based on the provided input. * - * @param prompt The prompt that guides the Stable Diffusion model. - * @param seed The random noise seed for image generation (use 0 or omit for a random seed). - * @param stylePreset The style preset to guide the image model towards a specific style. + * @param prompt The prompt that guides the Stable Diffusion model. + * @param seed The random noise seed for image generation (use 0 or omit + * for a random seed). + * @param stylePreset The style preset to guide the image model towards a + * specific style. * @return A Base64-encoded string representing the generated image. */ public static String invokeStableDiffusion(String prompt, long seed, String stylePreset) { /* - The different model providers have individual request and response formats. - For the format, ranges, and available style_presets of Stable Diffusion models refer to: - https://platform.stability.ai/docs/api-reference#tag/v1generation + * The different model providers have individual request and response formats. + * For the format, ranges, and available style_presets of Stable Diffusion + * models refer to: + * https://platform.stability.ai/docs/api-reference#tag/v1generation */ String stableDiffusionModelId = "stability.stable-diffusion-xl"; @@ -285,19 +287,23 @@ public static String invokeStableDiffusion(String prompt, long seed, String styl // snippet-start:[bedrock-runtime.java2.invoke_titan_image_async.main] /** - * Invokes the Amazon Titan image generation model to create an image using the input + * Invokes the Amazon Titan image generation model to create an image using the + * input * provided in the request body. * - * @param prompt The prompt that you want Amazon Titan to use for image generation. - * @param seed The random noise seed for image generation (Range: 0 to 2147483647). + * @param prompt The prompt that you want Amazon Titan to use for image + * generation. + * @param seed The random noise seed for image generation (Range: 0 to + * 2147483647). * @return A Base64-encoded string representing the generated image. */ public static String invokeTitanImage(String prompt, long seed) { /* - The different model providers have individual request and response formats. - For the format, ranges, and default values for Titan Image models refer to: - https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-titan-image.html - */ + * The different model providers have individual request and response formats. + * For the format, ranges, and default values for Titan Image models refer to: + * https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-titan- + * image.html + */ String titanImageModelId = "amazon.titan-image-generator-v1"; BedrockRuntimeAsyncClient client = BedrockRuntimeAsyncClient.builder() diff --git a/javav2/example_code/bedrock-runtime/src/main/java/com/example/bedrockruntime/InvokeModelWithResponseStream.java b/javav2/example_code/bedrock-runtime/src/main/java/com/example/bedrockruntime/InvokeModelWithResponseStream.java index 263728881d5..9837221134f 100644 --- a/javav2/example_code/bedrock-runtime/src/main/java/com/example/bedrockruntime/InvokeModelWithResponseStream.java +++ b/javav2/example_code/bedrock-runtime/src/main/java/com/example/bedrockruntime/InvokeModelWithResponseStream.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[InvokeModel.java demonstrates how to invoke a model with Amazon Bedrock and process the response stream.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Bedrock] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.bedrockruntime; @@ -23,7 +16,8 @@ // snippet-end:[bedrock-runtime.java2.invoke_model_with_response_stream.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,54 +25,58 @@ */ public class InvokeModelWithResponseStream { - // snippet-start:[bedrock-runtime.java2.invoke_model_with_response_stream.main] - /** - * Invokes the Anthropic Claude 2 model and processes the response stream. - * - * @param prompt The prompt for Claude to complete. - * @param silent Suppress console output of the individual response stream chunks. - * @return The generated response. - */ - public static String invokeClaude(String prompt, boolean silent) { + // snippet-start:[bedrock-runtime.java2.invoke_model_with_response_stream.main] + /** + * Invokes the Anthropic Claude 2 model and processes the response stream. + * + * @param prompt The prompt for Claude to complete. + * @param silent Suppress console output of the individual response stream + * chunks. + * @return The generated response. + */ + public static String invokeClaude(String prompt, boolean silent) { - BedrockRuntimeAsyncClient client = BedrockRuntimeAsyncClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); + BedrockRuntimeAsyncClient client = BedrockRuntimeAsyncClient.builder() + .region(Region.US_EAST_1) + .credentialsProvider(ProfileCredentialsProvider.create()) + .build(); - var finalCompletion = new AtomicReference<>(""); + var finalCompletion = new AtomicReference<>(""); - var payload = new JSONObject() - .put("prompt", "Human: " + prompt + " Assistant:") - .put("temperature", 0.8) - .put("max_tokens_to_sample", 300) - .toString(); + var payload = new JSONObject() + .put("prompt", "Human: " + prompt + " Assistant:") + .put("temperature", 0.8) + .put("max_tokens_to_sample", 300) + .toString(); - var request = InvokeModelWithResponseStreamRequest.builder() - .body(SdkBytes.fromUtf8String(payload)) - .modelId("anthropic.claude-v2") - .contentType("application/json") - .accept("application/json") - .build(); + var request = InvokeModelWithResponseStreamRequest.builder() + .body(SdkBytes.fromUtf8String(payload)) + .modelId("anthropic.claude-v2") + .contentType("application/json") + .accept("application/json") + .build(); - var visitor = InvokeModelWithResponseStreamResponseHandler.Visitor.builder() - .onChunk(chunk -> { - var json = new JSONObject(chunk.bytes().asUtf8String()); - var completion = json.getString("completion"); - finalCompletion.set(finalCompletion.get() + completion); - if (!silent) { System.out.print(completion); } - }) - .build(); + var visitor = InvokeModelWithResponseStreamResponseHandler.Visitor.builder() + .onChunk(chunk -> { + var json = new JSONObject(chunk.bytes().asUtf8String()); + var completion = json.getString("completion"); + finalCompletion.set(finalCompletion.get() + completion); + if (!silent) { + System.out.print(completion); + } + }) + .build(); - var handler = InvokeModelWithResponseStreamResponseHandler.builder() - .onEventStream(stream -> stream.subscribe(event -> event.accept(visitor))) - .onComplete(() -> {} ) - .onError(e -> System.out.println("\n\nError: " + e.getMessage())) - .build(); + var handler = InvokeModelWithResponseStreamResponseHandler.builder() + .onEventStream(stream -> stream.subscribe(event -> event.accept(visitor))) + .onComplete(() -> { + }) + .onError(e -> System.out.println("\n\nError: " + e.getMessage())) + .build(); - client.invokeModelWithResponseStream(request, handler).join(); + client.invokeModelWithResponseStream(request, handler).join(); - return finalCompletion.get(); - } - // snippet-end:[bedrock-runtime.java2.invoke_model_with_response_stream.main] + return finalCompletion.get(); + } + // snippet-end:[bedrock-runtime.java2.invoke_model_with_response_stream.main] } diff --git a/javav2/example_code/bedrock-runtime/src/test/java/TestBase.java b/javav2/example_code/bedrock-runtime/src/test/java/TestBase.java index d0e8257d6c4..669fde95174 100644 --- a/javav2/example_code/bedrock-runtime/src/test/java/TestBase.java +++ b/javav2/example_code/bedrock-runtime/src/test/java/TestBase.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; diff --git a/javav2/example_code/bedrock-runtime/src/test/java/TextToImageAsyncTest.java b/javav2/example_code/bedrock-runtime/src/test/java/TextToImageAsyncTest.java index 9ae618dfdf5..5d9d01c4121 100644 --- a/javav2/example_code/bedrock-runtime/src/test/java/TextToImageAsyncTest.java +++ b/javav2/example_code/bedrock-runtime/src/test/java/TextToImageAsyncTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.bedrockruntime.InvokeModelAsync; import org.junit.jupiter.api.*; diff --git a/javav2/example_code/bedrock-runtime/src/test/java/TextToImageSyncTest.java b/javav2/example_code/bedrock-runtime/src/test/java/TextToImageSyncTest.java index cb4669af996..7e198c652b3 100644 --- a/javav2/example_code/bedrock-runtime/src/test/java/TextToImageSyncTest.java +++ b/javav2/example_code/bedrock-runtime/src/test/java/TextToImageSyncTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.bedrockruntime.InvokeModel; import org.junit.jupiter.api.*; diff --git a/javav2/example_code/bedrock-runtime/src/test/java/TextToTextAsyncTest.java b/javav2/example_code/bedrock-runtime/src/test/java/TextToTextAsyncTest.java index c15eb54890a..5789c6f1a90 100644 --- a/javav2/example_code/bedrock-runtime/src/test/java/TextToTextAsyncTest.java +++ b/javav2/example_code/bedrock-runtime/src/test/java/TextToTextAsyncTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.bedrockruntime.InvokeModelAsync; import com.example.bedrockruntime.InvokeModelWithResponseStream; diff --git a/javav2/example_code/bedrock-runtime/src/test/java/TextToTextSyncTest.java b/javav2/example_code/bedrock-runtime/src/test/java/TextToTextSyncTest.java index fab4ee5de90..9861f15dfa6 100644 --- a/javav2/example_code/bedrock-runtime/src/test/java/TextToTextSyncTest.java +++ b/javav2/example_code/bedrock-runtime/src/test/java/TextToTextSyncTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.bedrockruntime.InvokeModel; import org.junit.jupiter.api.*; diff --git a/javav2/example_code/bedrock/src/main/java/com/example/bedrock/ListFoundationModels.java b/javav2/example_code/bedrock/src/main/java/com/example/bedrock/ListFoundationModels.java index 2ab239ad066..9c5a76f8e79 100644 --- a/javav2/example_code/bedrock/src/main/java/com/example/bedrock/ListFoundationModels.java +++ b/javav2/example_code/bedrock/src/main/java/com/example/bedrock/ListFoundationModels.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[ListFoundationModels.java demonstrates how to obtain a list of the available foundation models.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Bedrock] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.bedrock; @@ -22,7 +15,8 @@ // snippet-end:[bedrock.java2.list_foundation_models.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * diff --git a/javav2/example_code/bedrock/src/test/java/BedrockTest.java b/javav2/example_code/bedrock/src/test/java/BedrockTest.java index 852cab86d56..1cb7d81f557 100644 --- a/javav2/example_code/bedrock/src/test/java/BedrockTest.java +++ b/javav2/example_code/bedrock/src/test/java/BedrockTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.bedrock.ListFoundationModels; import org.junit.jupiter.api.BeforeAll; diff --git a/javav2/example_code/cloudformation/src/main/java/com/example/cloudformation/CreateStack.java b/javav2/example_code/cloudformation/src/main/java/com/example/cloudformation/CreateStack.java index bc4c492e857..965587cb2e1 100644 --- a/javav2/example_code/cloudformation/src/main/java/com/example/cloudformation/CreateStack.java +++ b/javav2/example_code/cloudformation/src/main/java/com/example/cloudformation/CreateStack.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[CreateStack.java demonstrates how to create a stack based on a template and wait until it's ready by using a waiter.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CloudFormation] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudformation; @@ -25,15 +18,19 @@ // snippet-end:[cf.java2.create_stack.import] /** - * To run this example, you must have a valid template that is located in an Amazon S3 bucket. - * For example: + * To run this example, you must have a valid template that is located in an + * Amazon S3 bucket. + * For example: * - * https://s3.amazonaws.com//template.yml + * https://s3.amazonaws.com//template.yml * - * Also, the role that you use must have CloudFormation permissions as well as Amazon S3 and Amazon EC2 permissions. For more information, - * see "Getting started with AWS CloudFormation" in the AWS CloudFormation User Guide. + * Also, the role that you use must have CloudFormation permissions as well as + * Amazon S3 and Amazon EC2 permissions. For more information, + * see "Getting started with AWS CloudFormation" in the AWS CloudFormation User + * Guide. * - * Also, before running this Java V2 code example, set up your development environment, including your credentials. + * Also, before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -45,16 +42,16 @@ public class CreateStack { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - stackName - The name of the AWS CloudFormation stack.\s - roleARN - The ARN of the role that has AWS CloudFormation permissions.\s - location - The location of file containing the template body. (for example, https://s3.amazonaws.com//template.yml).\s - key - The key associated with the parameter.\s - value - The value associated with the parameter.\s - """; + Where: + stackName - The name of the AWS CloudFormation stack.\s + roleARN - The ARN of the role that has AWS CloudFormation permissions.\s + location - The location of file containing the template body. (for example, https://s3.amazonaws.com//template.yml).\s + key - The key associated with the parameter.\s + value - The value associated with the parameter.\s + """; if (args.length != 5) { System.out.println(usage); @@ -69,38 +66,38 @@ public static void main(String[] args) { Region region = Region.US_EAST_1; CloudFormationClient cfClient = CloudFormationClient.builder() - .region(region) - .build(); + .region(region) + .build(); createCFStack(cfClient, stackName, roleARN, location, key, value); cfClient.close(); } public static void createCFStack(CloudFormationClient cfClient, - String stackName, - String roleARN, - String location, - String key, - String value) { + String stackName, + String roleARN, + String location, + String key, + String value) { try { CloudFormationWaiter waiter = cfClient.waiter(); Parameter myParameter = Parameter.builder() - .parameterKey(key) - .parameterValue(value) - .build(); + .parameterKey(key) + .parameterValue(value) + .build(); CreateStackRequest stackRequest = CreateStackRequest.builder() - .stackName(stackName) - .templateURL(location) - .roleARN(roleARN) - .onFailure(OnFailure.ROLLBACK) - .parameters(myParameter) - .build(); + .stackName(stackName) + .templateURL(location) + .roleARN(roleARN) + .onFailure(OnFailure.ROLLBACK) + .parameters(myParameter) + .build(); cfClient.createStack(stackRequest); DescribeStacksRequest stacksRequest = DescribeStacksRequest.builder() - .stackName(stackName) - .build(); + .stackName(stackName) + .build(); WaiterResponse waiterResponse = waiter.waitUntilStackCreateComplete(stacksRequest); waiterResponse.matched().response().ifPresent(System.out::println); diff --git a/javav2/example_code/cloudformation/src/main/java/com/example/cloudformation/DeleteStack.java b/javav2/example_code/cloudformation/src/main/java/com/example/cloudformation/DeleteStack.java index ed9156fcb99..197f927f9db 100644 --- a/javav2/example_code/cloudformation/src/main/java/com/example/cloudformation/DeleteStack.java +++ b/javav2/example_code/cloudformation/src/main/java/com/example/cloudformation/DeleteStack.java @@ -1,13 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[DeleteStack.java demonstrates how to delete an existing stack.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CloudFormation] - - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudformation; @@ -20,7 +12,8 @@ // snippet-end:[cf.java2.delete_stack.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,12 +24,12 @@ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - stackName - The name of the AWS CloudFormation stack.\s - """; + Where: + stackName - The name of the AWS CloudFormation stack.\s + """; if (args.length != 1) { System.out.println(usage); @@ -46,8 +39,8 @@ public static void main(String[] args) { String stackName = args[0]; Region region = Region.US_EAST_1; CloudFormationClient cfClient = CloudFormationClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteSpecificTemplate(cfClient, stackName); cfClient.close(); @@ -56,8 +49,8 @@ public static void main(String[] args) { public static void deleteSpecificTemplate(CloudFormationClient cfClient, String stackName) { try { DeleteStackRequest stackRequest = DeleteStackRequest.builder() - .stackName(stackName) - .build(); + .stackName(stackName) + .build(); cfClient.deleteStack(stackRequest); System.out.println("The AWS CloudFormation stack was successfully deleted!"); diff --git a/javav2/example_code/cloudformation/src/main/java/com/example/cloudformation/DescribeStacks.java b/javav2/example_code/cloudformation/src/main/java/com/example/cloudformation/DescribeStacks.java index 8107a296996..de54a676729 100644 --- a/javav2/example_code/cloudformation/src/main/java/com/example/cloudformation/DescribeStacks.java +++ b/javav2/example_code/cloudformation/src/main/java/com/example/cloudformation/DescribeStacks.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[DescribeStacks.java demonstrates how to obtain information about stacks.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CloudFormation] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudformation; @@ -21,7 +14,8 @@ // snippet-end:[cf.java2.get_stacks.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,12 +25,13 @@ public class DescribeStacks { public static void main(String[] args) { Region region = Region.US_WEST_2; CloudFormationClient cfClient = CloudFormationClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeAllStacks(cfClient); cfClient.close(); } + public static void describeAllStacks(CloudFormationClient cfClient) { try { DescribeStacksResponse stacksResponse = cfClient.describeStacks(); diff --git a/javav2/example_code/cloudformation/src/main/java/com/example/cloudformation/GetTemplate.java b/javav2/example_code/cloudformation/src/main/java/com/example/cloudformation/GetTemplate.java index 8f4e756d42f..b624eaa5228 100644 --- a/javav2/example_code/cloudformation/src/main/java/com/example/cloudformation/GetTemplate.java +++ b/javav2/example_code/cloudformation/src/main/java/com/example/cloudformation/GetTemplate.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[GetTemplate.java demonstrates how to retrieve a template.] -//snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CloudFormation] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudformation; @@ -20,7 +13,8 @@ // snippet-end:[cf.java2._template.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,12 +25,12 @@ public class GetTemplate { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - stackName - The name of the AWS CloudFormation stack.\s - """; + Where: + stackName - The name of the AWS CloudFormation stack.\s + """; if (args.length != 1) { System.out.println(usage); @@ -46,8 +40,8 @@ public static void main(String[] args) { String stackName = args[0]; Region region = Region.US_WEST_2; CloudFormationClient cfClient = CloudFormationClient.builder() - .region(region) - .build(); + .region(region) + .build(); getSpecificTemplate(cfClient, stackName); cfClient.close(); @@ -56,8 +50,8 @@ public static void main(String[] args) { public static void getSpecificTemplate(CloudFormationClient cfClient, String stackName) { try { GetTemplateRequest typeRequest = GetTemplateRequest.builder() - .stackName(stackName) - .build(); + .stackName(stackName) + .build(); GetTemplateResponse response = cfClient.getTemplate(typeRequest); String body = response.templateBody(); diff --git a/javav2/example_code/cloudformation/src/test/java/CloudFormationTest.java b/javav2/example_code/cloudformation/src/test/java/CloudFormationTest.java index da9b640ccdc..2f4247bef01 100644 --- a/javav2/example_code/cloudformation/src/test/java/CloudFormationTest.java +++ b/javav2/example_code/cloudformation/src/test/java/CloudFormationTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.cloudformation.*; import com.google.gson.Gson; @@ -21,7 +19,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class CloudFormationTest { - private static CloudFormationClient cfClient; + private static CloudFormationClient cfClient; private static String stackName = ""; private static String roleARN = ""; private static String location = ""; @@ -31,9 +29,9 @@ public class CloudFormationTest { @BeforeAll public static void setUp() { cfClient = CloudFormationClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -41,38 +39,41 @@ public static void setUp() { SecretValues values = gson.fromJson(json, SecretValues.class); stackName = values.getStackName(); roleARN = values.getRoleARN(); - location= values.getLocation(); - key= values.getKey(); - value= values.getValue(); - - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - try (InputStream input = CloudFormationTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - // Populate the data members required for all tests. - prop.load(input); - stackName = prop.getProperty("stackName"); - roleARN = prop.getProperty("roleARN"); - location = prop.getProperty("location"); - key = prop.getProperty("key"); - value = prop.getProperty("value"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + location = values.getLocation(); + key = values.getKey(); + value = values.getValue(); + + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * try (InputStream input = + * CloudFormationTest.class.getClassLoader().getResourceAsStream( + * "config.properties")) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * // Populate the data members required for all tests. + * prop.load(input); + * stackName = prop.getProperty("stackName"); + * roleARN = prop.getProperty("roleARN"); + * location = prop.getProperty("location"); + * key = prop.getProperty("key"); + * value = prop.getProperty("value"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @Tag("IntegrationTest") @Order(1) public void CreateStack() { - assertDoesNotThrow(() ->CreateStack.createCFStack(cfClient, stackName, roleARN, location, key, value)); + assertDoesNotThrow(() -> CreateStack.createCFStack(cfClient, stackName, roleARN, location, key, value)); System.out.println("Test 1 passed"); } @@ -80,7 +81,7 @@ public void CreateStack() { @Tag("IntegrationTest") @Order(2) public void DescribeStacks() { - assertDoesNotThrow(() ->DescribeStacks.describeAllStacks(cfClient)); + assertDoesNotThrow(() -> DescribeStacks.describeAllStacks(cfClient)); System.out.println("Test 2 passed"); } @@ -88,28 +89,28 @@ public void DescribeStacks() { @Tag("IntegrationTest") @Order(3) public void GetTemplate() { - assertDoesNotThrow(() ->GetTemplate.getSpecificTemplate(cfClient, stackName)); + assertDoesNotThrow(() -> GetTemplate.getSpecificTemplate(cfClient, stackName)); System.out.println("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void DeleteStack(){ - assertDoesNotThrow(() ->DeleteStack.deleteSpecificTemplate(cfClient, stackName)); + public void DeleteStack() { + assertDoesNotThrow(() -> DeleteStack.deleteSpecificTemplate(cfClient, stackName)); System.out.println("Test 4 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/cloudformation"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); diff --git a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateBucketPolicy.java b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateBucketPolicy.java index 504f6eed88d..e9577eb326a 100644 --- a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateBucketPolicy.java +++ b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateBucketPolicy.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[CreateBucketPolicy.java demonstrates how to use Amazon CloudFront to programmatically alter a policy file that allows access to an Amazon Simple Storage Service (Amazon S3) bucket. It also adds the policy to the S3 bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudFront] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.cloudfront; // snippet-start:[cloudfront.java2.createbucketpolicy.import] @@ -27,7 +22,7 @@ public class CreateBucketPolicy { final private static Logger logger = LoggerFactory.getLogger(CreateBucketPolicy.class); - public static String createBucketPolicy(String bucketName, String accountId , String distributionId) { + public static String createBucketPolicy(String bucketName, String accountId, String distributionId) { URL resource = CreateBucketPolicy.class.getClassLoader().getResource("bucketAccessPolicy.json"); String fileName = resource.getPath(); @@ -42,7 +37,7 @@ public static String createBucketPolicy(String bucketName, String accountId , St firstObject.put("Resource", "arn:aws:s3:::" + bucketName + "/*"); JSONObject condition = (JSONObject) firstObject.get("Condition"); JSONObject stringEquals = (JSONObject) condition.get("StringEquals"); - stringEquals.put("AWS:SourceArn", "arn:aws:cloudfront::"+ accountId + ":distribution/" + distributionId); + stringEquals.put("AWS:SourceArn", "arn:aws:cloudfront::" + accountId + ":distribution/" + distributionId); replacedPolicy = root.toJSONString(); } catch (IOException | ParseException e) { @@ -57,9 +52,9 @@ public static void uploadBucketPolicy(S3Client s3Client, String bucketName, Stri .bucket(bucketName) .policy(bucketAccessPolicy)); - if (response.sdkHttpResponse().isSuccessful() ){ + if (response.sdkHttpResponse().isSuccessful()) { logger.info("Bucket access policy successfully uploaded"); } } -// snippet-end:[cloudfront.java2.createbucketpolicy.main] + // snippet-end:[cloudfront.java2.createbucketpolicy.main] } diff --git a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateCannedPolicyRequest.java b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateCannedPolicyRequest.java index c7d7482956c..b02537f11d1 100644 --- a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateCannedPolicyRequest.java +++ b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateCannedPolicyRequest.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[CreateCannedPolicyRequest.java demonstrates how to use the CannedSignerRequest class to specify the required properties to sign URLs or cookies to access Amazon CloudFront.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudFront] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.cloudfront; // snippet-start:[cloudfront.java2.createcannedpolicyrequest.import] @@ -21,8 +16,9 @@ // snippet-start:[cloudfront.java2.createcannedpolicyrequest.main] public class CreateCannedPolicyRequest { - public static CannedSignerRequest createRequestForCannedPolicy(String distributionDomainName, String fileNameToUpload, - String privateKeyFullPath, String publicKeyId) throws Exception{ + public static CannedSignerRequest createRequestForCannedPolicy(String distributionDomainName, + String fileNameToUpload, + String privateKeyFullPath, String publicKeyId) throws Exception { String protocol = "https"; String resourcePath = "/" + fileNameToUpload; diff --git a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateCustomPolicyRequest.java b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateCustomPolicyRequest.java index 690abfefc39..a2ed63f1b0e 100644 --- a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateCustomPolicyRequest.java +++ b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateCustomPolicyRequest.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[CreateCustomPolicyRequest.java demonstrates how to use the CustomSignerRequest class to specify the required properties to sign URLs or cookies to access Amazon CloudFront.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudFront] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.cloudfront; // snippet-start:[cloudfront.java2.createcustompolicyrequest.import] @@ -21,8 +16,9 @@ // snippet-start:[cloudfront.java2.createcustompolicyrequest.main] public class CreateCustomPolicyRequest { - public static CustomSignerRequest createRequestForCustomPolicy(String distributionDomainName, String fileNameToUpload, - String privateKeyFullPath, String publicKeyId) throws Exception { + public static CustomSignerRequest createRequestForCustomPolicy(String distributionDomainName, + String fileNameToUpload, + String privateKeyFullPath, String publicKeyId) throws Exception { String protocol = "https"; String resourcePath = "/" + fileNameToUpload; @@ -37,8 +33,8 @@ public static CustomSignerRequest createRequestForCustomPolicy(String distributi .privateKey(path) .keyPairId(publicKeyId) .expirationDate(expireDate) - .activeDate(activeDate) // Optional. - //.ipRange("192.168.0.1/24") // Optional. + .activeDate(activeDate) // Optional. + // .ipRange("192.168.0.1/24") // Optional. .build(); } } diff --git a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateDistribution.java b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateDistribution.java index f3e407f63d0..78866e5edd0 100644 --- a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateDistribution.java +++ b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateDistribution.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[CreateDistribution.java demonstrates how to create an Amazon CloudFront distribution that requires signed URLs/cookies to access resources.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudFront] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.cloudfront; // snippet-start:[cloudfront.java2.createdistribution.import] @@ -29,79 +24,90 @@ // snippet-start:[cloudfront.java2.createdistribution.main] public class CreateDistribution { - private static final Logger logger = LoggerFactory.getLogger(CreateDistribution.class); + private static final Logger logger = LoggerFactory.getLogger(CreateDistribution.class); - public static Distribution createDistribution(CloudFrontClient cloudFrontClient, S3Client s3Client, - final String bucketName, final String keyGroupId, final String originAccessControlId) { + public static Distribution createDistribution(CloudFrontClient cloudFrontClient, S3Client s3Client, + final String bucketName, final String keyGroupId, final String originAccessControlId) { - final String region = s3Client.headBucket(b -> b.bucket(bucketName)).sdkHttpResponse().headers().get("x-amz-bucket-region").get(0); - final String originDomain = bucketName + ".s3." + region + ".amazonaws.com"; - String originId = originDomain; // Use the originDomain value for the originId. + final String region = s3Client.headBucket(b -> b.bucket(bucketName)).sdkHttpResponse().headers() + .get("x-amz-bucket-region").get(0); + final String originDomain = bucketName + ".s3." + region + ".amazonaws.com"; + String originId = originDomain; // Use the originDomain value for the originId. - // The service API requires some deprecated methods, such as DefaultCacheBehavior.Builder#minTTL and #forwardedValue. - CreateDistributionResponse createDistResponse = cloudFrontClient.createDistribution(builder -> builder - .distributionConfig(b1 -> b1 - .origins(b2 -> b2 - .quantity(1) - .items(b3 -> b3 - .domainName(originDomain) - .id(originId) - .s3OriginConfig(builder4 -> builder4.originAccessIdentity("")) - .originAccessControlId(originAccessControlId))) - .defaultCacheBehavior(b2 -> b2 - .viewerProtocolPolicy(ViewerProtocolPolicy.ALLOW_ALL) - .targetOriginId(originId) - .minTTL(200L) - .forwardedValues(b5 -> b5 - .cookies(cp -> cp - .forward(ItemSelection.NONE)) - .queryString(true)) - .trustedKeyGroups(b3 -> b3 - .quantity(1) - .items(keyGroupId) - .enabled(true)) - .allowedMethods(b4 -> b4 - .quantity(2) - .items(Method.HEAD, Method.GET) - .cachedMethods(b5 -> b5 - .quantity(2) - .items(Method.HEAD, Method.GET)))) - .cacheBehaviors(b -> b - .quantity(1) - .items(b2 -> b2 - .pathPattern("/index.html") - .viewerProtocolPolicy(ViewerProtocolPolicy.ALLOW_ALL) - .targetOriginId(originId) - .trustedKeyGroups(b3 -> b3 - .quantity(1) - .items(keyGroupId) - .enabled(true)) - .minTTL(200L) - .forwardedValues(b4 -> b4 - .cookies(cp -> cp - .forward(ItemSelection.NONE)) - .queryString(true)) - .allowedMethods(b5 -> b5. - quantity(2). - items(Method.HEAD, Method.GET) - .cachedMethods(b6 -> b6 - .quantity(2) - .items(Method.HEAD, Method.GET))))) - .enabled(true) - .comment("Distribution built with java") - .callerReference(Instant.now().toString()) - )); + // The service API requires some deprecated methods, such as + // DefaultCacheBehavior.Builder#minTTL and #forwardedValue. + CreateDistributionResponse createDistResponse = cloudFrontClient.createDistribution(builder -> builder + .distributionConfig(b1 -> b1 + .origins(b2 -> b2 + .quantity(1) + .items(b3 -> b3 + .domainName(originDomain) + .id(originId) + .s3OriginConfig(builder4 -> builder4 + .originAccessIdentity( + "")) + .originAccessControlId( + originAccessControlId))) + .defaultCacheBehavior(b2 -> b2 + .viewerProtocolPolicy(ViewerProtocolPolicy.ALLOW_ALL) + .targetOriginId(originId) + .minTTL(200L) + .forwardedValues(b5 -> b5 + .cookies(cp -> cp + .forward(ItemSelection.NONE)) + .queryString(true)) + .trustedKeyGroups(b3 -> b3 + .quantity(1) + .items(keyGroupId) + .enabled(true)) + .allowedMethods(b4 -> b4 + .quantity(2) + .items(Method.HEAD, Method.GET) + .cachedMethods(b5 -> b5 + .quantity(2) + .items(Method.HEAD, + Method.GET)))) + .cacheBehaviors(b -> b + .quantity(1) + .items(b2 -> b2 + .pathPattern("/index.html") + .viewerProtocolPolicy( + ViewerProtocolPolicy.ALLOW_ALL) + .targetOriginId(originId) + .trustedKeyGroups(b3 -> b3 + .quantity(1) + .items(keyGroupId) + .enabled(true)) + .minTTL(200L) + .forwardedValues(b4 -> b4 + .cookies(cp -> cp + .forward(ItemSelection.NONE)) + .queryString(true)) + .allowedMethods(b5 -> b5.quantity(2) + .items(Method.HEAD, + Method.GET) + .cachedMethods(b6 -> b6 + .quantity(2) + .items(Method.HEAD, + Method.GET))))) + .enabled(true) + .comment("Distribution built with java") + .callerReference(Instant.now().toString()))); - final Distribution distribution = createDistResponse.distribution(); - logger.info("Distribution created. DomainName: [{}] Id: [{}]", distribution.domainName(), distribution.id()); - logger.info("Waiting for distribution to be deployed ..."); - try (CloudFrontWaiter cfWaiter = CloudFrontWaiter.builder().client(cloudFrontClient).build()) { - ResponseOrException responseOrException = - cfWaiter.waitUntilDistributionDeployed(builder -> builder.id(distribution.id())).matched(); - responseOrException.response().orElseThrow(() -> new RuntimeException("Distribution not created")); - logger.info("Distribution deployed. DomainName: [{}] Id: [{}]", distribution.domainName(), distribution.id()); + final Distribution distribution = createDistResponse.distribution(); + logger.info("Distribution created. DomainName: [{}] Id: [{}]", distribution.domainName(), + distribution.id()); + logger.info("Waiting for distribution to be deployed ..."); + try (CloudFrontWaiter cfWaiter = CloudFrontWaiter.builder().client(cloudFrontClient).build()) { + ResponseOrException responseOrException = cfWaiter + .waitUntilDistributionDeployed(builder -> builder.id(distribution.id())) + .matched(); + responseOrException.response() + .orElseThrow(() -> new RuntimeException("Distribution not created")); + logger.info("Distribution deployed. DomainName: [{}] Id: [{}]", distribution.domainName(), + distribution.id()); + } + return distribution; } - return distribution; - } } // snippet-end:[cloudfront.java2.createdistribution.main] \ No newline at end of file diff --git a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateFunction.java b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateFunction.java index f040d29e940..1970a8ff9f4 100644 --- a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateFunction.java +++ b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateFunction.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[CreateFunction.java demonstrates how to create a CloudFront function.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon CloudFront] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudfront; @@ -23,7 +17,8 @@ // snippet-end:[cloudfront.java2.function.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -34,27 +29,27 @@ public class CreateFunction { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - functionName - The name of the function to create.\s - filePath - The path to a file that contains the application logic for the function.\s - """; + Where: + functionName - The name of the function to create.\s + filePath - The path to a file that contains the application logic for the function.\s + """; - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } String functionName = args[0]; - String filePath = args[1] ; + String filePath = args[1]; CloudFrontClient cloudFrontClient = CloudFrontClient.builder() - .region(Region.AWS_GLOBAL) - .build(); + .region(Region.AWS_GLOBAL) + .build(); String funArn = createNewFunction(cloudFrontClient, functionName, filePath); - System.out.println("The function ARN is "+funArn); + System.out.println("The function ARN is " + funArn); cloudFrontClient.close(); } @@ -64,20 +59,20 @@ public static String createNewFunction(CloudFrontClient cloudFrontClient, String SdkBytes functionCode = SdkBytes.fromInputStream(fileIs); FunctionConfig config = FunctionConfig.builder() - .comment("Created by using the CloudFront Java API") - .runtime(FunctionRuntime.CLOUDFRONT_JS_1_0) - .build(); + .comment("Created by using the CloudFront Java API") + .runtime(FunctionRuntime.CLOUDFRONT_JS_1_0) + .build(); CreateFunctionRequest functionRequest = CreateFunctionRequest.builder() - .name(functionName) - .functionCode(functionCode) - .functionConfig(config) - .build(); + .name(functionName) + .functionCode(functionCode) + .functionConfig(config) + .build(); CreateFunctionResponse response = cloudFrontClient.createFunction(functionRequest); return response.functionSummary().functionMetadata().functionARN(); - } catch (CloudFrontException e){ + } catch (CloudFrontException e) { System.err.println(e.getMessage()); System.exit(1); } @@ -85,4 +80,3 @@ public static String createNewFunction(CloudFrontClient cloudFrontClient, String } } // snippet-end:[cloudfront.java2.function.main] - diff --git a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateKeyGroup.java b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateKeyGroup.java index 21347327e26..0bb91bb57f6 100644 --- a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateKeyGroup.java +++ b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateKeyGroup.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[CreateKeyGroup.java demonstrates how to create a trusted key group for Amazon CloudFront that is used to verify signed URLs/cookies.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudFront] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.cloudfront; // snippet-start:[cloudfront.java2.createkeygroup.import] @@ -21,10 +16,9 @@ public class CreateKeyGroup { private static final Logger logger = LoggerFactory.getLogger(CreateKeyGroup.class); public static String createKeyGroup(CloudFrontClient cloudFrontClient, String publicKeyId) { - String keyGroupId = cloudFrontClient.createKeyGroup(b -> b. - keyGroupConfig(c -> c - .items(publicKeyId) - .name("JavaKeyGroup"+ UUID.randomUUID()))) + String keyGroupId = cloudFrontClient.createKeyGroup(b -> b.keyGroupConfig(c -> c + .items(publicKeyId) + .name("JavaKeyGroup" + UUID.randomUUID()))) .keyGroup().id(); logger.info("KeyGroup created with ID: [{}]", keyGroupId); return keyGroupId; diff --git a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateOriginAccessControl.java b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateOriginAccessControl.java index 93ba17f9950..0f076232cf3 100644 --- a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateOriginAccessControl.java +++ b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreateOriginAccessControl.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[CreateOriginAccessControl.java demonstrates how to have Amazon CloudFront access Amazon Simple Storage Service (Amazon S3) resources by using signed requests.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudFront] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.cloudfront; // snippet-start:[cloudfront.java2.createoriginaccesscontrol.import] @@ -22,6 +17,7 @@ // snippet-start:[cloudfront.java2.createoriginaccesscontrol.main] public class CreateOriginAccessControl { private static final Logger logger = LoggerFactory.getLogger(CreateOriginAccessControl.class); + public static String createOriginAccessControl(CloudFrontClient cloudFrontClient) { CreateOriginAccessControlResponse response = cloudFrontClient.createOriginAccessControl(b -> b .originAccessControlConfig(o -> o diff --git a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreatePublicKey.java b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreatePublicKey.java index 46c60a1f7c5..8a9026ce006 100644 --- a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreatePublicKey.java +++ b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/CreatePublicKey.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[CreatePublicKey.java demonstrates how to read a public key file and upload it to Amazon CloudFront.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudFront] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.cloudfront; // snippet-start:[cloudfront.java2.createpublickey.import] @@ -27,8 +22,8 @@ public class CreatePublicKey { public static String createPublicKey(CloudFrontClient cloudFrontClient, String publicKeyFileName) { try (InputStream is = CreatePublicKey.class.getClassLoader().getResourceAsStream(publicKeyFileName)) { String publicKeyString = IoUtils.toUtf8String(is); - CreatePublicKeyResponse createPublicKeyResponse = cloudFrontClient.createPublicKey(b -> b. - publicKeyConfig(c -> c + CreatePublicKeyResponse createPublicKeyResponse = cloudFrontClient + .createPublicKey(b -> b.publicKeyConfig(c -> c .name("JavaCreatedPublicKey" + UUID.randomUUID()) .encodedKey(publicKeyString) .callerReference(UUID.randomUUID().toString()))); diff --git a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/DeleteDistribution.java b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/DeleteDistribution.java index b0520e9e58b..dec7c667e52 100644 --- a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/DeleteDistribution.java +++ b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/DeleteDistribution.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[DeleteDistribution.java demonstrates how to disable an Amazon CloudFront distribution by updating the distribution. After the change is deployed, the code shows how to delete the distribution.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudFront] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.cloudfront; // snippet-start:[cloudfront.java2.deletedistribution.import] @@ -21,53 +16,55 @@ // snippet-start:[cloudfront.java2.deletedistribution.main] public class DeleteDistribution { - private static final Logger logger = LoggerFactory.getLogger(DeleteDistribution.class); + private static final Logger logger = LoggerFactory.getLogger(DeleteDistribution.class); - public static void deleteDistribution(final CloudFrontClient cloudFrontClient, final String distributionId) { - // First, disable the distribution by updating it. - GetDistributionResponse response = cloudFrontClient. - getDistribution(b -> b - .id(distributionId)); - String etag = response.eTag(); - DistributionConfig distConfig = response.distribution().distributionConfig(); + public static void deleteDistribution(final CloudFrontClient cloudFrontClient, final String distributionId) { + // First, disable the distribution by updating it. + GetDistributionResponse response = cloudFrontClient.getDistribution(b -> b + .id(distributionId)); + String etag = response.eTag(); + DistributionConfig distConfig = response.distribution().distributionConfig(); - cloudFrontClient.updateDistribution(builder -> builder - .id(distributionId) - .distributionConfig(builder1 -> builder1 - .cacheBehaviors(distConfig.cacheBehaviors()) - .defaultCacheBehavior(distConfig.defaultCacheBehavior()) - .enabled(false) - .origins(distConfig.origins()) - .comment(distConfig.comment()) - .callerReference(distConfig.callerReference()) - .defaultCacheBehavior(distConfig.defaultCacheBehavior()) - .priceClass(distConfig.priceClass()) - .aliases(distConfig.aliases()) - .logging(distConfig.logging()) - .defaultRootObject(distConfig.defaultRootObject()) - .customErrorResponses(distConfig.customErrorResponses()) - .httpVersion(distConfig.httpVersion()) - .isIPV6Enabled(distConfig.isIPV6Enabled()) - .restrictions(distConfig.restrictions()) - .viewerCertificate(distConfig.viewerCertificate()) - .webACLId(distConfig.webACLId()) - .originGroups(distConfig.originGroups())) - .ifMatch(etag)); + cloudFrontClient.updateDistribution(builder -> builder + .id(distributionId) + .distributionConfig(builder1 -> builder1 + .cacheBehaviors(distConfig.cacheBehaviors()) + .defaultCacheBehavior(distConfig.defaultCacheBehavior()) + .enabled(false) + .origins(distConfig.origins()) + .comment(distConfig.comment()) + .callerReference(distConfig.callerReference()) + .defaultCacheBehavior(distConfig.defaultCacheBehavior()) + .priceClass(distConfig.priceClass()) + .aliases(distConfig.aliases()) + .logging(distConfig.logging()) + .defaultRootObject(distConfig.defaultRootObject()) + .customErrorResponses(distConfig.customErrorResponses()) + .httpVersion(distConfig.httpVersion()) + .isIPV6Enabled(distConfig.isIPV6Enabled()) + .restrictions(distConfig.restrictions()) + .viewerCertificate(distConfig.viewerCertificate()) + .webACLId(distConfig.webACLId()) + .originGroups(distConfig.originGroups())) + .ifMatch(etag)); - logger.info("Distribution [{}] is DISABLED, waiting for deployment before deleting ...", distributionId); - GetDistributionResponse distributionResponse; - try (CloudFrontWaiter cfWaiter = CloudFrontWaiter.builder().client(cloudFrontClient).build()) { - ResponseOrException responseOrException = - cfWaiter.waitUntilDistributionDeployed(builder -> builder.id(distributionId)).matched(); - distributionResponse = responseOrException.response().orElseThrow(() -> new RuntimeException("Could not disable distribution")); - } + logger.info("Distribution [{}] is DISABLED, waiting for deployment before deleting ...", + distributionId); + GetDistributionResponse distributionResponse; + try (CloudFrontWaiter cfWaiter = CloudFrontWaiter.builder().client(cloudFrontClient).build()) { + ResponseOrException responseOrException = cfWaiter + .waitUntilDistributionDeployed(builder -> builder.id(distributionId)).matched(); + distributionResponse = responseOrException.response() + .orElseThrow(() -> new RuntimeException("Could not disable distribution")); + } - DeleteDistributionResponse deleteDistributionResponse = cloudFrontClient.deleteDistribution(builder -> builder - .id(distributionId) - .ifMatch(distributionResponse.eTag())); - if ( deleteDistributionResponse.sdkHttpResponse().isSuccessful() ){ - logger.info("Distribution [{}] DELETED", distributionId); + DeleteDistributionResponse deleteDistributionResponse = cloudFrontClient + .deleteDistribution(builder -> builder + .id(distributionId) + .ifMatch(distributionResponse.eTag())); + if (deleteDistributionResponse.sdkHttpResponse().isSuccessful()) { + logger.info("Distribution [{}] DELETED", distributionId); + } } - } } // snippet-end:[cloudfront.java2.deletedistribution.main] diff --git a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/DeleteFunction.java b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/DeleteFunction.java index f4b008de8ff..bbf394b9b35 100644 --- a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/DeleteFunction.java +++ b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/DeleteFunction.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[DeleteFunction.java demonstrates how to delete a CloudFront function.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon CloudFront] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudfront; @@ -17,7 +12,8 @@ // snippet-end:[cloudfront.java2.del_function.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,13 +24,13 @@ public class DeleteFunction { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - functionName - The name of the function to delete.\s - ifMatchVal - The current version (ETag value) of the function that you are deleting, which you can get using DescribeFunction.\s - """; + Where: + functionName - The name of the function to delete.\s + ifMatchVal - The current version (ETag value) of the function that you are deleting, which you can get using DescribeFunction.\s + """; if (args.length != 2) { System.out.println(usage); @@ -44,19 +40,20 @@ public static void main(String[] args) { String functionName = args[0]; String ifMatchVal = args[1]; CloudFrontClient cloudFrontClient = CloudFrontClient.builder() - .region(Region.AWS_GLOBAL) - .build(); + .region(Region.AWS_GLOBAL) + .build(); deleteSpecificFunction(cloudFrontClient, functionName, ifMatchVal); cloudFrontClient.close(); } - public static void deleteSpecificFunction(CloudFrontClient cloudFrontClient, String functionName, String ifMatchVal) { + public static void deleteSpecificFunction(CloudFrontClient cloudFrontClient, String functionName, + String ifMatchVal) { try { DeleteFunctionRequest functionRequest = DeleteFunctionRequest.builder() - .name(functionName) - .ifMatch(ifMatchVal) - .build(); + .name(functionName) + .ifMatch(ifMatchVal) + .build(); cloudFrontClient.deleteFunction(functionRequest); System.out.println(functionName + " was successfully deleted."); diff --git a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/DeleteSigningResources.java b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/DeleteSigningResources.java index 0bf31fe2c65..3aad2903796 100644 --- a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/DeleteSigningResources.java +++ b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/DeleteSigningResources.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[DeleteSigningResources.java demonstrates how to delete ancillary resources used by an Amazon CloudFront distribution. Do this after deleting the distribution.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudFront] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.cloudfront; // snippet-start:[cloudfront.java2.deletedistributionresources.import] @@ -24,35 +19,37 @@ public class DeleteSigningResources { private static final Logger logger = LoggerFactory.getLogger(DeleteSigningResources.class); - public static void deleteOriginAccessControl(final CloudFrontClient cloudFrontClient, final String originAccessControlId){ - GetOriginAccessControlResponse getResponse = cloudFrontClient.getOriginAccessControl(b -> b.id(originAccessControlId)); + public static void deleteOriginAccessControl(final CloudFrontClient cloudFrontClient, + final String originAccessControlId) { + GetOriginAccessControlResponse getResponse = cloudFrontClient + .getOriginAccessControl(b -> b.id(originAccessControlId)); DeleteOriginAccessControlResponse deleteResponse = cloudFrontClient.deleteOriginAccessControl(builder -> builder .id(originAccessControlId) .ifMatch(getResponse.eTag())); - if ( deleteResponse.sdkHttpResponse().isSuccessful() ){ + if (deleteResponse.sdkHttpResponse().isSuccessful()) { logger.info("Successfully deleted Origin Access Control [{}]", originAccessControlId); } } - public static void deleteKeyGroup(final CloudFrontClient cloudFrontClient, final String keyGroupId){ + public static void deleteKeyGroup(final CloudFrontClient cloudFrontClient, final String keyGroupId) { GetKeyGroupResponse getResponse = cloudFrontClient.getKeyGroup(b -> b.id(keyGroupId)); DeleteKeyGroupResponse deleteResponse = cloudFrontClient.deleteKeyGroup(builder -> builder .id(keyGroupId) .ifMatch(getResponse.eTag())); - if ( deleteResponse.sdkHttpResponse().isSuccessful() ){ + if (deleteResponse.sdkHttpResponse().isSuccessful()) { logger.info("Successfully deleted Key Group [{}]", keyGroupId); } } - public static void deletePublicKey(final CloudFrontClient cloudFrontClient, final String publicKeyId){ + public static void deletePublicKey(final CloudFrontClient cloudFrontClient, final String publicKeyId) { GetPublicKeyResponse getResponse = cloudFrontClient.getPublicKey(b -> b.id(publicKeyId)); DeletePublicKeyResponse deleteResponse = cloudFrontClient.deletePublicKey(builder -> builder .id(publicKeyId) .ifMatch(getResponse.eTag())); - if (deleteResponse.sdkHttpResponse().isSuccessful()){ + if (deleteResponse.sdkHttpResponse().isSuccessful()) { logger.info("Successfully deleted Public Key [{}]", publicKeyId); } } diff --git a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/DescribeFunction.java b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/DescribeFunction.java index 476422adac1..e57f40aa602 100644 --- a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/DescribeFunction.java +++ b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/DescribeFunction.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeFunction.java demonstrates how to get configuration information and metadata about a CloudFront function.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon CloudFront] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudfront; @@ -20,7 +14,8 @@ // snippet-end:[cloudfront.java2.des_function.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,39 +26,39 @@ public class DescribeFunction { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - functionName - The name of the function to describe.\s - """; + Where: + functionName - The name of the function to describe.\s + """; - if (args.length != 1) { - System.out.println(usage); - System.exit(1); + if (args.length != 1) { + System.out.println(usage); + System.exit(1); } String functionName = args[0]; CloudFrontClient cloudFrontClient = CloudFrontClient.builder() - .region(Region.AWS_GLOBAL) - .build(); + .region(Region.AWS_GLOBAL) + .build(); String eTagVal = describeFunction(cloudFrontClient, functionName); - System.out.println(eTagVal +" is the eTag value."); + System.out.println(eTagVal + " is the eTag value."); cloudFrontClient.close(); } public static String describeFunction(CloudFrontClient cloudFrontClient, String functionName) { try { DescribeFunctionRequest functionRequest = DescribeFunctionRequest.builder() - .name(functionName) - .stage(FunctionStage.DEVELOPMENT) - .build(); + .name(functionName) + .stage(FunctionStage.DEVELOPMENT) + .build(); DescribeFunctionResponse functionResponse = cloudFrontClient.describeFunction(functionRequest); return functionResponse.eTag(); - } catch (CloudFrontException e){ + } catch (CloudFrontException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } diff --git a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/GetDistributions.java b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/GetDistributions.java index 05f5c03de94..4d570650d5f 100644 --- a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/GetDistributions.java +++ b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/GetDistributions.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[GetDistrubutions.java demonstrates how to get information about a distribution.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon CloudFront] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudfront; @@ -20,7 +15,8 @@ // snippet-end:[cloudfront.java2.dis.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,24 +25,24 @@ public class GetDistributions { public static void main(String[] args) { CloudFrontClient cloudFrontClient = CloudFrontClient.builder() - .region(Region.AWS_GLOBAL) - .build(); + .region(Region.AWS_GLOBAL) + .build(); getCFDistributions(cloudFrontClient); cloudFrontClient.close(); } public static void getCFDistributions(CloudFrontClient cloudFrontClient) { - try { - ListDistributionsResponse response = cloudFrontClient.listDistributions(); - DistributionList list = response.distributionList(); - List dists = list.items(); - dists.forEach(dist -> System.out.println("The Distribution ARN is "+dist.arn())); + try { + ListDistributionsResponse response = cloudFrontClient.listDistributions(); + DistributionList list = response.distributionList(); + List dists = list.items(); + dists.forEach(dist -> System.out.println("The Distribution ARN is " + dist.arn())); - } catch (CloudFrontException e){ - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } + } catch (CloudFrontException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } } } // snippet-end:[cloudfront.java2.dis.main] diff --git a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/ListFunctions.java b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/ListFunctions.java index 87fc8677e63..58df0683793 100644 --- a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/ListFunctions.java +++ b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/ListFunctions.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[ListFunctions.java demonstrates how to list CloudFront functions.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon CloudFront] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudfront; @@ -22,7 +17,8 @@ // snippet-end:[cloudfront.java2.list.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,32 +27,32 @@ public class ListFunctions { public static void main(String[] args) { CloudFrontClient cloudFrontClient = CloudFrontClient.builder() - .region(Region.AWS_GLOBAL) - .build(); + .region(Region.AWS_GLOBAL) + .build(); listAllFunctions(cloudFrontClient); cloudFrontClient.close(); } - public static void listAllFunctions( CloudFrontClient cloudFrontClient) { + public static void listAllFunctions(CloudFrontClient cloudFrontClient) { try { ListFunctionsRequest functionsRequest = ListFunctionsRequest.builder() - .stage(FunctionStage.DEVELOPMENT) - .maxItems("10") - .build(); + .stage(FunctionStage.DEVELOPMENT) + .maxItems("10") + .build(); ListFunctionsResponse response = cloudFrontClient.listFunctions(functionsRequest); FunctionList allFunctions = response.functionList(); List functions = allFunctions.items(); - for (FunctionSummary funSummary: functions) { - System.out.println("Function name is "+funSummary.name()); - System.out.println("Function runtime is "+funSummary.functionConfig().runtime().toString()); + for (FunctionSummary funSummary : functions) { + System.out.println("Function name is " + funSummary.name()); + System.out.println("Function runtime is " + funSummary.functionConfig().runtime().toString()); } - } catch (CloudFrontException e){ - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } + } catch (CloudFrontException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } } } // snippet-end:[cloudfront.java2.list.main] \ No newline at end of file diff --git a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/ModifyDistribution.java b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/ModifyDistribution.java index 53a6233d6da..a2da30fb63a 100644 --- a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/ModifyDistribution.java +++ b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/ModifyDistribution.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[ModifyDistribution.java demonstrates how to modify a CloudFront distribution.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon CloudFront] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudfront; @@ -22,7 +16,8 @@ // snippet-end:[cloudfront.java2.mod.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,22 +27,22 @@ public class ModifyDistribution { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - id - the id value of the distribution.\s - """; + Where: + id - the id value of the distribution.\s + """; if (args.length != 1) { - System.out.println(usage); - System.exit(1); + System.out.println(usage); + System.exit(1); } String id = args[0]; CloudFrontClient cloudFrontClient = CloudFrontClient.builder() - .region(Region.AWS_GLOBAL) - .build(); + .region(Region.AWS_GLOBAL) + .build(); modDistribution(cloudFrontClient, id); cloudFrontClient.close(); @@ -57,46 +52,46 @@ public static void modDistribution(CloudFrontClient cloudFrontClient, String idV try { // Get the Distribution to modify. GetDistributionRequest disRequest = GetDistributionRequest.builder() - .id(idVal) - .build(); + .id(idVal) + .build(); GetDistributionResponse response = cloudFrontClient.getDistribution(disRequest); Distribution disObject = response.distribution(); DistributionConfig config = disObject.distributionConfig(); - // Create a new DistributionConfig object and add new values to comment and aliases + // Create a new DistributionConfig object and add new values to comment and + // aliases DistributionConfig config1 = DistributionConfig.builder() - .aliases(config.aliases()) // You can pass in new values here - .comment("New Comment") - .cacheBehaviors(config.cacheBehaviors()) - .priceClass(config.priceClass()) - .defaultCacheBehavior(config.defaultCacheBehavior()) - .enabled(config.enabled()) - .callerReference(config.callerReference()) - .logging(config.logging()) - .originGroups(config.originGroups()) - .origins(config.origins()) - .restrictions(config.restrictions()) - .defaultRootObject(config.defaultRootObject()) - .webACLId(config.webACLId()) - .httpVersion(config.httpVersion()) - .viewerCertificate(config.viewerCertificate()) - .customErrorResponses(config.customErrorResponses()) - .build(); + .aliases(config.aliases()) // You can pass in new values here + .comment("New Comment") + .cacheBehaviors(config.cacheBehaviors()) + .priceClass(config.priceClass()) + .defaultCacheBehavior(config.defaultCacheBehavior()) + .enabled(config.enabled()) + .callerReference(config.callerReference()) + .logging(config.logging()) + .originGroups(config.originGroups()) + .origins(config.origins()) + .restrictions(config.restrictions()) + .defaultRootObject(config.defaultRootObject()) + .webACLId(config.webACLId()) + .httpVersion(config.httpVersion()) + .viewerCertificate(config.viewerCertificate()) + .customErrorResponses(config.customErrorResponses()) + .build(); UpdateDistributionRequest updateDistributionRequest = UpdateDistributionRequest.builder() - .distributionConfig(config1) - .id(disObject.id()) - .ifMatch(response.eTag()) - .build(); + .distributionConfig(config1) + .id(disObject.id()) + .ifMatch(response.eTag()) + .build(); cloudFrontClient.updateDistribution(updateDistributionRequest); - } catch (CloudFrontException e){ + } catch (CloudFrontException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } // snippet-end:[cloudfront.java2.mod.main] - diff --git a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/SigningUtilities.java b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/SigningUtilities.java index 850817a316c..d33c89da78a 100644 --- a/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/SigningUtilities.java +++ b/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/SigningUtilities.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[SigningUtilities.java demonstrates sign URLs and generate signed cookies to access restricted content in Amazon CloudFront.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudFront] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.cloudfront; // snippet-start:[cloudfront.java2.signingutilities.import] @@ -24,20 +19,21 @@ public class SigningUtilities { private static final Logger logger = LoggerFactory.getLogger(SigningUtilities.class); private static final CloudFrontUtilities cloudFrontUtilities = CloudFrontUtilities.create(); - public static SignedUrl signUrlForCannedPolicy(CannedSignerRequest cannedSignerRequest){ + public static SignedUrl signUrlForCannedPolicy(CannedSignerRequest cannedSignerRequest) { SignedUrl signedUrl = cloudFrontUtilities.getSignedUrlWithCannedPolicy(cannedSignerRequest); logger.info("Signed URL: [{}]", signedUrl.url()); return signedUrl; } - public static SignedUrl signUrlForCustomPolicy(CustomSignerRequest customSignerRequest){ + public static SignedUrl signUrlForCustomPolicy(CustomSignerRequest customSignerRequest) { SignedUrl signedUrl = cloudFrontUtilities.getSignedUrlWithCustomPolicy(customSignerRequest); logger.info("Signed URL: [{}]", signedUrl.url()); return signedUrl; } - public static CookiesForCannedPolicy getCookiesForCannedPolicy(CannedSignerRequest cannedSignerRequest){ - CookiesForCannedPolicy cookiesForCannedPolicy = cloudFrontUtilities.getCookiesForCannedPolicy(cannedSignerRequest); + public static CookiesForCannedPolicy getCookiesForCannedPolicy(CannedSignerRequest cannedSignerRequest) { + CookiesForCannedPolicy cookiesForCannedPolicy = cloudFrontUtilities + .getCookiesForCannedPolicy(cannedSignerRequest); logger.info("Cookie EXPIRES header [{}]", cookiesForCannedPolicy.expiresHeaderValue()); logger.info("Cookie KEYPAIR header [{}]", cookiesForCannedPolicy.keyPairIdHeaderValue()); logger.info("Cookie SIGNATURE header [{}]", cookiesForCannedPolicy.signatureHeaderValue()); @@ -45,7 +41,8 @@ public static CookiesForCannedPolicy getCookiesForCannedPolicy(CannedSignerReque } public static CookiesForCustomPolicy getCookiesForCustomPolicy(CustomSignerRequest customSignerRequest) { - CookiesForCustomPolicy cookiesForCustomPolicy = cloudFrontUtilities.getCookiesForCustomPolicy(customSignerRequest); + CookiesForCustomPolicy cookiesForCustomPolicy = cloudFrontUtilities + .getCookiesForCustomPolicy(customSignerRequest); logger.info("Cookie POLICY header [{}]", cookiesForCustomPolicy.policyHeaderValue()); logger.info("Cookie KEYPAIR header [{}]", cookiesForCustomPolicy.keyPairIdHeaderValue()); logger.info("Cookie SIGNATURE header [{}]", cookiesForCustomPolicy.signatureHeaderValue()); diff --git a/javav2/example_code/cloudfront/src/main/resources/CF_function.js b/javav2/example_code/cloudfront/src/main/resources/CF_function.js index f931c264bbd..b93cf4df09b 100644 --- a/javav2/example_code/cloudfront/src/main/resources/CF_function.js +++ b/javav2/example_code/cloudfront/src/main/resources/CF_function.js @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 function handler(event) { // NOTE: This example function is for a viewer request event trigger. // Choose viewer request for event trigger when you associate this function with a distribution. diff --git a/javav2/example_code/cloudfront/src/test/java/CloudFrontTest.java b/javav2/example_code/cloudfront/src/test/java/CloudFrontTest.java index 5cf93e42e9e..5879a06d1b3 100644 --- a/javav2/example_code/cloudfront/src/test/java/CloudFrontTest.java +++ b/javav2/example_code/cloudfront/src/test/java/CloudFrontTest.java @@ -1,7 +1,6 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + import com.google.gson.Gson; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.services.cloudfront.CloudFrontClient; @@ -23,18 +22,19 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class CloudFrontTest { - private static CloudFrontClient cloudFrontClient ; + private static CloudFrontClient cloudFrontClient; private static String functionName = ""; private static String filePath = ""; private static String funcARN = ""; private static String eTagVal = ""; private static String id = ""; + @BeforeAll public static void setUp() { cloudFrontClient = CloudFrontClient.builder() - .region(Region.AWS_GLOBAL) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.AWS_GLOBAL) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -44,34 +44,37 @@ public static void setUp() { filePath = values.getFilePath(); id = values.getId(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - try (InputStream input = CloudFrontTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - //load a properties file from class path, inside static method - prop.load(input); - - // Populate the data members required for all tests - functionName = prop.getProperty("functionName"); - filePath= prop.getProperty("filePath"); - id = prop.getProperty("id"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * try (InputStream input = + * CloudFrontTest.class.getClassLoader().getResourceAsStream("config.properties" + * )) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * //load a properties file from class path, inside static method + * prop.load(input); + * + * // Populate the data members required for all tests + * functionName = prop.getProperty("functionName"); + * filePath= prop.getProperty("filePath"); + * id = prop.getProperty("id"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @Tag("IntegrationTest") @Order(1) public void CreateFunction() { - funcARN = CreateFunction.createNewFunction(cloudFrontClient, functionName, filePath); + funcARN = CreateFunction.createNewFunction(cloudFrontClient, functionName, filePath); assertFalse(funcARN.isEmpty()); System.out.println("Test 1 passed"); } @@ -88,45 +91,45 @@ public void DescribeFunction() { @Test @Tag("IntegrationTest") @Order(3) - public void ListFunctions(){ - assertDoesNotThrow(() ->ListFunctions.listAllFunctions(cloudFrontClient)); + public void ListFunctions() { + assertDoesNotThrow(() -> ListFunctions.listAllFunctions(cloudFrontClient)); System.out.println("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void GetDistrubutions() { - assertDoesNotThrow(() ->com.example.cloudfront.GetDistributions.getCFDistributions(cloudFrontClient)); + public void GetDistrubutions() { + assertDoesNotThrow(() -> com.example.cloudfront.GetDistributions.getCFDistributions(cloudFrontClient)); System.out.println("Test 4 passed"); - } + } @Test @Tag("IntegrationTest") @Order(5) - public void ModifyDistrution() { - assertDoesNotThrow(() ->ModifyDistribution.modDistribution(cloudFrontClient, id)); + public void ModifyDistrution() { + assertDoesNotThrow(() -> ModifyDistribution.modDistribution(cloudFrontClient, id)); System.out.println("Test 5 passed"); - } + } @Test @Tag("IntegrationTest") @Order(6) - public void DeleteFunction(){ - assertDoesNotThrow(() ->DeleteFunction.deleteSpecificFunction(cloudFrontClient, functionName, eTagVal)); - System.out.println("Test 6 passed"); + public void DeleteFunction() { + assertDoesNotThrow(() -> DeleteFunction.deleteSpecificFunction(cloudFrontClient, functionName, eTagVal)); + System.out.println("Test 6 passed"); } - private static String getSecretValues() { + private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/cloudfront"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -152,4 +155,3 @@ public String getId() { } } } - diff --git a/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/CreateTrail.java b/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/CreateTrail.java index 33091446ea0..5fcc1f3bc5e 100644 --- a/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/CreateTrail.java +++ b/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/CreateTrail.java @@ -1,25 +1,20 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[CreateTrail.java demonstrates how to create a trail.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CloudTrail] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudtrail; -//snippet-start:[cloudtrail.java2.create_trail.main] -//snippet-start:[cloudtrail.java2.create_trail.import] + +// snippet-start:[cloudtrail.java2.create_trail.main] +// snippet-start:[cloudtrail.java2.create_trail.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudtrail.CloudTrailClient; import software.amazon.awssdk.services.cloudtrail.model.CloudTrailException; import software.amazon.awssdk.services.cloudtrail.model.CreateTrailRequest; import software.amazon.awssdk.services.cloudtrail.model.CreateTrailResponse; -//snippet-end:[cloudtrail.java2.create_trail.import] +// snippet-end:[cloudtrail.java2.create_trail.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,13 +25,13 @@ public class CreateTrail { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - trailName - The name of the trail.\s - s3BucketName - The name of the Amazon S3 bucket designated for publishing log files.\s - """; + Where: + trailName - The name of the trail.\s + s3BucketName - The name of the Amazon S3 bucket designated for publishing log files.\s + """; if (args.length != 2) { System.out.println(usage); @@ -47,8 +42,8 @@ public static void main(String[] args) { String s3BucketName = args[1]; Region region = Region.US_EAST_1; CloudTrailClient cloudTrailClient = CloudTrailClient.builder() - .region(region) - .build(); + .region(region) + .build(); createNewTrail(cloudTrailClient, trailName, s3BucketName); cloudTrailClient.close(); @@ -57,10 +52,10 @@ public static void main(String[] args) { public static void createNewTrail(CloudTrailClient cloudTrailClient, String trailName, String s3BucketName) { try { CreateTrailRequest trailRequest = CreateTrailRequest.builder() - .name(trailName) - .s3BucketName(s3BucketName) - .isMultiRegionTrail(true) - .build(); + .name(trailName) + .s3BucketName(s3BucketName) + .isMultiRegionTrail(true) + .build(); CreateTrailResponse trailResponse = cloudTrailClient.createTrail(trailRequest); System.out.println("The Trail ARN is " + trailResponse.trailARN()); @@ -71,4 +66,4 @@ public static void createNewTrail(CloudTrailClient cloudTrailClient, String trai } } } -//snippet-end:[cloudtrail.java2.create_trail.main] +// snippet-end:[cloudtrail.java2.create_trail.main] diff --git a/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/DeleteTrail.java b/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/DeleteTrail.java index 03f0ec719f7..0fe53cad32e 100644 --- a/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/DeleteTrail.java +++ b/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/DeleteTrail.java @@ -1,23 +1,19 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[DeleteTrail.java demonstrates how to delete a trail.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CloudTrail] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.cloudtrail; -//snippet-start:[cloudtrail.java2.delete_trail.main] -//snippet-start:[cloudtrail.java2.delete_trail.import] +// snippet-start:[cloudtrail.java2.delete_trail.main] +// snippet-start:[cloudtrail.java2.delete_trail.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudtrail.CloudTrailClient; import software.amazon.awssdk.services.cloudtrail.model.CloudTrailException; import software.amazon.awssdk.services.cloudtrail.model.DeleteTrailRequest; -//snippet-end:[cloudtrail.java2.delete_trail.import] +// snippet-end:[cloudtrail.java2.delete_trail.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +24,12 @@ public class DeleteTrail { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - trailName - The name of the trail to delete.\s - """; + Where: + trailName - The name of the trail to delete.\s + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +39,8 @@ public static void main(String[] args) { String trailName = args[0]; Region region = Region.US_EAST_1; CloudTrailClient cloudTrailClient = CloudTrailClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteSpecificTrail(cloudTrailClient, trailName); cloudTrailClient.close(); @@ -53,8 +49,8 @@ public static void main(String[] args) { public static void deleteSpecificTrail(CloudTrailClient cloudTrailClientClient, String trailName) { try { DeleteTrailRequest trailRequest = DeleteTrailRequest.builder() - .name(trailName) - .build(); + .name(trailName) + .build(); cloudTrailClientClient.deleteTrail(trailRequest); System.out.println(trailName + " was successfully deleted"); @@ -65,4 +61,4 @@ public static void deleteSpecificTrail(CloudTrailClient cloudTrailClientClient, } } } -//snippet-end:[cloudtrail.java2.delete_trail.main] +// snippet-end:[cloudtrail.java2.delete_trail.main] diff --git a/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/DescribeTrails.java b/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/DescribeTrails.java index 33b6d7595c6..380f259d30a 100644 --- a/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/DescribeTrails.java +++ b/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/DescribeTrails.java @@ -1,16 +1,10 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[DescribeTrails.java demonstrates how to look up information about a trail.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CloudTrail] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.cloudtrail; -//snippet-start:[cloudtrail.java2.describe_trail.main] -//snippet-start:[cloudtrail.java2.describe_trail.import] +// snippet-start:[cloudtrail.java2.describe_trail.main] +// snippet-start:[cloudtrail.java2.describe_trail.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudtrail.CloudTrailClient; import software.amazon.awssdk.services.cloudtrail.model.CloudTrailException; @@ -18,10 +12,11 @@ import software.amazon.awssdk.services.cloudtrail.model.DescribeTrailsResponse; import software.amazon.awssdk.services.cloudtrail.model.Trail; import java.util.List; -//snippet-end:[cloudtrail.java2.describe_trail.import] +// snippet-end:[cloudtrail.java2.describe_trail.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,12 +27,12 @@ public class DescribeTrails { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - trailName - The name of the trail to describe.\s - """; + Where: + trailName - The name of the trail to describe.\s + """; if (args.length != 1) { System.out.println(usage); @@ -47,8 +42,8 @@ public static void main(String[] args) { String trailName = args[0]; Region region = Region.US_EAST_1; CloudTrailClient cloudTrailClient = CloudTrailClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeSpecificTrails(cloudTrailClient, trailName); cloudTrailClient.close(); @@ -57,8 +52,8 @@ public static void main(String[] args) { public static void describeSpecificTrails(CloudTrailClient cloudTrailClientClient, String trailName) { try { DescribeTrailsRequest trailsRequest = DescribeTrailsRequest.builder() - .trailNameList(trailName) - .build(); + .trailNameList(trailName) + .build(); DescribeTrailsResponse response = cloudTrailClientClient.describeTrails(trailsRequest); List trails = response.trailList(); @@ -72,4 +67,4 @@ public static void describeSpecificTrails(CloudTrailClient cloudTrailClientClien } } } -//snippet-end:[cloudtrail.java2.describe_trail.main] \ No newline at end of file +// snippet-end:[cloudtrail.java2.describe_trail.main] \ No newline at end of file diff --git a/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/GetEventSelectors.java b/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/GetEventSelectors.java index aea20d6b934..cf929b063db 100644 --- a/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/GetEventSelectors.java +++ b/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/GetEventSelectors.java @@ -1,17 +1,10 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[GetEventSelectors.java demonstrates how to get event selectors for a given trail.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CloudTrail] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudtrail; -//snippet-start:[cloudtrail.java2.get_event_selectors.main] -//snippet-start:[cloudtrail.java2.get_event_selectors.import] +// snippet-start:[cloudtrail.java2.get_event_selectors.main] +// snippet-start:[cloudtrail.java2.get_event_selectors.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudtrail.CloudTrailClient; import software.amazon.awssdk.services.cloudtrail.model.CloudTrailException; @@ -19,10 +12,11 @@ import software.amazon.awssdk.services.cloudtrail.model.GetEventSelectorsRequest; import software.amazon.awssdk.services.cloudtrail.model.GetEventSelectorsResponse; import java.util.List; -//snippet-end:[cloudtrail.java2.get_event_selectors.import] +// snippet-end:[cloudtrail.java2.get_event_selectors.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -33,12 +27,12 @@ public class GetEventSelectors { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - trailName - The name of the trail.\s - """; + Where: + trailName - The name of the trail.\s + """; if (args.length != 1) { System.out.println(usage); @@ -48,8 +42,8 @@ public static void main(String[] args) { String trailName = args[0]; Region region = Region.US_EAST_1; CloudTrailClient cloudTrailClient = CloudTrailClient.builder() - .region(region) - .build(); + .region(region) + .build(); getSelectors(cloudTrailClient, trailName); cloudTrailClient.close(); @@ -58,13 +52,13 @@ public static void main(String[] args) { public static void getSelectors(CloudTrailClient cloudTrailClientClient, String trailName) { try { GetEventSelectorsRequest selectorsRequest = GetEventSelectorsRequest.builder() - .trailName(trailName) - .build(); + .trailName(trailName) + .build(); - GetEventSelectorsResponse selectorsResponse = cloudTrailClientClient. getEventSelectors(selectorsRequest); + GetEventSelectorsResponse selectorsResponse = cloudTrailClientClient.getEventSelectors(selectorsRequest); List selectors = selectorsResponse.eventSelectors(); - for (EventSelector selector: selectors) { - System.out.println("The type is "+selector.readWriteTypeAsString()); + for (EventSelector selector : selectors) { + System.out.println("The type is " + selector.readWriteTypeAsString()); } } catch (CloudTrailException e) { @@ -73,4 +67,4 @@ public static void getSelectors(CloudTrailClient cloudTrailClientClient, String } } } -//snippet-end:[cloudtrail.java2.get_event_selectors.main] +// snippet-end:[cloudtrail.java2.get_event_selectors.main] diff --git a/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/GetTrailLoggingTime.java b/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/GetTrailLoggingTime.java index 118f014914e..1027ac43a16 100644 --- a/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/GetTrailLoggingTime.java +++ b/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/GetTrailLoggingTime.java @@ -1,17 +1,10 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[GetTrailStatus.java demonstrates how to look up time information about a trail.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CloudTrail] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudtrail; -//snippet-start:[cloudtrail.java2.getLogTime.main] -//snippet-start:[cloudtrail.java2.getLogTime.import] +// snippet-start:[cloudtrail.java2.getLogTime.main] +// snippet-start:[cloudtrail.java2.getLogTime.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudtrail.CloudTrailClient; @@ -23,10 +16,11 @@ import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.util.Locale; -//snippet-end:[cloudtrail.java2.getLogTime.import] +// snippet-end:[cloudtrail.java2.getLogTime.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -38,43 +32,42 @@ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - trailName - The name of the trail.\s - """; + Where: + trailName - The name of the trail.\s + """; if (args.length != 1) { System.out.println(usage); System.exit(1); } - String trailName = args[0] ; + String trailName = args[0]; Region region = Region.US_EAST_1; CloudTrailClient cloudTrailClient = CloudTrailClient.builder() - .region(region) - .build(); + .region(region) + .build(); - getLogTime(cloudTrailClient, trailName) ; + getLogTime(cloudTrailClient, trailName); cloudTrailClient.close(); } public static void getLogTime(CloudTrailClient cloudTrailClientClient, String trailName) { try { GetTrailStatusRequest trailStatusRequest = GetTrailStatusRequest.builder() - .name(trailName) - .build(); + .name(trailName) + .build(); GetTrailStatusResponse trailStatusResponse = cloudTrailClientClient.getTrailStatus(trailStatusRequest); Instant lastestNotication = trailStatusResponse.startLoggingTime(); if (lastestNotication != null) { // Convert the Instant to readable date. - DateTimeFormatter formatter = - DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) - .withLocale(Locale.US) - .withZone(ZoneId.systemDefault()); + DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) + .withLocale(Locale.US) + .withZone(ZoneId.systemDefault()); formatter.format(lastestNotication); System.out.println("The date of the logging time is " + lastestNotication); @@ -88,4 +81,4 @@ public static void getLogTime(CloudTrailClient cloudTrailClientClient, String tr } } } -//snippet-end:[cloudtrail.java2.getLogTime.main] +// snippet-end:[cloudtrail.java2.getLogTime.main] diff --git a/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/LookupEvents.java b/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/LookupEvents.java index d4200981b91..89e9d440732 100644 --- a/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/LookupEvents.java +++ b/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/LookupEvents.java @@ -1,16 +1,10 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[LookupEvents.java demonstrates how to look up Cloud Trail events.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CloudTrail] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudtrail; -//snippet-start:[cloudtrail.java2.events.main] -//snippet-start:[cloudtrail.java2.events.import] +// snippet-start:[cloudtrail.java2.events.main] +// snippet-start:[cloudtrail.java2.events.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudtrail.CloudTrailClient; import software.amazon.awssdk.services.cloudtrail.model.CloudTrailException; @@ -18,10 +12,11 @@ import software.amazon.awssdk.services.cloudtrail.model.LookupEventsRequest; import software.amazon.awssdk.services.cloudtrail.model.LookupEventsResponse; import java.util.List; -//snippet-end:[cloudtrail.java2.events.import] +// snippet-end:[cloudtrail.java2.events.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,8 +27,8 @@ public class LookupEvents { public static void main(String[] args) { Region region = Region.US_EAST_1; CloudTrailClient cloudTrailClient = CloudTrailClient.builder() - .region(region) - .build(); + .region(region) + .build(); lookupAllEvents(cloudTrailClient); cloudTrailClient.close(); @@ -42,14 +37,14 @@ public static void main(String[] args) { public static void lookupAllEvents(CloudTrailClient cloudTrailClientClient) { try { LookupEventsRequest eventsRequest = LookupEventsRequest.builder() - .maxResults(20) - .build(); + .maxResults(20) + .build(); LookupEventsResponse response = cloudTrailClientClient.lookupEvents(eventsRequest); List events = response.events(); - for (Event event: events) { - System.out.println("Event name is : "+event.eventName()); - System.out.println("The event source is : "+event.eventSource()); + for (Event event : events) { + System.out.println("Event name is : " + event.eventName()); + System.out.println("The event source is : " + event.eventSource()); } } catch (CloudTrailException e) { @@ -58,4 +53,4 @@ public static void lookupAllEvents(CloudTrailClient cloudTrailClientClient) { } } } -//snippet-end:[cloudtrail.java2.events.main] +// snippet-end:[cloudtrail.java2.events.main] diff --git a/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/PutEventSelectors.java b/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/PutEventSelectors.java index ab69673c1e0..249cd245bc5 100644 --- a/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/PutEventSelectors.java +++ b/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/PutEventSelectors.java @@ -1,16 +1,10 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[PutEventSelectors.java demonstrates how to configure an event selector for your trail.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CloudTrail] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.cloudtrail; -//snippet-start:[cloudtrail.java2._selectors.main] -//snippet-start:[cloudtrail.java2._selectors.import] +// snippet-start:[cloudtrail.java2._selectors.main] +// snippet-start:[cloudtrail.java2._selectors.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudtrail.CloudTrailClient; @@ -19,10 +13,11 @@ import software.amazon.awssdk.services.cloudtrail.model.EventSelector; import java.util.ArrayList; import java.util.List; -//snippet-end:[cloudtrail.java2._selectors.import] +// snippet-end:[cloudtrail.java2._selectors.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -35,12 +30,12 @@ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - trailName - The name of the trail.\s - """; + Where: + trailName - The name of the trail.\s + """; if (args.length != 1) { System.out.println(usage); @@ -50,8 +45,8 @@ public static void main(String[] args) { String trailName = args[0]; Region region = Region.US_EAST_1; CloudTrailClient cloudTrailClient = CloudTrailClient.builder() - .region(region) - .build(); + .region(region) + .build(); setSelector(cloudTrailClient, trailName); cloudTrailClient.close(); @@ -60,15 +55,15 @@ public static void main(String[] args) { public static void setSelector(CloudTrailClient cloudTrailClientClient, String trailName) { try { EventSelector selector = EventSelector.builder() - .readWriteType("All") - .build(); + .readWriteType("All") + .build(); List selList = new ArrayList<>(); selList.add(selector); PutEventSelectorsRequest selectorsRequest = PutEventSelectorsRequest.builder() - .trailName(trailName) - .eventSelectors(selList) - .build(); + .trailName(trailName) + .eventSelectors(selList) + .build(); cloudTrailClientClient.putEventSelectors(selectorsRequest); @@ -78,4 +73,4 @@ public static void setSelector(CloudTrailClient cloudTrailClientClient, String t } } } -//snippet-end:[cloudtrail.java2._selectors.main] +// snippet-end:[cloudtrail.java2._selectors.main] diff --git a/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/StartLogging.java b/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/StartLogging.java index b44ada06125..ade64869e17 100644 --- a/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/StartLogging.java +++ b/javav2/example_code/cloudtrail/src/main/java/com/example/cloudtrail/StartLogging.java @@ -1,25 +1,20 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[StartLogging.java demonstrates how to start and stop logging.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CloudTrail] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudtrail; -//snippet-start:[cloudtrail.java2.logging.main] -//snippet-start:[cloudtrail.java2.logging.import] +// snippet-start:[cloudtrail.java2.logging.main] +// snippet-start:[cloudtrail.java2.logging.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudtrail.CloudTrailClient; import software.amazon.awssdk.services.cloudtrail.model.CloudTrailException; import software.amazon.awssdk.services.cloudtrail.model.StartLoggingRequest; import software.amazon.awssdk.services.cloudtrail.model.StopLoggingRequest; -//snippet-end:[cloudtrail.java2.logging.import] +// snippet-end:[cloudtrail.java2.logging.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,12 +25,12 @@ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - trailName - The name of the trail.\s - """; + Where: + trailName - The name of the trail.\s + """; if (args.length != 1) { System.out.println(usage); @@ -45,8 +40,8 @@ public static void main(String[] args) { String trailName = args[0]; Region region = Region.US_EAST_1; CloudTrailClient cloudTrailClient = CloudTrailClient.builder() - .region(region) - .build(); + .region(region) + .build(); startLog(cloudTrailClient, trailName); stopLog(cloudTrailClient, trailName); @@ -56,8 +51,8 @@ public static void main(String[] args) { public static void startLog(CloudTrailClient cloudTrailClientClient, String trailName) { try { StopLoggingRequest loggingRequest = StopLoggingRequest.builder() - .name(trailName) - .build(); + .name(trailName) + .build(); cloudTrailClientClient.stopLogging(loggingRequest); System.out.println(trailName + " has stopped logging"); @@ -71,8 +66,8 @@ public static void startLog(CloudTrailClient cloudTrailClientClient, String trai public static void stopLog(CloudTrailClient cloudTrailClientClient, String trailName) { try { StartLoggingRequest loggingRequest = StartLoggingRequest.builder() - .name(trailName) - .build(); + .name(trailName) + .build(); cloudTrailClientClient.startLogging(loggingRequest); System.out.println(trailName + " has started logging"); @@ -83,4 +78,4 @@ public static void stopLog(CloudTrailClient cloudTrailClientClient, String trail } } } -//snippet-end:[cloudtrail.java2.logging.main] +// snippet-end:[cloudtrail.java2.logging.main] diff --git a/javav2/example_code/cloudtrail/src/test/java/CloudTrailTest.java b/javav2/example_code/cloudtrail/src/test/java/CloudTrailTest.java index d80ea1572a2..b46a3d19355 100644 --- a/javav2/example_code/cloudtrail/src/test/java/CloudTrailTest.java +++ b/javav2/example_code/cloudtrail/src/test/java/CloudTrailTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.cloudtrail.*; import com.google.gson.Gson; @@ -21,16 +19,16 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class CloudTrailTest { - private static CloudTrailClient cloudTrailClient ; + private static CloudTrailClient cloudTrailClient; private static String trailName = ""; private static String s3BucketName = ""; @BeforeAll public static void setUp() { cloudTrailClient = CloudTrailClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -39,31 +37,34 @@ public static void setUp() { trailName = values.getTrailName(); s3BucketName = values.getS3BucketName(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - try (InputStream input = CloudTrailTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - // Populate the data members required for all tests. - prop.load(input); - trailName = prop.getProperty("trailName"); - s3BucketName = prop.getProperty("s3BucketName"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * try (InputStream input = + * CloudTrailTest.class.getClassLoader().getResourceAsStream("config.properties" + * )) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * // Populate the data members required for all tests. + * prop.load(input); + * trailName = prop.getProperty("trailName"); + * s3BucketName = prop.getProperty("s3BucketName"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @Tag("IntegrationTest") @Order(1) public void CreateTrail() { - assertDoesNotThrow(() ->CreateTrail.createNewTrail(cloudTrailClient, trailName, s3BucketName)); + assertDoesNotThrow(() -> CreateTrail.createNewTrail(cloudTrailClient, trailName, s3BucketName)); System.out.println("Test 1 passed"); } @@ -71,7 +72,7 @@ public void CreateTrail() { @Tag("IntegrationTest") @Order(2) public void PutEventSelectors() { - assertDoesNotThrow(() ->PutEventSelectors.setSelector(cloudTrailClient, trailName)); + assertDoesNotThrow(() -> PutEventSelectors.setSelector(cloudTrailClient, trailName)); System.out.println("Test 2 passed"); } @@ -79,7 +80,7 @@ public void PutEventSelectors() { @Tag("IntegrationTest") @Order(3) public void GetEventSelectors() { - assertDoesNotThrow(() ->GetEventSelectors.getSelectors(cloudTrailClient, trailName)); + assertDoesNotThrow(() -> GetEventSelectors.getSelectors(cloudTrailClient, trailName)); System.out.println("Test 3 passed"); } @@ -87,7 +88,7 @@ public void GetEventSelectors() { @Tag("IntegrationTest") @Order(4) public void LookupEvents() { - assertDoesNotThrow(() ->LookupEvents.lookupAllEvents(cloudTrailClient)); + assertDoesNotThrow(() -> LookupEvents.lookupAllEvents(cloudTrailClient)); System.out.println("Test 4 passed"); } @@ -95,7 +96,7 @@ public void LookupEvents() { @Tag("IntegrationTest") @Order(5) public void DescribeTrails() { - assertDoesNotThrow(() ->DescribeTrails.describeSpecificTrails(cloudTrailClient, trailName)); + assertDoesNotThrow(() -> DescribeTrails.describeSpecificTrails(cloudTrailClient, trailName)); System.out.println("Test 5 passed"); } @@ -103,7 +104,7 @@ public void DescribeTrails() { @Tag("IntegrationTest") @Order(6) public void GetTrailLoggingTime() { - assertDoesNotThrow(() ->GetTrailLoggingTime.getLogTime(cloudTrailClient, trailName)); + assertDoesNotThrow(() -> GetTrailLoggingTime.getLogTime(cloudTrailClient, trailName)); System.out.println("Test 6 passed"); } @@ -111,7 +112,7 @@ public void GetTrailLoggingTime() { @Tag("IntegrationTest") @Order(7) public void StartLogging() { - assertDoesNotThrow(() ->StartLogging.startLog(cloudTrailClient, trailName)); + assertDoesNotThrow(() -> StartLogging.startLog(cloudTrailClient, trailName)); System.out.println("Test 7 passed"); } @@ -119,7 +120,7 @@ public void StartLogging() { @Tag("IntegrationTest") @Order(8) public void StopLogging() { - assertDoesNotThrow(() ->StartLogging.stopLog(cloudTrailClient, trailName)); + assertDoesNotThrow(() -> StartLogging.stopLog(cloudTrailClient, trailName)); System.out.println("Test 8 passed"); } @@ -127,20 +128,20 @@ public void StopLogging() { @Tag("IntegrationTest") @Order(9) public void DeleteTrail() { - assertDoesNotThrow(() ->DeleteTrail.deleteSpecificTrail(cloudTrailClient, trailName)); + assertDoesNotThrow(() -> DeleteTrail.deleteSpecificTrail(cloudTrailClient, trailName)); System.out.println("Test 9 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/cloudtrail"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); diff --git a/javav2/example_code/cloudwatch/run_example.sh b/javav2/example_code/cloudwatch/run_example.sh index b6209662230..962e866f5f5 100755 --- a/javav2/example_code/cloudwatch/run_example.sh +++ b/javav2/example_code/cloudwatch/run_example.sh @@ -1,13 +1,15 @@ -#!/bin/bash -if [[ -z $* ]] ; then - echo 'Supply the name of one of the example classes as an argument.' - echo 'If there are arguments to the class, put them in quotes after the class name.' - exit 1 -fi -export CLASSPATH=target/sdk-cloudwatch-examples-1.0.jar -export className=$1 -echo "## Running $className..." -shift -echo "## arguments $@..." -mvn exec:java -Dexec.mainClass="com.example.cloudwatch.$className" -Dexec.args="$@" - +#!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +if [[ -z $* ]] ; then + echo 'Supply the name of one of the example classes as an argument.' + echo 'If there are arguments to the class, put them in quotes after the class name.' + exit 1 +fi +export CLASSPATH=target/sdk-cloudwatch-examples-1.0.jar +export className=$1 +echo "## Running $className..." +shift +echo "## arguments $@..." +mvn exec:java -Dexec.mainClass="com.example.cloudwatch.$className" -Dexec.args="$@" + diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/CloudWatchScenario.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/CloudWatchScenario.java index 96039e46d3d..dece8a435af 100644 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/CloudWatchScenario.java +++ b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/CloudWatchScenario.java @@ -1,13 +1,8 @@ -//snippet-sourcedescription:[CloudWatchScenario.java demonstrates how to perform various operations by using Amazon CloudWatch.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudWatch] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudwatch; + // snippet-start:[cloudwatch.java2.scenario.main] import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; @@ -78,13 +73,15 @@ import java.util.Scanner; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * To enable billing metrics and statistics for this example, make sure billing alerts are enabled for your account: + * To enable billing metrics and statistics for this example, make sure billing + * alerts are enabled for your account: * https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/monitor_estimated_charges_with_cloudwatch.html#turning_on_billing_metrics * * This Java code example performs the following tasks: @@ -110,26 +107,27 @@ */ public class CloudWatchScenario { public static final String DASHES = new String(new char[80]).replace("\0", "-"); + public static void main(String[] args) throws IOException { final String usage = """ - Usage: - \s - - Where: - myDate - The start date to use to get metric statistics. (For example, 2023-01-11T18:35:24.00Z.)\s - costDateWeek - The start date to use to get AWS/Billinget statistics. (For example, 2023-01-11T18:35:24.00Z.)\s - dashboardName - The name of the dashboard to create.\s - dashboardJson - The location of a JSON file to use to create a dashboard. (See Readme file.)\s - dashboardAdd - The location of a JSON file to use to update a dashboard. (See Readme file.)\s - settings - The location of a JSON file from which various values are read. (See Readme file.)\s - metricImage - The location of a BMP file that is used to create a graph.\s - """; - - if (args.length != 7) { - System.out.println(usage); - System.exit(1); - } + Usage: + \s + + Where: + myDate - The start date to use to get metric statistics. (For example, 2023-01-11T18:35:24.00Z.)\s + costDateWeek - The start date to use to get AWS/Billinget statistics. (For example, 2023-01-11T18:35:24.00Z.)\s + dashboardName - The name of the dashboard to create.\s + dashboardJson - The location of a JSON file to use to create a dashboard. (See Readme file.)\s + dashboardAdd - The location of a JSON file to use to update a dashboard. (See Readme file.)\s + settings - The location of a JSON file from which various values are read. (See Readme file.)\s + metricImage - The location of a BMP file that is used to create a graph.\s + """; + + if (args.length != 7) { + System.out.println(usage); + System.exit(1); + } Region region = Region.US_EAST_1; String myDate = args[0]; @@ -140,59 +138,59 @@ public static void main(String[] args) throws IOException { String settings = args[5]; String metricImage = args[6]; - Double dataPoint = Double.parseDouble("10.0"); Scanner sc = new Scanner(System.in); CloudWatchClient cw = CloudWatchClient.builder() - .region(region) - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(ProfileCredentialsProvider.create()) + .build(); System.out.println(DASHES); System.out.println("Welcome to the Amazon CloudWatch example scenario."); System.out.println(DASHES); System.out.println(DASHES); - System.out.println("1. List at least five available unique namespaces from Amazon CloudWatch. Select one from the list."); + System.out.println( + "1. List at least five available unique namespaces from Amazon CloudWatch. Select one from the list."); ArrayList list = listNameSpaces(cw); - for (int z=0; z<5; z++) { - int index = z+1; - System.out.println(" " +index +". " +list.get(z)); + for (int z = 0; z < 5; z++) { + int index = z + 1; + System.out.println(" " + index + ". " + list.get(z)); } String selectedNamespace = ""; String selectedMetrics = ""; int num = Integer.parseInt(sc.nextLine()); - if (1 <= num && num <= 5){ - selectedNamespace = list.get(num-1); + if (1 <= num && num <= 5) { + selectedNamespace = list.get(num - 1); } else { System.out.println("You did not select a valid option."); System.exit(1); } - System.out.println("You selected "+selectedNamespace); + System.out.println("You selected " + selectedNamespace); System.out.println(DASHES); System.out.println(DASHES); System.out.println("2. List available metrics within the selected namespace and select one from the list."); ArrayList metList = listMets(cw, selectedNamespace); - for (int z=0; z<5; z++) { - int index = z+1; - System.out.println(" " +index +". " +metList.get(z)); + for (int z = 0; z < 5; z++) { + int index = z + 1; + System.out.println(" " + index + ". " + metList.get(z)); } num = Integer.parseInt(sc.nextLine()); - if (1 <= num && num <= 5){ - selectedMetrics = metList.get(num-1); + if (1 <= num && num <= 5) { + selectedMetrics = metList.get(num - 1); } else { System.out.println("You did not select a valid option."); System.exit(1); } - System.out.println("You selected "+selectedMetrics); - Dimension myDimension = getSpecificMet( cw, selectedNamespace); + System.out.println("You selected " + selectedMetrics); + Dimension myDimension = getSpecificMet(cw, selectedNamespace); System.out.println(DASHES); System.out.println(DASHES); System.out.println("3. Get statistics for the selected metric over the last day."); - String metricOption=""; + String metricOption = ""; ArrayList statTypes = new ArrayList<>(); statTypes.add("SampleCount"); statTypes.add("Average"); @@ -200,18 +198,18 @@ public static void main(String[] args) throws IOException { statTypes.add("Minimum"); statTypes.add("Maximum"); - for (int t=0; t<5; t++){ - System.out.println(" " +(t+1) +". "+statTypes.get(t)); + for (int t = 0; t < 5; t++) { + System.out.println(" " + (t + 1) + ". " + statTypes.get(t)); } System.out.println("Select a metric statistic by entering a number from the preceding list:"); num = Integer.parseInt(sc.nextLine()); - if (1 <= num && num <= 5){ - metricOption = statTypes.get(num-1); + if (1 <= num && num <= 5) { + metricOption = statTypes.get(num - 1); } else { System.out.println("You did not select a valid option."); System.exit(1); } - System.out.println("You selected "+metricOption); + System.out.println("You selected " + metricOption); getAndDisplayMetricStatistics(cw, selectedNamespace, selectedMetrics, metricOption, myDate, myDimension); System.out.println(DASHES); @@ -252,12 +250,12 @@ public static void main(String[] args) throws IOException { System.out.println(DASHES); System.out.println("11. Get current data for new custom metric."); - getCustomMetricData(cw,settings); + getCustomMetricData(cw, settings); System.out.println(DASHES); System.out.println(DASHES); System.out.println("12. Push data into the custom metric to trigger the alarm."); - addMetricDataForAlarm(cw, settings) ; + addMetricDataForAlarm(cw, settings); System.out.println(DASHES); System.out.println(DASHES); @@ -308,14 +306,14 @@ public static void deleteAnomalyDetector(CloudWatchClient cw, String fileName) { String customMetricName = rootNode.findValue("customMetricName").asText(); SingleMetricAnomalyDetector singleMetricAnomalyDetector = SingleMetricAnomalyDetector.builder() - .metricName(customMetricName) - .namespace(customMetricNamespace) - .stat("Maximum") - .build(); + .metricName(customMetricName) + .namespace(customMetricNamespace) + .stat("Maximum") + .build(); DeleteAnomalyDetectorRequest request = DeleteAnomalyDetectorRequest.builder() - .singleMetricAnomalyDetector(singleMetricAnomalyDetector) - .build(); + .singleMetricAnomalyDetector(singleMetricAnomalyDetector) + .build(); cw.deleteAnomalyDetector(request); System.out.println("Successfully deleted the Anomaly Detector."); @@ -333,11 +331,11 @@ public static void deleteAnomalyDetector(CloudWatchClient cw, String fileName) { public static void deleteCWAlarm(CloudWatchClient cw, String alarmName) { try { DeleteAlarmsRequest request = DeleteAlarmsRequest.builder() - .alarmNames(alarmName) - .build(); + .alarmNames(alarmName) + .build(); cw.deleteAlarms(request); - System.out.println("Successfully deleted alarm " +alarmName); + System.out.println("Successfully deleted alarm " + alarmName); } catch (CloudWatchException e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -350,8 +348,8 @@ public static void deleteCWAlarm(CloudWatchClient cw, String alarmName) { public static void deleteDashboard(CloudWatchClient cw, String dashboardName) { try { DeleteDashboardsRequest dashboardsRequest = DeleteDashboardsRequest.builder() - .dashboardNames(dashboardName) - .build(); + .dashboardNames(dashboardName) + .build(); cw.deleteDashboards(dashboardsRequest); System.out.println(dashboardName + " was successfully deleted."); @@ -366,26 +364,26 @@ public static void deleteDashboard(CloudWatchClient cw, String dashboardName) { public static void getAndOpenMetricImage(CloudWatchClient cw, String fileName) { System.out.println("Getting Image data for custom metric."); try { - String myJSON = "{\n" + - " \"title\": \"Example Metric Graph\",\n" + - " \"view\": \"timeSeries\",\n" + - " \"stacked \": false,\n" + - " \"period\": 10,\n" + - " \"width\": 1400,\n" + - " \"height\": 600,\n" + - " \"metrics\": [\n" + - " [\n" + - " \"AWS/Billing\",\n" + - " \"EstimatedCharges\",\n" + - " \"Currency\",\n" + - " \"USD\"\n" + - " ]\n" + - " ]\n" + - "}"; + String myJSON = "{\n" + + " \"title\": \"Example Metric Graph\",\n" + + " \"view\": \"timeSeries\",\n" + + " \"stacked \": false,\n" + + " \"period\": 10,\n" + + " \"width\": 1400,\n" + + " \"height\": 600,\n" + + " \"metrics\": [\n" + + " [\n" + + " \"AWS/Billing\",\n" + + " \"EstimatedCharges\",\n" + + " \"Currency\",\n" + + " \"USD\"\n" + + " ]\n" + + " ]\n" + + "}"; GetMetricWidgetImageRequest imageRequest = GetMetricWidgetImageRequest.builder() - .metricWidget(myJSON) - .build(); + .metricWidget(myJSON) + .build(); GetMetricWidgetImageResponse response = cw.getMetricWidgetImage(imageRequest); SdkBytes sdkBytes = response.metricWidgetImage(); @@ -411,16 +409,16 @@ public static void describeAnomalyDetectors(CloudWatchClient cw, String fileName String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText(); String customMetricName = rootNode.findValue("customMetricName").asText(); DescribeAnomalyDetectorsRequest detectorsRequest = DescribeAnomalyDetectorsRequest.builder() - .maxResults(10) - .metricName(customMetricName) - .namespace(customMetricNamespace) - .build(); + .maxResults(10) + .metricName(customMetricName) + .namespace(customMetricNamespace) + .build(); - DescribeAnomalyDetectorsResponse response = cw.describeAnomalyDetectors(detectorsRequest) ; + DescribeAnomalyDetectorsResponse response = cw.describeAnomalyDetectors(detectorsRequest); List anomalyDetectorList = response.anomalyDetectors(); - for (AnomalyDetector detector: anomalyDetectorList) { - System.out.println("Metric name: "+detector.singleMetricAnomalyDetector().metricName()); - System.out.println("State: "+detector.stateValue()); + for (AnomalyDetector detector : anomalyDetectorList) { + System.out.println("Metric name: " + detector.singleMetricAnomalyDetector().metricName()); + System.out.println("State: " + detector.stateValue()); } } catch (CloudWatchException | IOException e) { @@ -440,17 +438,17 @@ public static void addAnomalyDetector(CloudWatchClient cw, String fileName) { String customMetricName = rootNode.findValue("customMetricName").asText(); SingleMetricAnomalyDetector singleMetricAnomalyDetector = SingleMetricAnomalyDetector.builder() - .metricName(customMetricName) - .namespace(customMetricNamespace) - .stat("Maximum") - .build(); + .metricName(customMetricName) + .namespace(customMetricNamespace) + .stat("Maximum") + .build(); PutAnomalyDetectorRequest anomalyDetectorRequest = PutAnomalyDetectorRequest.builder() - .singleMetricAnomalyDetector(singleMetricAnomalyDetector) - .build(); + .singleMetricAnomalyDetector(singleMetricAnomalyDetector) + .build(); cw.putAnomalyDetector(anomalyDetectorRequest); - System.out.println("Added anomaly detector for metric "+customMetricName+"."); + System.out.println("Added anomaly detector for metric " + customMetricName + "."); } catch (CloudWatchException | IOException e) { System.err.println(e.getMessage()); @@ -470,20 +468,20 @@ public static void getAlarmHistory(CloudWatchClient cw, String fileName, String Instant start = Instant.parse(date); Instant endDate = Instant.now(); DescribeAlarmHistoryRequest historyRequest = DescribeAlarmHistoryRequest.builder() - .startDate(start) - .endDate(endDate) - .alarmName(alarmName) - .historyItemType(HistoryItemType.ACTION) - .build(); + .startDate(start) + .endDate(endDate) + .alarmName(alarmName) + .historyItemType(HistoryItemType.ACTION) + .build(); DescribeAlarmHistoryResponse response = cw.describeAlarmHistory(historyRequest); - ListhistoryItems = response.alarmHistoryItems(); + List historyItems = response.alarmHistoryItems(); if (historyItems.isEmpty()) { - System.out.println("No alarm history data found for "+alarmName +"."); + System.out.println("No alarm history data found for " + alarmName + "."); } else { - for (AlarmHistoryItem item: historyItems) { - System.out.println("History summary: "+item.historySummary()); - System.out.println("Time stamp: "+item.timestamp()); + for (AlarmHistoryItem item : historyItems) { + System.out.println("History summary: " + item.historySummary()); + System.out.println("Time stamp: " + item.timestamp()); } } @@ -506,9 +504,9 @@ public static void checkForMetricAlarm(CloudWatchClient cw, String fileName) { int retries = 10; DescribeAlarmsForMetricRequest metricRequest = DescribeAlarmsForMetricRequest.builder() - .metricName(customMetricName) - .namespace(customMetricNamespace) - .build(); + .metricName(customMetricName) + .namespace(customMetricNamespace) + .build(); while (!hasAlarm && retries > 0) { DescribeAlarmsForMetricResponse response = cw.describeAlarmsForMetric(metricRequest); @@ -518,9 +516,9 @@ public static void checkForMetricAlarm(CloudWatchClient cw, String fileName) { System.out.println("."); } if (!hasAlarm) - System.out.println("No Alarm state found for "+ customMetricName +" after 10 retries."); + System.out.println("No Alarm state found for " + customMetricName + " after 10 retries."); else - System.out.println("Alarm state found for "+ customMetricName +"."); + System.out.println("Alarm state found for " + customMetricName + "."); } catch (CloudWatchException | IOException | InterruptedException e) { System.err.println(e.getMessage()); @@ -539,34 +537,34 @@ public static void addMetricDataForAlarm(CloudWatchClient cw, String fileName) { String customMetricName = rootNode.findValue("customMetricName").asText(); // Set an Instant object. - String time = ZonedDateTime.now( ZoneOffset.UTC ).format( DateTimeFormatter.ISO_INSTANT ); + String time = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT); Instant instant = Instant.parse(time); MetricDatum datum = MetricDatum.builder() - .metricName(customMetricName) - .unit(StandardUnit.NONE) - .value(1001.00) - .timestamp(instant) - .build(); + .metricName(customMetricName) + .unit(StandardUnit.NONE) + .value(1001.00) + .timestamp(instant) + .build(); MetricDatum datum2 = MetricDatum.builder() - .metricName(customMetricName) - .unit(StandardUnit.NONE) - .value(1002.00) - .timestamp(instant) - .build(); + .metricName(customMetricName) + .unit(StandardUnit.NONE) + .value(1002.00) + .timestamp(instant) + .build(); List metricDataList = new ArrayList<>(); metricDataList.add(datum); metricDataList.add(datum2); PutMetricDataRequest request = PutMetricDataRequest.builder() - .namespace(customMetricNamespace) - .metricData(metricDataList) - .build(); + .namespace(customMetricNamespace) + .metricData(metricDataList) + .build(); cw.putMetricData(request); - System.out.println("Added metric values for for metric " +customMetricName); + System.out.println("Added metric values for for metric " + customMetricName); } catch (CloudWatchException | IOException e) { System.err.println(e.getMessage()); @@ -590,35 +588,35 @@ public static void getCustomMetricData(CloudWatchClient cw, String fileName) { long hours = 1; long minutes = 30; Instant date2 = nowDate.plus(hours, ChronoUnit.HOURS).plus(minutes, - ChronoUnit.MINUTES); + ChronoUnit.MINUTES); Metric met = Metric.builder() - .metricName(customMetricName) - .namespace(customMetricNamespace) - .build(); + .metricName(customMetricName) + .namespace(customMetricNamespace) + .build(); MetricStat metStat = MetricStat.builder() - .stat("Maximum") - .period(1) - .metric(met) - .build(); + .stat("Maximum") + .period(1) + .metric(met) + .build(); MetricDataQuery dataQUery = MetricDataQuery.builder() - .metricStat(metStat) - .id("foo2") - .returnData(true) - .build(); + .metricStat(metStat) + .id("foo2") + .returnData(true) + .build(); List dq = new ArrayList<>(); dq.add(dataQUery); GetMetricDataRequest getMetReq = GetMetricDataRequest.builder() - .maxDatapoints(10) - .scanBy(ScanBy.TIMESTAMP_DESCENDING) - .startTime(nowDate) - .endTime(date2) - .metricDataQueries(dq) - .build(); + .maxDatapoints(10) + .scanBy(ScanBy.TIMESTAMP_DESCENDING) + .startTime(nowDate) + .endTime(date2) + .metricDataQueries(dq) + .build(); GetMetricDataResponse response = cw.getMetricData(getMetReq); List data = response.metricDataResults(); @@ -641,13 +639,13 @@ public static void describeAlarms(CloudWatchClient cw) { typeList.add(AlarmType.METRIC_ALARM); DescribeAlarmsRequest alarmsRequest = DescribeAlarmsRequest.builder() - .alarmTypes(typeList) - .maxRecords(10) - .build(); + .alarmTypes(typeList) + .maxRecords(10) + .build(); DescribeAlarmsResponse response = cw.describeAlarms(alarmsRequest); List alarmList = response.metricAlarms(); - for (MetricAlarm alarm: alarmList) { + for (MetricAlarm alarm : alarmList) { System.out.println("Alarm name: " + alarm.alarmName()); System.out.println("Alarm description: " + alarm.alarmDescription()); } @@ -673,24 +671,24 @@ public static String createAlarm(CloudWatchClient cw, String fileName) { // Create a List for alarm actions. List alarmActions = new ArrayList<>(); - alarmActions.add("arn:aws:sns:"+region+":"+accountId+":"+emailTopic); + alarmActions.add("arn:aws:sns:" + region + ":" + accountId + ":" + emailTopic); PutMetricAlarmRequest alarmRequest = PutMetricAlarmRequest.builder() - .alarmActions(alarmActions) - .alarmDescription("Example metric alarm") - .alarmName(alarmName) - .comparisonOperator(ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD) - .threshold(100.00) - .metricName(customMetricName) - .namespace(customMetricNamespace) - .evaluationPeriods(1) - .period(10) - .statistic("Maximum") - .datapointsToAlarm(1) - .treatMissingData("ignore") - .build(); + .alarmActions(alarmActions) + .alarmDescription("Example metric alarm") + .alarmName(alarmName) + .comparisonOperator(ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD) + .threshold(100.00) + .metricName(customMetricName) + .namespace(customMetricNamespace) + .evaluationPeriods(1) + .period(10) + .statistic("Maximum") + .datapointsToAlarm(1) + .treatMissingData("ignore") + .build(); cw.putMetricAlarm(alarmRequest); - System.out.println(alarmName +" was successfully created!"); + System.out.println(alarmName + " was successfully created!"); return alarmName; } catch (CloudWatchException | IOException e) { @@ -705,12 +703,12 @@ public static String createAlarm(CloudWatchClient cw, String fileName) { public static void addMetricToDashboard(CloudWatchClient cw, String fileName, String dashboardName) { try { PutDashboardRequest dashboardRequest = PutDashboardRequest.builder() - .dashboardName(dashboardName) - .dashboardBody(readFileAsString(fileName)) - .build(); + .dashboardName(dashboardName) + .dashboardBody(readFileAsString(fileName)) + .build(); cw.putDashboard(dashboardRequest); - System.out.println(dashboardName +" was successfully updated."); + System.out.println(dashboardName + " was successfully updated."); } catch (CloudWatchException | IOException e) { System.err.println(e.getMessage()); @@ -723,26 +721,26 @@ public static void addMetricToDashboard(CloudWatchClient cw, String fileName, St public static void createNewCustomMetric(CloudWatchClient cw, Double dataPoint) { try { Dimension dimension = Dimension.builder() - .name("UNIQUE_PAGES") - .value("URLS") - .build(); + .name("UNIQUE_PAGES") + .value("URLS") + .build(); // Set an Instant object. - String time = ZonedDateTime.now( ZoneOffset.UTC ).format( DateTimeFormatter.ISO_INSTANT ); + String time = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT); Instant instant = Instant.parse(time); MetricDatum datum = MetricDatum.builder() - .metricName("PAGES_VISITED") - .unit(StandardUnit.NONE) - .value(dataPoint) - .timestamp(instant) - .dimensions(dimension) - .build(); + .metricName("PAGES_VISITED") + .unit(StandardUnit.NONE) + .value(dataPoint) + .timestamp(instant) + .dimensions(dimension) + .build(); PutMetricDataRequest request = PutMetricDataRequest.builder() - .namespace("SITE/TRAFFIC") - .metricData(datum) - .build(); + .namespace("SITE/TRAFFIC") + .metricData(datum) + .build(); cw.putMetricData(request); System.out.println("Added metric values for for metric PAGES_VISITED"); @@ -759,11 +757,11 @@ public static void listDashboards(CloudWatchClient cw) { try { ListDashboardsIterable listRes = cw.listDashboardsPaginator(); listRes.stream() - .flatMap(r -> r.dashboardEntries().stream()) - .forEach(entry ->{ - System.out.println("Dashboard name is: " + entry.dashboardName()); - System.out.println("Dashboard ARN is: " + entry.dashboardArn()); - }); + .flatMap(r -> r.dashboardEntries().stream()) + .forEach(entry -> { + System.out.println("Dashboard name is: " + entry.dashboardName()); + System.out.println("Dashboard ARN is: " + entry.dashboardArn()); + }); } catch (CloudWatchException e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -776,12 +774,12 @@ public static void listDashboards(CloudWatchClient cw) { public static void createDashboardWithMetrics(CloudWatchClient cw, String dashboardName, String fileName) { try { PutDashboardRequest dashboardRequest = PutDashboardRequest.builder() - .dashboardName(dashboardName) - .dashboardBody(readFileAsString(fileName)) - .build(); + .dashboardName(dashboardName) + .dashboardBody(readFileAsString(fileName)) + .build(); PutDashboardResponse response = cw.putDashboard(dashboardRequest); - System.out.println(dashboardName +" was successfully created."); + System.out.println(dashboardName + " was successfully created."); List messages = response.dashboardValidationMessages(); if (messages.isEmpty()) { System.out.println("There are no messages in the new Dashboard"); @@ -808,27 +806,28 @@ public static void getMetricStatistics(CloudWatchClient cw, String costDateWeek) Instant start = Instant.parse(costDateWeek); Instant endDate = Instant.now(); Dimension dimension = Dimension.builder() - .name("Currency") - .value("USD") - .build(); + .name("Currency") + .value("USD") + .build(); List dimensionList = new ArrayList<>(); dimensionList.add(dimension); GetMetricStatisticsRequest statisticsRequest = GetMetricStatisticsRequest.builder() - .metricName("EstimatedCharges") - .namespace("AWS/Billing") - .dimensions(dimensionList) - .statistics(Statistic.MAXIMUM) - .startTime(start) - .endTime(endDate) - .period(86400) - .build(); + .metricName("EstimatedCharges") + .namespace("AWS/Billing") + .dimensions(dimensionList) + .statistics(Statistic.MAXIMUM) + .startTime(start) + .endTime(endDate) + .period(86400) + .build(); GetMetricStatisticsResponse response = cw.getMetricStatistics(statisticsRequest); List data = response.datapoints(); if (!data.isEmpty()) { - for (Datapoint datapoint: data) { - System.out.println("Timestamp: " + datapoint.timestamp() + " Maximum value: " + datapoint.maximum()); + for (Datapoint datapoint : data) { + System.out + .println("Timestamp: " + datapoint.timestamp() + " Maximum value: " + datapoint.maximum()); } } else { System.out.println("The returned data list is empty"); @@ -842,26 +841,28 @@ public static void getMetricStatistics(CloudWatchClient cw, String costDateWeek) // snippet-end:[cloudwatch.java2.scenario.get.metrics.main] // snippet-start:[cloudwatch.java2.scenario.display.metrics.main] - public static void getAndDisplayMetricStatistics( CloudWatchClient cw, String nameSpace, String metVal, String metricOption, String date, Dimension myDimension) { + public static void getAndDisplayMetricStatistics(CloudWatchClient cw, String nameSpace, String metVal, + String metricOption, String date, Dimension myDimension) { try { Instant start = Instant.parse(date); Instant endDate = Instant.now(); GetMetricStatisticsRequest statisticsRequest = GetMetricStatisticsRequest.builder() - .endTime(endDate) - .startTime(start) - .dimensions(myDimension) - .metricName(metVal) - .namespace(nameSpace) - .period(86400) - .statistics(Statistic.fromValue(metricOption)) - .build(); + .endTime(endDate) + .startTime(start) + .dimensions(myDimension) + .metricName(metVal) + .namespace(nameSpace) + .period(86400) + .statistics(Statistic.fromValue(metricOption)) + .build(); GetMetricStatisticsResponse response = cw.getMetricStatistics(statisticsRequest); List data = response.datapoints(); if (!data.isEmpty()) { - for (Datapoint datapoint: data) { - System.out.println("Timestamp: " + datapoint.timestamp() + " Maximum value: " + datapoint.maximum()); + for (Datapoint datapoint : data) { + System.out + .println("Timestamp: " + datapoint.timestamp() + " Maximum value: " + datapoint.maximum()); } } else { System.out.println("The returned data list is empty"); @@ -874,11 +875,11 @@ public static void getAndDisplayMetricStatistics( CloudWatchClient cw, String na } // snippet-end:[cloudwatch.java2.scenario.display.metrics.main] - public static Dimension getSpecificMet( CloudWatchClient cw, String namespace) { + public static Dimension getSpecificMet(CloudWatchClient cw, String namespace) { try { ListMetricsRequest request = ListMetricsRequest.builder() - .namespace(namespace) - .build(); + .namespace(namespace) + .build(); ListMetricsResponse response = cw.listMetrics(request); List myList = response.metrics(); @@ -893,17 +894,17 @@ public static Dimension getSpecificMet( CloudWatchClient cw, String namespace) { } // snippet-start:[cloudwatch.java2.scenario.list.metrics.main] - public static ArrayList listMets( CloudWatchClient cw, String namespace) { + public static ArrayList listMets(CloudWatchClient cw, String namespace) { try { ArrayList metList = new ArrayList<>(); ListMetricsRequest request = ListMetricsRequest.builder() - .namespace(namespace) - .build(); + .namespace(namespace) + .build(); ListMetricsIterable listRes = cw.listMetricsPaginator(request); listRes.stream() - .flatMap(r -> r.metrics().stream()) - .forEach(metrics -> metList.add(metrics.metricName())); + .flatMap(r -> r.metrics().stream()) + .forEach(metrics -> metList.add(metrics.metricName())); return metList; @@ -916,29 +917,29 @@ public static ArrayList listMets( CloudWatchClient cw, String namespace) // snippet-end:[cloudwatch.java2.scenario.list.metrics.main] // snippet-start:[cloudwatch.java2.scenario.list.namespaces.main] - public static ArrayList listNameSpaces(CloudWatchClient cw) { - try { - ArrayList nameSpaceList = new ArrayList<>(); - ListMetricsRequest request = ListMetricsRequest.builder() - .build(); - - ListMetricsIterable listRes = cw.listMetricsPaginator(request); - listRes.stream() - .flatMap(r -> r.metrics().stream()) - .forEach(metrics -> { - String data = metrics.namespace(); - if(!nameSpaceList.contains(data)) { - nameSpaceList.add(data); - } - }) ; - - return nameSpaceList; - } catch (CloudWatchException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - return null; - } + public static ArrayList listNameSpaces(CloudWatchClient cw) { + try { + ArrayList nameSpaceList = new ArrayList<>(); + ListMetricsRequest request = ListMetricsRequest.builder() + .build(); + + ListMetricsIterable listRes = cw.listMetricsPaginator(request); + listRes.stream() + .flatMap(r -> r.metrics().stream()) + .forEach(metrics -> { + String data = metrics.namespace(); + if (!nameSpaceList.contains(data)) { + nameSpaceList.add(data); + } + }); + + return nameSpaceList; + } catch (CloudWatchException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + return null; + } // snippet-end:[cloudwatch.java2.scenario.list.namespaces.main] } // snippet-end:[cloudwatch.java2.scenario.main] \ No newline at end of file diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DeleteAlarm.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DeleteAlarm.java index b9734e7c4d8..0beb6381456 100644 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DeleteAlarm.java +++ b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DeleteAlarm.java @@ -1,10 +1,6 @@ -//snippet-sourcedescription:[DeleteAlarm.java demonstrates how to delete an Amazon CloudWatch alarm.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudWatch] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.cloudwatch; // snippet-start:[cloudwatch.java2.delete_metrics.main] @@ -16,7 +12,8 @@ // snippet-end:[cloudwatch.java2.delete_metrics.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,12 +24,12 @@ public class DeleteAlarm { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - alarmName - An alarm name to delete (for example, MyAlarm). - """; + Where: + alarmName - An alarm name to delete (for example, MyAlarm). + """; if (args.length != 1) { System.out.println(usage); @@ -42,18 +39,18 @@ public static void main(String[] args) { String alarmName = args[0]; Region region = Region.US_EAST_2; CloudWatchClient cw = CloudWatchClient.builder() - .region(region) - .build(); + .region(region) + .build(); - deleteCWAlarm(cw, alarmName) ; + deleteCWAlarm(cw, alarmName); cw.close(); } public static void deleteCWAlarm(CloudWatchClient cw, String alarmName) { try { DeleteAlarmsRequest request = DeleteAlarmsRequest.builder() - .alarmNames(alarmName) - .build(); + .alarmNames(alarmName) + .build(); cw.deleteAlarms(request); System.out.printf("Successfully deleted alarm %s", alarmName); diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DeleteSubscriptionFilter.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DeleteSubscriptionFilter.java index bb89d67d389..787c930d5b2 100644 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DeleteSubscriptionFilter.java +++ b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DeleteSubscriptionFilter.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[DeleteSubscriptionFilter.java demonstrates how to delete Amazon CloudWatch log subscription filters.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudWatch] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.cloudwatch; // snippet-start:[cloudwatch.java2.delete_subscription_filter.main] @@ -16,7 +11,8 @@ // snippet-end:[cloudwatch.java2.delete_subscription_filter.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -26,13 +22,13 @@ public class DeleteSubscriptionFilter { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - filter - The name of the subscription filter (for example, MyFilter). - logGroup - The name of the log group. (for example, testgroup). - """; + Where: + filter - The name of the subscription filter (for example, MyFilter). + logGroup - The name of the log group. (for example, testgroup). + """; if (args.length != 2) { System.out.println(usage); @@ -42,18 +38,18 @@ public static void main(String[] args) { String filter = args[0]; String logGroup = args[1]; CloudWatchLogsClient logs = CloudWatchLogsClient.builder() - .build(); + .build(); - deleteSubFilter(logs, filter, logGroup ); + deleteSubFilter(logs, filter, logGroup); logs.close(); } public static void deleteSubFilter(CloudWatchLogsClient logs, String filter, String logGroup) { try { DeleteSubscriptionFilterRequest request = DeleteSubscriptionFilterRequest.builder() - .filterName(filter) - .logGroupName(logGroup) - .build(); + .filterName(filter) + .logGroupName(logGroup) + .build(); logs.deleteSubscriptionFilter(request); System.out.printf("Successfully deleted CloudWatch logs subscription filter %s", filter); @@ -62,7 +58,6 @@ public static void deleteSubFilter(CloudWatchLogsClient logs, String filter, Str System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } - } + } } // snippet-end:[cloudwatch.java2.delete_subscription_filter.main] - diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DescribeAlarms.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DescribeAlarms.java index eb74c591173..60b334d8d6e 100644 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DescribeAlarms.java +++ b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DescribeAlarms.java @@ -1,10 +1,6 @@ -//snippet-sourcedescription:[DescribeAlarms.java demonstrates how to get information about Amazon CloudWatch alarms.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudWatch] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.cloudwatch; // snippet-start:[cloudwatch.java2.describe_alarms.main] @@ -18,7 +14,8 @@ // snippet-end:[cloudwatch.java2.describe_alarms.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,34 +25,34 @@ public class DescribeAlarms { public static void main(String[] args) { Region region = Region.US_EAST_1; CloudWatchClient cw = CloudWatchClient.builder() - .region(region) - .build(); + .region(region) + .build(); - desCWAlarms(cw) ; + desCWAlarms(cw); cw.close(); } - public static void desCWAlarms( CloudWatchClient cw) { + public static void desCWAlarms(CloudWatchClient cw) { try { boolean done = false; String newToken = null; - while(!done) { + while (!done) { DescribeAlarmsResponse response; if (newToken == null) { DescribeAlarmsRequest request = DescribeAlarmsRequest.builder().build(); response = cw.describeAlarms(request); } else { DescribeAlarmsRequest request = DescribeAlarmsRequest.builder() - .nextToken(newToken) - .build(); + .nextToken(newToken) + .build(); response = cw.describeAlarms(request); } - for(MetricAlarm alarm : response.metricAlarms()) { + for (MetricAlarm alarm : response.metricAlarms()) { System.out.printf("\n Retrieved alarm %s", alarm.alarmName()); } - if(response.nextToken() == null) { + if (response.nextToken() == null) { done = true; } else { newToken = response.nextToken(); diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DescribeRule.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DescribeRule.java index 83106fbd448..624cc9af6f6 100644 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DescribeRule.java +++ b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DescribeRule.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeRule.java demonstrates how to describe an existing rule and determine its schedule.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudWatch] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudwatch; @@ -18,9 +12,9 @@ import software.amazon.awssdk.services.cloudwatchevents.model.DescribeRuleResponse; // snippet-end:[cloudwatch.javav2.describe_rule.import] - /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,12 +24,12 @@ public class DescribeRule { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - ruleName - The name of the rule to describe. - """; + Where: + ruleName - The name of the rule to describe. + """; if (args.length != 1) { System.out.println(usage); @@ -44,8 +38,8 @@ public static void main(String[] args) { String ruleName = args[0]; CloudWatchEventsClient cwe = CloudWatchEventsClient.builder() - .region(Region.US_WEST_2) - .build(); + .region(Region.US_WEST_2) + .build(); describeSpecificRule(cwe, ruleName); cwe.close(); @@ -54,12 +48,12 @@ public static void main(String[] args) { public static void describeSpecificRule(CloudWatchEventsClient cwe, String ruleName) { try { DescribeRuleRequest ruleRequest = DescribeRuleRequest.builder() - .name(ruleName) - .build(); + .name(ruleName) + .build(); DescribeRuleResponse ruleResp = cwe.describeRule(ruleRequest); String schedule = ruleResp.scheduleExpression(); - System.out.println("The schedule for this rule is "+schedule); + System.out.println("The schedule for this rule is " + schedule); } catch (CloudWatchException e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DescribeSubscriptionFilters.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DescribeSubscriptionFilters.java index 0a87cced441..00debca652f 100644 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DescribeSubscriptionFilters.java +++ b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DescribeSubscriptionFilters.java @@ -1,12 +1,8 @@ -//snippet-sourcedescription:[DescribeSubscriptionFilters.java demonstrates how to get a list of Amazon CloudWatch subscription filters associated with a log group.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudWatch] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.cloudwatch; + // snippet-start:[cloudwatch.java2.describe_subscription_filters.main] // snippet-start:[cloudwatch.java2.describe_subscription_filters.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; @@ -18,7 +14,8 @@ // snippet-end:[cloudwatch.java2.describe_subscription_filters.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,12 +26,12 @@ public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - logGroup - A log group name (for example, myloggroup). - """; + Where: + logGroup - A log group name (for example, myloggroup). + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +40,8 @@ public static void main(String[] args) { String logGroup = args[0]; CloudWatchLogsClient logs = CloudWatchLogsClient.builder() - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); + .credentialsProvider(ProfileCredentialsProvider.create()) + .build(); describeFilters(logs, logGroup); logs.close(); @@ -55,42 +52,41 @@ public static void describeFilters(CloudWatchLogsClient logs, String logGroup) { boolean done = false; String newToken = null; - while(!done) { + while (!done) { DescribeSubscriptionFiltersResponse response; if (newToken == null) { DescribeSubscriptionFiltersRequest request = DescribeSubscriptionFiltersRequest.builder() - .logGroupName(logGroup) - .limit(1).build(); + .logGroupName(logGroup) + .limit(1).build(); response = logs.describeSubscriptionFilters(request); } else { DescribeSubscriptionFiltersRequest request = DescribeSubscriptionFiltersRequest.builder() - .nextToken(newToken) - .logGroupName(logGroup) - .limit(1).build(); + .nextToken(newToken) + .logGroupName(logGroup) + .limit(1).build(); response = logs.describeSubscriptionFilters(request); } - for(SubscriptionFilter filter : response.subscriptionFilters()) { + for (SubscriptionFilter filter : response.subscriptionFilters()) { System.out.printf("Retrieved filter with name %s, " + "pattern %s " + "and destination arn %s", - filter.filterName(), - filter.filterPattern(), - filter.destinationArn()); + filter.filterName(), + filter.filterPattern(), + filter.destinationArn()); } - if(response.nextToken() == null) { + if (response.nextToken() == null) { done = true; } else { newToken = response.nextToken(); } - } + } } catch (CloudWatchException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); } System.out.printf("Done"); } } // snippet-end:[cloudwatch.java2.describe_subscription_filters.main] - diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DisableAlarmActions.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DisableAlarmActions.java index 62c39dc82e6..a21a1adde6c 100644 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DisableAlarmActions.java +++ b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/DisableAlarmActions.java @@ -1,12 +1,8 @@ -//snippet-sourcedescription:[DisableAlarmActions.java demonstrates how to disable actions on an Amazon CloudWatch alarm.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudWatch] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.cloudwatch; + // snippet-start:[cloudwatch.java2.disable_alarm_actions.main] // snippet-start:[cloudwatch.java2.disable_alarm_actions.import] import software.amazon.awssdk.regions.Region; @@ -16,7 +12,8 @@ // snippet-end:[cloudwatch.java2.disable_alarm_actions.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -26,12 +23,12 @@ public class DisableAlarmActions { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - alarmName - An alarm name to disable (for example, MyAlarm). - """; + Where: + alarmName - An alarm name to disable (for example, MyAlarm). + """; if (args.length != 1) { System.out.println(usage); @@ -41,18 +38,18 @@ public static void main(String[] args) { String alarmName = args[0]; Region region = Region.US_EAST_1; CloudWatchClient cw = CloudWatchClient.builder() - .region(region) - .build(); + .region(region) + .build(); - disableActions(cw, alarmName) ; + disableActions(cw, alarmName); cw.close(); } public static void disableActions(CloudWatchClient cw, String alarmName) { try { DisableAlarmActionsRequest request = DisableAlarmActionsRequest.builder() - .alarmNames(alarmName) - .build(); + .alarmNames(alarmName) + .build(); cw.disableAlarmActions(request); System.out.printf("Successfully disabled actions on alarm %s", alarmName); diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/EnableAlarmActions.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/EnableAlarmActions.java index 681dcd0c634..eec07f5414d 100644 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/EnableAlarmActions.java +++ b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/EnableAlarmActions.java @@ -1,10 +1,6 @@ -//snippet-sourcedescription:[EnableAlarmActions.java demonstrates how to enable actions on a CloudWatch alarm.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudWatch] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.cloudwatch; // snippet-start:[cloudwatch.java2.enable_alarm_actions.main] @@ -16,7 +12,8 @@ // snippet-end:[cloudwatch.java2.enable_alarm_actions.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -26,12 +23,12 @@ public class EnableAlarmActions { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - alarmName - An alarm name to enable (for example, MyAlarm). - """; + Where: + alarmName - An alarm name to enable (for example, MyAlarm). + """; if (args.length != 1) { System.out.println(usage); @@ -41,18 +38,18 @@ public static void main(String[] args) { String alarm = args[0]; Region region = Region.US_EAST_1; CloudWatchClient cw = CloudWatchClient.builder() - .region(region) - .build(); + .region(region) + .build(); - enableActions(cw, alarm) ; + enableActions(cw, alarm); cw.close(); } public static void enableActions(CloudWatchClient cw, String alarm) { try { EnableAlarmActionsRequest request = EnableAlarmActionsRequest.builder() - .alarmNames(alarm) - .build(); + .alarmNames(alarm) + .build(); cw.enableAlarmActions(request); System.out.printf("Successfully enabled actions on alarm %s", alarm); @@ -61,7 +58,6 @@ public static void enableActions(CloudWatchClient cw, String alarm) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } - } + } } // snippet-end:[cloudwatch.java2.enable_alarm_actions.main] - diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/FilterLogEvents.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/FilterLogEvents.java index 6fd4310e479..cb28c7824c3 100644 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/FilterLogEvents.java +++ b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/FilterLogEvents.java @@ -1,23 +1,21 @@ -//snippet-sourcedescription:[FilterLogEvents.java demonstrates how to get log events from Amazon CloudWatch.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudWatch] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.cloudwatch; // snippet-start:[cloudwatch.java2.filter_logs.main] // snippet-start:[cloudwatch.java2.filter_logs.import] +import java.util.List; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException; import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; import software.amazon.awssdk.services.cloudwatchlogs.model.FilterLogEventsRequest; +import software.amazon.awssdk.services.cloudwatchlogs.model.FilteredLogEvent; // snippet-end:[cloudwatch.java2.filter_logs.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,14 +26,14 @@ public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - logGroupName - The name of the log group (for example, myloggroup). - startTime - The start of the time range, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC (for example, 1620940080). - endTime - The end of the time range, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC (for example, 1620949080) - """; + Where: + logGroupName - The name of the log group (for example, myloggroup). + startTime - The start of the time range, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC (for example, 1620940080). + endTime - The end of the time range, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC (for example, 1620949080) + """; if (args.length != 3) { System.out.print(usage); @@ -47,23 +45,24 @@ public static void main(String[] args) { Long endTime = Long.parseLong(args[2]); Region region = Region.US_WEST_2; CloudWatchLogsClient cloudWatchLogsClient = CloudWatchLogsClient.builder() - .region(region) - .build(); + .region(region) + .build(); filterCWLogEvents(cloudWatchLogsClient, logGroupName, startTime, endTime); cloudWatchLogsClient.close(); } - public static void filterCWLogEvents(CloudWatchLogsClient cloudWatchLogsClient, String logGroupName, Long startTime, Long endTime) { + public static void filterCWLogEvents(CloudWatchLogsClient cloudWatchLogsClient, String logGroupName, Long startTime, + Long endTime) { try { FilterLogEventsRequest filterLogEventsRequest = FilterLogEventsRequest.builder() - .logGroupName(logGroupName) - .startTime(startTime) - .endTime(endTime) - .build(); + .logGroupName(logGroupName) + .startTime(startTime) + .endTime(endTime) + .build(); List events = cloudWatchLogsClient.filterLogEvents(filterLogEventsRequest).events(); - for (FilteredLogEvent event: events) { + for (FilteredLogEvent event : events) { System.out.println(event.message()); } diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/GetLogEvents.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/GetLogEvents.java index 67171dfade7..1931da0fb3b 100644 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/GetLogEvents.java +++ b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/GetLogEvents.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[GetLogEvents.java demonstrates how to get log events from Amazon CloudWatch.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudWatch] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.cloudwatch; // snippet-start:[cloudwatch.java2.get_logs.main] @@ -17,7 +12,8 @@ // snippet-end:[cloudwatch.java2.get_logs.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,13 +25,13 @@ public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - logStreamName - The name of the log stream (for example, mystream). - logGroupName - The name of the log group (for example, myloggroup). - """; + Where: + logStreamName - The name of the log stream (for example, mystream). + logGroupName - The name of the log group (for example, myloggroup). + """; if (args.length != 2) { System.out.print(usage); @@ -46,20 +42,21 @@ public static void main(String[] args) { String logGroupName = args[1]; Region region = Region.US_WEST_2; CloudWatchLogsClient cloudWatchLogsClient = CloudWatchLogsClient.builder() - .region(region) - .build(); + .region(region) + .build(); getCWLogEvents(cloudWatchLogsClient, logGroupName, logStreamName); cloudWatchLogsClient.close(); } - public static void getCWLogEvents(CloudWatchLogsClient cloudWatchLogsClient, String logGroupName, String logStreamName) { + public static void getCWLogEvents(CloudWatchLogsClient cloudWatchLogsClient, String logGroupName, + String logStreamName) { try { GetLogEventsRequest getLogEventsRequest = GetLogEventsRequest.builder() - .logGroupName(logGroupName) - .logStreamName(logStreamName) - .startFromHead(true) - .build(); + .logGroupName(logGroupName) + .logStreamName(logStreamName) + .startFromHead(true) + .build(); int logLimit = cloudWatchLogsClient.getLogEvents(getLogEventsRequest).events().size(); for (int c = 0; c < logLimit; c++) { diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/GetMetricData.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/GetMetricData.java index ff53ad0c151..5a4b6d66d06 100644 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/GetMetricData.java +++ b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/GetMetricData.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[PutMetricData.java demonstrates how to get Amazon CloudWatch metric data.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudWatch] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudwatch; @@ -26,7 +20,8 @@ // snippet-end:[cloudwatch.java2.get_metric_data.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -36,44 +31,44 @@ public class GetMetricData { public static void main(String[] args) { Region region = Region.US_EAST_1; CloudWatchClient cw = CloudWatchClient.builder() - .region(region) - .build(); + .region(region) + .build(); - getMetData(cw) ; + getMetData(cw); cw.close(); } - public static void getMetData( CloudWatchClient cw) { + public static void getMetData(CloudWatchClient cw) { try { // Set the date. Instant start = Instant.parse("2019-10-23T10:12:35Z"); Instant endDate = Instant.now(); Metric met = Metric.builder() - .metricName("DiskReadBytes") - .namespace("AWS/EC2") - .build(); + .metricName("DiskReadBytes") + .namespace("AWS/EC2") + .build(); MetricStat metStat = MetricStat.builder() - .stat("Minimum") - .period(60) - .metric(met) - .build(); + .stat("Minimum") + .period(60) + .metric(met) + .build(); MetricDataQuery dataQUery = MetricDataQuery.builder() - .metricStat(metStat) - .id("foo2") - .returnData(true) - .build(); + .metricStat(metStat) + .id("foo2") + .returnData(true) + .build(); List dq = new ArrayList<>(); dq.add(dataQUery); GetMetricDataRequest getMetReq = GetMetricDataRequest.builder() - .maxDatapoints(100) - .startTime(start) - .endTime(endDate) - .metricDataQueries(dq) - .build(); + .maxDatapoints(100) + .startTime(start) + .endTime(endDate) + .metricDataQueries(dq) + .build(); GetMetricDataResponse response = cw.getMetricData(getMetReq); List data = response.metricDataResults(); diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/HelloService.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/HelloService.java index d7e9650b64e..23ff545e025 100644 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/HelloService.java +++ b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/HelloService.java @@ -1,14 +1,8 @@ -//snippet-sourcedescription:[HelloService.java demonstrates how to list Amazon CloudWatch metrics using a paginator.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudWatch] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudwatch; + // snippet-start:[cloudwatch.java2.hello.main] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudwatch.CloudWatchClient; @@ -17,7 +11,8 @@ import software.amazon.awssdk.services.cloudwatch.paginators.ListMetricsIterable; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,12 +22,12 @@ public class HelloService { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - namespace - The namespace to filter against (for example, AWS/EC2).\s - """; + Where: + namespace - The namespace to filter against (for example, AWS/EC2).\s + """; if (args.length != 1) { System.out.println(usage); @@ -42,24 +37,23 @@ public static void main(String[] args) { String namespace = args[0]; Region region = Region.US_EAST_1; CloudWatchClient cw = CloudWatchClient.builder() - .region(region) - .build(); + .region(region) + .build(); listMets(cw, namespace); cw.close(); } - - public static void listMets( CloudWatchClient cw, String namespace) { + public static void listMets(CloudWatchClient cw, String namespace) { try { ListMetricsRequest request = ListMetricsRequest.builder() - .namespace(namespace) - .build(); + .namespace(namespace) + .build(); ListMetricsIterable listRes = cw.listMetricsPaginator(request); listRes.stream() - .flatMap(r -> r.metrics().stream()) - .forEach(metrics -> System.out.println(" Retrieved metric is: " + metrics.metricName())); + .flatMap(r -> r.metrics().stream()) + .forEach(metrics -> System.out.println(" Retrieved metric is: " + metrics.metricName())); } catch (CloudWatchException e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/ListMetrics.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/ListMetrics.java index f16c6245783..e00f6d952db 100644 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/ListMetrics.java +++ b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/ListMetrics.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[ListMetrics.java demonstrates how to list Amazon CloudWatch metrics.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudWatch] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.cloudwatch; // snippet-start:[cloudwatch.java2.list_metrics.main] @@ -19,7 +14,8 @@ // snippet-end:[cloudwatch.java2.list_metrics.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,12 +25,12 @@ public class ListMetrics { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - namespace - The namespace to filter against (for example, AWS/EC2).\s - """; + Where: + namespace - The namespace to filter against (for example, AWS/EC2).\s + """; if (args.length != 1) { System.out.println(usage); @@ -44,47 +40,47 @@ public static void main(String[] args) { String namespace = args[0]; Region region = Region.US_EAST_1; CloudWatchClient cw = CloudWatchClient.builder() - .region(region) - .build(); + .region(region) + .build(); - listMets(cw, namespace) ; + listMets(cw, namespace); cw.close(); } - public static void listMets( CloudWatchClient cw, String namespace) { + public static void listMets(CloudWatchClient cw, String namespace) { boolean done = false; String nextToken = null; try { - while(!done) { + while (!done) { ListMetricsResponse response; if (nextToken == null) { ListMetricsRequest request = ListMetricsRequest.builder() - .namespace(namespace) - .build(); + .namespace(namespace) + .build(); response = cw.listMetrics(request); } else { ListMetricsRequest request = ListMetricsRequest.builder() - .namespace(namespace) - .nextToken(nextToken) - .build(); + .namespace(namespace) + .nextToken(nextToken) + .build(); response = cw.listMetrics(request); } - for (Metric metric : response.metrics()) { - System.out.printf("Retrieved metric %s", metric.metricName()); - System.out.println(); - } + for (Metric metric : response.metrics()) { + System.out.printf("Retrieved metric %s", metric.metricName()); + System.out.println(); + } - if(response.nextToken() == null) { - done = true; - } else { - nextToken = response.nextToken(); + if (response.nextToken() == null) { + done = true; + } else { + nextToken = response.nextToken(); + } } - } } catch (CloudWatchException e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutEvents.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutEvents.java index 3c6f555231e..94b33716d99 100644 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutEvents.java +++ b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutEvents.java @@ -1,10 +1,6 @@ -//snippet-sourcedescription:[PutEvents.java demonstrates how to put a sample CloudWatch event.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudWatch] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.cloudwatch; // snippet-start:[cloudwatch.java2.put_events.main] @@ -16,7 +12,8 @@ // snippet-end:[cloudwatch.java2.put_events.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -26,12 +23,12 @@ public class PutEvents { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - resourceArn - An Amazon Resource Name (ARN) related to the events. - """; + Where: + resourceArn - An Amazon Resource Name (ARN) related to the events. + """; if (args.length != 1) { System.out.println(usage); @@ -40,27 +37,26 @@ public static void main(String[] args) { String resourceArn = args[0]; CloudWatchEventsClient cwe = CloudWatchEventsClient.builder() - .build(); + .build(); - putCWEvents(cwe, resourceArn ); + putCWEvents(cwe, resourceArn); cwe.close(); } - public static void putCWEvents(CloudWatchEventsClient cwe, String resourceArn ) { + public static void putCWEvents(CloudWatchEventsClient cwe, String resourceArn) { try { - final String EVENT_DETAILS = - "{ \"key1\": \"value1\", \"key2\": \"value2\" }"; + final String EVENT_DETAILS = "{ \"key1\": \"value1\", \"key2\": \"value2\" }"; PutEventsRequestEntry requestEntry = PutEventsRequestEntry.builder() - .detail(EVENT_DETAILS) - .detailType("sampleSubmitted") - .resources(resourceArn) - .source("aws-sdk-java-cloudwatch-example") - .build(); + .detail(EVENT_DETAILS) + .detailType("sampleSubmitted") + .resources(resourceArn) + .source("aws-sdk-java-cloudwatch-example") + .build(); PutEventsRequest request = PutEventsRequest.builder() - .entries(requestEntry) - .build(); + .entries(requestEntry) + .build(); cwe.putEvents(request); System.out.println("Successfully put CloudWatch event"); diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutLogEvents.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutLogEvents.java index 25889ed1ebf..3f3b06ff861 100644 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutLogEvents.java +++ b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutLogEvents.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[PutEvents.java demonstrates how to put a sample CloudWatch event.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudWatch] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.cloudwatch; // snippet-start:[cloudwatch.java2.put_log_events.main] @@ -20,7 +15,8 @@ // snippet-end:[cloudwatch.java2.put_log_events.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,13 +26,13 @@ public class PutLogEvents { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - logGroupName - A log group name. - streamName - A stream name. - """; + Where: + logGroupName - A log group name. + streamName - A stream name. + """; if (args.length != 2) { System.out.println(usage); @@ -46,38 +42,39 @@ public static void main(String[] args) { String logGroupName = args[0]; String streamName = args[1]; CloudWatchLogsClient logsClient = CloudWatchLogsClient.builder() - .build(); + .build(); - putCWLogEvents(logsClient, logGroupName, streamName) ; + putCWLogEvents(logsClient, logGroupName, streamName); logsClient.close(); } public static void putCWLogEvents(CloudWatchLogsClient logsClient, String logGroupName, String streamName) { try { DescribeLogStreamsRequest logStreamRequest = DescribeLogStreamsRequest.builder() - .logGroupName(logGroupName) - .logStreamNamePrefix(streamName) - .build(); + .logGroupName(logGroupName) + .logStreamNamePrefix(streamName) + .build(); DescribeLogStreamsResponse describeLogStreamsResponse = logsClient.describeLogStreams(logStreamRequest); - // Assume that a single stream is returned since a specific stream name was specified in the previous request. + // Assume that a single stream is returned since a specific stream name was + // specified in the previous request. String sequenceToken = describeLogStreamsResponse.logStreams().get(0).uploadSequenceToken(); // Build an input log message to put to CloudWatch. InputLogEvent inputLogEvent = InputLogEvent.builder() - .message("{ \"key1\": \"value1\", \"key2\": \"value2\" }") - .timestamp(System.currentTimeMillis()) - .build(); + .message("{ \"key1\": \"value1\", \"key2\": \"value2\" }") + .timestamp(System.currentTimeMillis()) + .build(); // Specify the request parameters. // Sequence token is required so that the log can be written to the // latest location in the stream. PutLogEventsRequest putLogEventsRequest = PutLogEventsRequest.builder() - .logEvents(Arrays.asList(inputLogEvent)) - .logGroupName(logGroupName) - .logStreamName(streamName) - .sequenceToken(sequenceToken) - .build(); + .logEvents(Arrays.asList(inputLogEvent)) + .logGroupName(logGroupName) + .logStreamName(streamName) + .sequenceToken(sequenceToken) + .build(); logsClient.putLogEvents(putLogEventsRequest); System.out.println("Successfully put CloudWatch log event"); diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutMetricAlarm.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutMetricAlarm.java index cf8fff03228..1fd43ff7ae2 100644 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutMetricAlarm.java +++ b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutMetricAlarm.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[PutMetricAlarm.java demonstrates how to create a new Amazon CloudWatch alarm based on CPU utilization for an instance.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudWatch] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.cloudwatch; // snippet-start:[cloudwatch.java2.put_metric_alarm.main] @@ -21,7 +16,8 @@ // snippet-end:[cloudwatch.java2.put_metric_alarm.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,13 +28,13 @@ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - alarmName - An alarm name to use. - instanceId - An instance Id value . - """; + Where: + alarmName - An alarm name to use. + instanceId - An instance Id value . + """; if (args.length != 2) { System.out.println(usage); @@ -48,33 +44,33 @@ public static void main(String[] args) { String alarmName = args[0]; String instanceId = args[1]; CloudWatchClient cw = CloudWatchClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); - putMetricAlarm(cw, alarmName, instanceId) ; + putMetricAlarm(cw, alarmName, instanceId); cw.close(); } public static void putMetricAlarm(CloudWatchClient cw, String alarmName, String instanceId) { try { Dimension dimension = Dimension.builder() - .name("InstanceId") - .value(instanceId).build(); + .name("InstanceId") + .value(instanceId).build(); PutMetricAlarmRequest request = PutMetricAlarmRequest.builder() - .alarmName(alarmName) - .comparisonOperator(ComparisonOperator.GREATER_THAN_THRESHOLD) - .evaluationPeriods(1) - .metricName("CPUUtilization") - .namespace("AWS/EC2") - .period(60) - .statistic(Statistic.AVERAGE) - .threshold(70.0) - .actionsEnabled(false) - .alarmDescription("Alarm when server CPU utilization exceeds 70%") - .unit(StandardUnit.SECONDS) - .dimensions(dimension) - .build(); + .alarmName(alarmName) + .comparisonOperator(ComparisonOperator.GREATER_THAN_THRESHOLD) + .evaluationPeriods(1) + .metricName("CPUUtilization") + .namespace("AWS/EC2") + .period(60) + .statistic(Statistic.AVERAGE) + .threshold(70.0) + .actionsEnabled(false) + .alarmDescription("Alarm when server CPU utilization exceeds 70%") + .unit(StandardUnit.SECONDS) + .dimensions(dimension) + .build(); cw.putMetricAlarm(request); System.out.printf("Successfully created alarm with name %s", alarmName); diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutMetricData.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutMetricData.java index d64fadfe141..6cf60518e97 100644 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutMetricData.java +++ b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutMetricData.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[PutMetricData.java demonstrates how to put a sample metric data point for a metric defined for a CloudWatch alarm.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudWatch] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudwatch; @@ -25,7 +19,8 @@ // snippet-end:[cloudwatch.java2.put_metric_data.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -35,12 +30,12 @@ public class PutMetricData { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - dataPoint - The value for the metric. - """; + Where: + dataPoint - The value for the metric. + """; if (args.length != 1) { System.out.println(usage); @@ -50,34 +45,34 @@ public static void main(String[] args) { Double dataPoint = Double.parseDouble(args[0]); Region region = Region.US_WEST_2; CloudWatchClient cw = CloudWatchClient.builder() - .region(region) - .build(); + .region(region) + .build(); - putMetData(cw, dataPoint) ; + putMetData(cw, dataPoint); cw.close(); } - public static void putMetData(CloudWatchClient cw, Double dataPoint ) { + public static void putMetData(CloudWatchClient cw, Double dataPoint) { try { Dimension dimension = Dimension.builder() - .name("UNIQUE_PAGES") - .value("URLS") - .build(); + .name("UNIQUE_PAGES") + .value("URLS") + .build(); // Set an Instant object. - String time = ZonedDateTime.now( ZoneOffset.UTC ).format( DateTimeFormatter.ISO_INSTANT ); + String time = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT); Instant instant = Instant.parse(time); MetricDatum datum = MetricDatum.builder() - .metricName("PAGES_VISITED") - .unit(StandardUnit.NONE) - .value(dataPoint) - .timestamp(instant) - .dimensions(dimension).build(); + .metricName("PAGES_VISITED") + .unit(StandardUnit.NONE) + .value(dataPoint) + .timestamp(instant) + .dimensions(dimension).build(); PutMetricDataRequest request = PutMetricDataRequest.builder() - .namespace("SITE/TRAFFIC") - .metricData(datum).build(); + .namespace("SITE/TRAFFIC") + .metricData(datum).build(); cw.putMetricData(request); diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutRule.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutRule.java index a2354463826..826cf129e10 100644 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutRule.java +++ b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutRule.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[PutRule.java demonstrates how to creates a CloudWatch event-routing rule.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudWatch] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudwatch; @@ -18,7 +13,8 @@ // snippet-end:[cloudwatch.java2.put_rule.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,13 +24,13 @@ public class PutRule { public static void main(String[] args) { final String usage = """ - Usage: - roleArn>\s + Usage: + roleArn>\s - Where: - ruleName - A rule name (for example, myrule). - roleArn - A role ARN value (for example, arn:aws:iam::xxxxxx047983:user/MyUser). - """; + Where: + ruleName - A rule name (for example, myrule). + roleArn - A role ARN value (for example, arn:aws:iam::xxxxxx047983:user/MyUser). + """; if (args.length != 2) { System.out.println(usage); @@ -44,28 +40,27 @@ public static void main(String[] args) { String ruleName = args[0]; String roleArn = args[1]; CloudWatchEventsClient cwe = CloudWatchEventsClient.builder() - .build(); + .build(); - putCWRule(cwe, ruleName, roleArn) ; + putCWRule(cwe, ruleName, roleArn); cwe.close(); } public static void putCWRule(CloudWatchEventsClient cwe, String ruleName, String roleArn) { try { PutRuleRequest request = PutRuleRequest.builder() - .name(ruleName) - .roleArn(roleArn) - .scheduleExpression("rate(5 minutes)") - .state(RuleState.ENABLED) - .build(); + .name(ruleName) + .roleArn(roleArn) + .scheduleExpression("rate(5 minutes)") + .state(RuleState.ENABLED) + .build(); PutRuleResponse response = cwe.putRule(request); System.out.printf( "Successfully created CloudWatch events rule %s with arn %s", roleArn, response.ruleArn()); - } catch ( - CloudWatchException e) { + } catch (CloudWatchException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutSubscriptionFilter.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutSubscriptionFilter.java index e7d513a65c2..222b4fe380a 100644 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutSubscriptionFilter.java +++ b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutSubscriptionFilter.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[PutSubscriptionFilter.java demonstrates how to create an Amazon CloudWatch log subscription filter.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudWatch] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cloudwatch; @@ -18,7 +12,8 @@ // snippet-end:[cloudwatch.java2.put_subscription_filter.import] /** - * Before running this code example, you need to grant permission to CloudWatch Logs the right to execute your Lambda function. + * Before running this code example, you need to grant permission to CloudWatch + * Logs the right to execute your Lambda function. * To perform this task, you can use this CLI command: * * aws lambda add-permission --function-name "lamda1" --statement-id "lamda1" @@ -26,11 +21,14 @@ * --source-arn "arn:aws:logs:us-west-2:111111111111:log-group:testgroup:*" * --source-account "111111111111" * - * Make sure you replace the function name with your function name and replace '111111111111' with your account details. - * For more information, see "Subscription Filters with AWS Lambda" in the Amazon CloudWatch Logs Guide. + * Make sure you replace the function name with your function name and replace + * '111111111111' with your account details. + * For more information, see "Subscription Filters with AWS Lambda" in the + * Amazon CloudWatch Logs Guide. * * - * Also, before running this Java V2 code example,set up your development environment,including your credentials. + * Also, before running this Java V2 code example,set up your development + * environment,including your credentials. * * For more information,see the following documentation topic: * @@ -42,15 +40,15 @@ public class PutSubscriptionFilter { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - filter - A filter name (for example, myfilter). - pattern - A filter pattern (for example, ERROR). - logGroup - A log group name (testgroup). - functionArn - An AWS Lambda function ARN (for example, arn:aws:lambda:us-west-2:111111111111:function:lambda1) . - """; + Where: + filter - A filter name (for example, myfilter). + pattern - A filter pattern (for example, ERROR). + logGroup - A log group name (testgroup). + functionArn - An AWS Lambda function ARN (for example, arn:aws:lambda:us-west-2:111111111111:function:lambda1) . + """; if (args.length != 4) { System.out.println(usage); @@ -63,26 +61,26 @@ public static void main(String[] args) { String functionArn = args[3]; Region region = Region.US_WEST_2; CloudWatchLogsClient cwl = CloudWatchLogsClient.builder() - .region(region) - .build(); + .region(region) + .build(); - putSubFilters(cwl, filter, pattern, logGroup, functionArn ) ; + putSubFilters(cwl, filter, pattern, logGroup, functionArn); cwl.close(); } public static void putSubFilters(CloudWatchLogsClient cwl, - String filter, - String pattern, - String logGroup, - String functionArn) { + String filter, + String pattern, + String logGroup, + String functionArn) { try { PutSubscriptionFilterRequest request = PutSubscriptionFilterRequest.builder() - .filterName(filter) - .filterPattern(pattern) - .logGroupName(logGroup) - .destinationArn(functionArn) - .build(); + .filterName(filter) + .filterPattern(pattern) + .logGroupName(logGroup) + .destinationArn(functionArn) + .build(); cwl.putSubscriptionFilter(request); System.out.printf( @@ -96,4 +94,3 @@ public static void putSubFilters(CloudWatchLogsClient cwl, } } // snippet-end:[cloudwatch.java2.put_subscription_filter.main] - diff --git a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutTargets.java b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutTargets.java index 54745937d24..ea8b5b569c4 100644 --- a/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutTargets.java +++ b/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutTargets.java @@ -1,13 +1,7 @@ -//snippet-sourcedescription:[PutTargets.java demonstrates how to creates an Amazon CloudWatch event-routing rule target.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon CloudWatch] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - - package com.example.cloudwatch; +package com.example.cloudwatch; // snippet-start:[cloudwatch.java2.put_targets.main] // snippet-start:[cloudwatch.java2.put_targets.import] @@ -18,7 +12,8 @@ // snippet-end:[cloudwatch.java2.put_targets.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -28,14 +23,14 @@ public class PutTargets { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - ruleName - A rule name (for example, myrule). - functionArn - An AWS Lambda function ARN (for example, arn:aws:lambda:us-west-2:xxxxxx047983:function:lamda1). - targetId - A target id value. - """; + Where: + ruleName - A rule name (for example, myrule). + functionArn - An AWS Lambda function ARN (for example, arn:aws:lambda:us-west-2:xxxxxx047983:function:lamda1). + targetId - A target id value. + """; if (args.length != 3) { System.out.println(usage); @@ -46,28 +41,28 @@ public static void main(String[] args) { String functionArn = args[1]; String targetId = args[2]; CloudWatchEventsClient cwe = CloudWatchEventsClient.builder() - .build(); + .build(); putCWTargets(cwe, ruleName, functionArn, targetId); cwe.close(); } - public static void putCWTargets(CloudWatchEventsClient cwe, String ruleName, String functionArn, String targetId ) { + public static void putCWTargets(CloudWatchEventsClient cwe, String ruleName, String functionArn, String targetId) { try { Target target = Target.builder() - .arn(functionArn) - .id(targetId) - .build(); + .arn(functionArn) + .id(targetId) + .build(); PutTargetsRequest request = PutTargetsRequest.builder() - .targets(target) - .rule(ruleName) - .build(); + .targets(target) + .rule(ruleName) + .build(); cwe.putTargets(request); System.out.printf( - "Successfully created CloudWatch events target for rule %s", - ruleName); + "Successfully created CloudWatch events target for rule %s", + ruleName); } catch (CloudWatchException e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/cloudwatch/src/test/java/CloudWatchTest.java b/javav2/example_code/cloudwatch/src/test/java/CloudWatchTest.java index a08b1af5b05..dce37ebdf93 100644 --- a/javav2/example_code/cloudwatch/src/test/java/CloudWatchTest.java +++ b/javav2/example_code/cloudwatch/src/test/java/CloudWatchTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.cloudwatch.DeleteAlarm; import com.google.gson.Gson; @@ -27,20 +25,20 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class CloudWatchTest { - private static CloudWatchClient cw ; - private static CloudWatchLogsClient cloudWatchLogsClient ; + private static CloudWatchClient cw; + private static CloudWatchLogsClient cloudWatchLogsClient; private static CloudWatchEventsClient cwe; - private static String logGroup=""; - private static String alarmName=""; - private static String streamName =""; + private static String logGroup = ""; + private static String alarmName = ""; + private static String streamName = ""; private static String metricId = ""; - private static String instanceId=""; + private static String instanceId = ""; private static String ruleResource = ""; - private static String filterName=""; - private static String destinationArn=""; - private static String roleArn =""; - private static String ruleArn =""; - private static String namespace =""; + private static String filterName = ""; + private static String destinationArn = ""; + private static String roleArn = ""; + private static String ruleArn = ""; + private static String namespace = ""; private static String filterPattern = ""; private static String ruleName = ""; private static String myDateSc = ""; @@ -54,19 +52,19 @@ public class CloudWatchTest { @BeforeAll public static void setUp() throws IOException { cw = CloudWatchClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); cloudWatchLogsClient = CloudWatchLogsClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); cwe = CloudWatchEventsClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -82,60 +80,63 @@ public static void setUp() throws IOException { roleArn = values.getRoleArn(); filterPattern = values.getFilterPattern(); instanceId = values.getInstanceId(); - ruleName = values.getRuleName(); + ruleName = values.getRuleName(); ruleArn = values.getRuleArn(); namespace = values.getNamespace(); - myDateSc= values.myDateSc; - costDateWeekSc= values.getCostDateWeekSc(); + myDateSc = values.myDateSc; + costDateWeekSc = values.getCostDateWeekSc(); dashboardNameSc = values.getDashboardNameSc(); - dashboardJsonSc= values.getDashboardJsonSc(); - dashboardAddSc= values.getDashboardAddSc(); - settingsSc= values.getSettingsSc(); - metricImageSc= values.getMetricImageSc(); - - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - try (InputStream input = CloudWatchTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - // Populate the data members required for all tests - prop.load(input); - logGroup = prop.getProperty("logGroup"); - alarmName = prop.getProperty("alarmName"); - streamName = prop.getProperty("streamName"); - ruleResource = prop.getProperty("ruleResource"); - metricId = prop.getProperty("metricId"); - filterName = prop.getProperty("filterName"); - destinationArn = prop.getProperty("destinationArn"); - roleArn= prop.getProperty("roleArn"); - filterPattern= prop.getProperty("filterPattern"); - instanceId= prop.getProperty("instanceId"); - ruleName= prop.getProperty("ruleName"); - ruleArn= prop.getProperty("ruleArn"); - namespace= prop.getProperty("namespace"); - myDateSc= prop.getProperty("myDateSc"); - costDateWeekSc= prop.getProperty("costDateWeekSc"); - dashboardNameSc= prop.getProperty("dashboardNameSc"); - dashboardJsonSc= prop.getProperty("dashboardJsonSc"); - dashboardAddSc= prop.getProperty("dashboardAddSc"); - settingsSc= prop.getProperty("settingsSc"); - metricImageSc= prop.getProperty("metricImageSc"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + dashboardJsonSc = values.getDashboardJsonSc(); + dashboardAddSc = values.getDashboardAddSc(); + settingsSc = values.getSettingsSc(); + metricImageSc = values.getMetricImageSc(); + + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * try (InputStream input = + * CloudWatchTest.class.getClassLoader().getResourceAsStream("config.properties" + * )) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * // Populate the data members required for all tests + * prop.load(input); + * logGroup = prop.getProperty("logGroup"); + * alarmName = prop.getProperty("alarmName"); + * streamName = prop.getProperty("streamName"); + * ruleResource = prop.getProperty("ruleResource"); + * metricId = prop.getProperty("metricId"); + * filterName = prop.getProperty("filterName"); + * destinationArn = prop.getProperty("destinationArn"); + * roleArn= prop.getProperty("roleArn"); + * filterPattern= prop.getProperty("filterPattern"); + * instanceId= prop.getProperty("instanceId"); + * ruleName= prop.getProperty("ruleName"); + * ruleArn= prop.getProperty("ruleArn"); + * namespace= prop.getProperty("namespace"); + * myDateSc= prop.getProperty("myDateSc"); + * costDateWeekSc= prop.getProperty("costDateWeekSc"); + * dashboardNameSc= prop.getProperty("dashboardNameSc"); + * dashboardJsonSc= prop.getProperty("dashboardJsonSc"); + * dashboardAddSc= prop.getProperty("dashboardAddSc"); + * settingsSc= prop.getProperty("settingsSc"); + * metricImageSc= prop.getProperty("metricImageSc"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @Tag("IntegrationTest") @Order(1) public void CreateAlarm() { - assertDoesNotThrow(() ->PutMetricAlarm.putMetricAlarm(cw, alarmName,instanceId)); + assertDoesNotThrow(() -> PutMetricAlarm.putMetricAlarm(cw, alarmName, instanceId)); System.out.println(" Test 1 passed"); } @@ -143,116 +144,116 @@ public void CreateAlarm() { @Tag("IntegrationTest") @Order(2) public void DescribeAlarms() { - assertDoesNotThrow(() ->DescribeAlarms.desCWAlarms(cw)); - System.out.println("Test 2 passed"); + assertDoesNotThrow(() -> DescribeAlarms.desCWAlarms(cw)); + System.out.println("Test 2 passed"); } @Test @Tag("IntegrationTest") @Order(3) public void DescribeSubscriptionFilters() { - assertDoesNotThrow(() ->DescribeSubscriptionFilters.describeFilters(cloudWatchLogsClient,logGroup)); - System.out.println(" Test 3 passed"); + assertDoesNotThrow(() -> DescribeSubscriptionFilters.describeFilters(cloudWatchLogsClient, logGroup)); + System.out.println(" Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) public void DisableAlarmActions() { - assertDoesNotThrow(() ->DisableAlarmActions.disableActions(cw, alarmName)); - System.out.println("\n Test 4 passed"); + assertDoesNotThrow(() -> DisableAlarmActions.disableActions(cw, alarmName)); + System.out.println("\n Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) public void EnableAlarmActions() { - assertDoesNotThrow(() ->EnableAlarmActions.enableActions(cw, alarmName)); - System.out.println("\n Test 6 passed"); + assertDoesNotThrow(() -> EnableAlarmActions.enableActions(cw, alarmName)); + System.out.println("\n Test 6 passed"); } @Test @Tag("IntegrationTest") @Order(6) void PutCloudWatchEvent() { - assertDoesNotThrow(() -> PutEvents.putCWEvents(cwe,ruleResource)); - System.out.println("\n Test 6 passed"); + assertDoesNotThrow(() -> PutEvents.putCWEvents(cwe, ruleResource)); + System.out.println("\n Test 6 passed"); } @Test @Tag("IntegrationTest") @Order(7) public void GetMetricData() { - assertDoesNotThrow(() ->GetMetricData.getMetData(cw)); - System.out.println("\n Test 7 passed"); + assertDoesNotThrow(() -> GetMetricData.getMetData(cw)); + System.out.println("\n Test 7 passed"); } @Test @Tag("IntegrationTest") @Order(8) - public void PutRule() { - assertDoesNotThrow(() ->PutRule.putCWRule(cwe, ruleName, ruleArn)); + public void PutRule() { + assertDoesNotThrow(() -> PutRule.putCWRule(cwe, ruleName, ruleArn)); System.out.println("\n Test 8 passed"); - } + } @Test @Tag("IntegrationTest") @Order(9) - public void ListMetrics() { - assertDoesNotThrow(() ->ListMetrics.listMets(cw, namespace)); - System.out.println("\n Test 9 passed"); - } + public void ListMetrics() { + assertDoesNotThrow(() -> ListMetrics.listMets(cw, namespace)); + System.out.println("\n Test 9 passed"); + } @Test @Tag("IntegrationTest") @Order(10) public void DeleteAlarm() { - assertDoesNotThrow(() ->DeleteAlarm.deleteCWAlarm(cw, alarmName)); + assertDoesNotThrow(() -> DeleteAlarm.deleteCWAlarm(cw, alarmName)); System.out.println("\n Test 10 passed"); } - @Test @Tag("IntegrationTest") @Order(11) public void CloudWatchScenarioTest() { Double dataPoint = Double.parseDouble("10.0"); - System.out.println("1. List at least five available unique namespaces from Amazon CloudWatch. Select one from the list."); + System.out.println( + "1. List at least five available unique namespaces from Amazon CloudWatch. Select one from the list."); ArrayList list = CloudWatchScenario.listNameSpaces(cw); - for (int z=0; z<5; z++) { - int index = z+1; - System.out.println(" " +index +". " +list.get(z)); + for (int z = 0; z < 5; z++) { + int index = z + 1; + System.out.println(" " + index + ". " + list.get(z)); } String selectedNamespace = ""; String selectedMetrics = ""; int num = 2; - if (1 <= num && num <= 5){ - selectedNamespace = list.get(num-1); + if (1 <= num && num <= 5) { + selectedNamespace = list.get(num - 1); } else { System.out.println("You did not select a valid option."); System.exit(1); } - System.out.println("You selected "+selectedNamespace); + System.out.println("You selected " + selectedNamespace); System.out.println("2. List available metrics within the selected namespace and select one from the list."); ArrayList metList = CloudWatchScenario.listMets(cw, selectedNamespace); - for (int z=0; z<5; z++) { - int index = z+1; - System.out.println(" " +index +". " +metList.get(z)); + for (int z = 0; z < 5; z++) { + int index = z + 1; + System.out.println(" " + index + ". " + metList.get(z)); } num = 1; - if (1 <= num && num <= 5){ - selectedMetrics = metList.get(num-1); + if (1 <= num && num <= 5) { + selectedMetrics = metList.get(num - 1); } else { System.out.println("You did not select a valid option."); System.exit(1); } - System.out.println("You selected "+selectedMetrics); - Dimension myDimension = CloudWatchScenario.getSpecificMet( cw, selectedNamespace); + System.out.println("You selected " + selectedMetrics); + Dimension myDimension = CloudWatchScenario.getSpecificMet(cw, selectedNamespace); System.out.println("3. Get statistics for the selected metric over the last day."); - String metricOption=""; + String metricOption = ""; ArrayList statTypes = new ArrayList<>(); statTypes.add("SampleCount"); statTypes.add("Average"); @@ -260,19 +261,20 @@ public void CloudWatchScenarioTest() { statTypes.add("Minimum"); statTypes.add("Maximum"); - for (int t=0; t<5; t++){ - System.out.println(" " +(t+1) +". "+statTypes.get(t)); + for (int t = 0; t < 5; t++) { + System.out.println(" " + (t + 1) + ". " + statTypes.get(t)); } System.out.println("Select a metric statistic by entering a number from the preceding list:"); num = Integer.parseInt("2"); - if (1 <= num && num <= 5){ - metricOption = statTypes.get(num-1); + if (1 <= num && num <= 5) { + metricOption = statTypes.get(num - 1); } else { System.out.println("You did not select a valid option."); System.exit(1); } - System.out.println("You selected "+metricOption); - CloudWatchScenario.getAndDisplayMetricStatistics(cw, selectedNamespace, selectedMetrics, metricOption, myDateSc, myDimension); + System.out.println("You selected " + metricOption); + CloudWatchScenario.getAndDisplayMetricStatistics(cw, selectedNamespace, selectedMetrics, metricOption, myDateSc, + myDimension); System.out.println("4. Get CloudWatch estimated billing for the last week."); CloudWatchScenario.getMetricStatistics(cw, costDateWeekSc); @@ -291,9 +293,9 @@ public void CloudWatchScenarioTest() { System.out.println("10. Describe ten current alarms."); CloudWatchScenario.describeAlarms(cw); System.out.println("11. Get current data for new custom metric."); - CloudWatchScenario.getCustomMetricData(cw,settingsSc); + CloudWatchScenario.getCustomMetricData(cw, settingsSc); System.out.println("12. Push data into the custom metric to trigger the alarm."); - CloudWatchScenario.addMetricDataForAlarm(cw, settingsSc) ; + CloudWatchScenario.addMetricDataForAlarm(cw, settingsSc); System.out.println("13. Check the alarm state using the action DescribeAlarmsForMetric."); CloudWatchScenario.checkForMetricAlarm(cw, settingsSc); System.out.println("14. Get alarm history for the new alarm."); @@ -311,17 +313,16 @@ public void CloudWatchScenarioTest() { System.out.println("The Amazon CloudWatch example scenario is complete."); } - private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/cloudwatch"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -449,9 +450,4 @@ public String getMetricImageSc() { return metricImageSc; } } - } - - - - - +} diff --git a/javav2/example_code/codecommit/src/main/java/com/example/commit/CreateBranch.java b/javav2/example_code/codecommit/src/main/java/com/example/commit/CreateBranch.java index 0a3f4a770c7..51a52e35457 100644 --- a/javav2/example_code/codecommit/src/main/java/com/example/commit/CreateBranch.java +++ b/javav2/example_code/codecommit/src/main/java/com/example/commit/CreateBranch.java @@ -1,12 +1,6 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[CreateBranch.java demonstrates how to create a branch.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CodeCommit] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.commit; // snippet-start:[codecommit.java2.create_branch.main] @@ -18,7 +12,8 @@ // snippet-end:[codecommit.java2.create_branch.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -29,14 +24,14 @@ public class CreateBranch { public static void main(String[] args) { final String USAGE = """ - Usage: - \s + Usage: + \s - Where: - repoName - the name of the repository. - branchName - the name of the branch. - commitId - The ID of the commit to point the new branch to.\s - """; + Where: + repoName - the name of the repository. + branchName - the name of the branch. + commitId - The ID of the commit to point the new branch to.\s + """; if (args.length != 3) { System.out.println(USAGE); @@ -49,24 +44,24 @@ public static void main(String[] args) { Region region = Region.US_EAST_1; CodeCommitClient codeCommitClient = CodeCommitClient.builder() - .region(region) - .build(); + .region(region) + .build(); createSpecificBranch(codeCommitClient, repoName, branchName, commitId); codeCommitClient.close(); } public static void createSpecificBranch(CodeCommitClient codeCommitClient, - String repoName, - String branchName, - String commitId) { + String repoName, + String branchName, + String commitId) { try { CreateBranchRequest branchRequest = CreateBranchRequest.builder() - .branchName(branchName) - .repositoryName(repoName) - .commitId(commitId) - .build(); + .branchName(branchName) + .repositoryName(repoName) + .commitId(commitId) + .build(); codeCommitClient.createBranch(branchRequest); System.out.println("Branch " + branchName + " was created"); diff --git a/javav2/example_code/codecommit/src/main/java/com/example/commit/CreatePullRequest.java b/javav2/example_code/codecommit/src/main/java/com/example/commit/CreatePullRequest.java index 9135fe73ca8..48dcfd4b250 100644 --- a/javav2/example_code/codecommit/src/main/java/com/example/commit/CreatePullRequest.java +++ b/javav2/example_code/codecommit/src/main/java/com/example/commit/CreatePullRequest.java @@ -1,12 +1,6 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[CreatePullRequest.java demonstrates how to create a pull request.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CodeCommit] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.commit; // snippet-start:[codecommit.java2.create_pr.main] @@ -22,7 +16,8 @@ // snippet-end:[codecommit.java2.create_pr.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -33,14 +28,14 @@ public class CreatePullRequest { public static void main(String[] args) { final String USAGE = """ - Usage: - \s + Usage: + \s - Where: - repoName - the name of the repository. - destinationReference - the branch of the repository where the pull request changes are merged. - sourceReference - the branch of the repository that contains the changes for the pull request. - """; + Where: + repoName - the name of the repository. + destinationReference - the branch of the repository where the pull request changes are merged. + sourceReference - the branch of the repository that contains the changes for the pull request. + """; if (args.length != 3) { System.out.println(USAGE); @@ -52,8 +47,8 @@ public static void main(String[] args) { String sourceReference = args[2]; Region region = Region.US_EAST_1; CodeCommitClient codeCommitClient = CodeCommitClient.builder() - .region(region) - .build(); + .region(region) + .build(); String prId = createPR(codeCommitClient, repoName, destinationReference, sourceReference); System.out.println("The pull request id is " + prId); @@ -61,23 +56,23 @@ public static void main(String[] args) { } public static String createPR(CodeCommitClient codeCommitClient, - String repoName, - String destinationReference, - String sourceReference) { + String repoName, + String destinationReference, + String sourceReference) { try { Target target = Target.builder() - .repositoryName(repoName) - .destinationReference(destinationReference) - .sourceReference(sourceReference) - .build(); + .repositoryName(repoName) + .destinationReference(destinationReference) + .sourceReference(sourceReference) + .build(); List myList = new ArrayList<>(); myList.add(target); CreatePullRequestRequest pullRequestRequest = CreatePullRequestRequest.builder() - .description("A Pull request created by the Java API") - .title("Example Pull Request") - .targets(myList) - .build(); + .description("A Pull request created by the Java API") + .title("Example Pull Request") + .targets(myList) + .build(); CreatePullRequestResponse requestResponse = codeCommitClient.createPullRequest(pullRequestRequest); return requestResponse.pullRequest().pullRequestId(); diff --git a/javav2/example_code/codecommit/src/main/java/com/example/commit/CreateRepository.java b/javav2/example_code/codecommit/src/main/java/com/example/commit/CreateRepository.java index 830dfebba77..b2ba4bcf460 100644 --- a/javav2/example_code/codecommit/src/main/java/com/example/commit/CreateRepository.java +++ b/javav2/example_code/codecommit/src/main/java/com/example/commit/CreateRepository.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[CreateRepository.java demonstrates how to create a new repository.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CodeCommit] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.commit; @@ -20,7 +13,8 @@ // snippet-end:[codecommit.java2.create_repo.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -31,12 +25,12 @@ public class CreateRepository { public static void main(String[] args) { final String USAGE = """ - Usage: - \s + Usage: + \s - Where: - repoName - the name of the repository.\s - """; + Where: + repoName - the name of the repository.\s + """; if (args.length != 1) { System.out.println(USAGE); @@ -46,8 +40,8 @@ public static void main(String[] args) { String repoName = args[0]; Region region = Region.US_EAST_1; CodeCommitClient codeCommitClient = CodeCommitClient.builder() - .region(region) - .build(); + .region(region) + .build(); createRepo(codeCommitClient, repoName); codeCommitClient.close(); @@ -56,9 +50,9 @@ public static void main(String[] args) { public static void createRepo(CodeCommitClient codeCommitClient, String repoName) { try { CreateRepositoryRequest repositoryRequest = CreateRepositoryRequest.builder() - .repositoryDescription("Created by the CodeCommit Java API") - .repositoryName(repoName) - .build(); + .repositoryDescription("Created by the CodeCommit Java API") + .repositoryName(repoName) + .build(); CreateRepositoryResponse repositoryResponse = codeCommitClient.createRepository(repositoryRequest); System.out.println("The ARN of the new repository is " + repositoryResponse.repositoryMetadata().arn()); diff --git a/javav2/example_code/codecommit/src/main/java/com/example/commit/DeleteBranch.java b/javav2/example_code/codecommit/src/main/java/com/example/commit/DeleteBranch.java index ea83e5fb222..61e1b27c5a0 100644 --- a/javav2/example_code/codecommit/src/main/java/com/example/commit/DeleteBranch.java +++ b/javav2/example_code/codecommit/src/main/java/com/example/commit/DeleteBranch.java @@ -1,16 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[DeleteBranch.java demonstrates how to delete a branch.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -// snippet-service:[AWS CodeCommit] -// snippet-sourcetype:[full-example] -//snippet-sourcedate:[09/28/2021] -// snippet-sourceauthor:[AWS - scmacdon] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.commit; @@ -23,7 +12,8 @@ // snippet-end:[codecommit.java2.del_branch.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -34,13 +24,13 @@ public class DeleteBranch { public static void main(String[] args) { final String USAGE = """ - Usage: - \s + Usage: + \s - Where: - repoName - the name of the repository. - branchName - the name of the branch.\s - """; + Where: + repoName - the name of the repository. + branchName - the name of the branch.\s + """; if (args.length != 2) { System.out.println(USAGE); @@ -51,8 +41,8 @@ public static void main(String[] args) { String branchName = args[1]; Region region = Region.US_EAST_1; CodeCommitClient codeCommitClient = CodeCommitClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteSpecificBranch(codeCommitClient, repoName, branchName); codeCommitClient.close(); @@ -61,9 +51,9 @@ public static void main(String[] args) { public static void deleteSpecificBranch(CodeCommitClient codeCommitClient, String repoName, String branchName) { try { DeleteBranchRequest branchRequest = DeleteBranchRequest.builder() - .branchName(branchName) - .repositoryName(repoName) - .build(); + .branchName(branchName) + .repositoryName(repoName) + .build(); codeCommitClient.deleteBranch(branchRequest); System.out.println("The " + branchName + " branch was deleted!"); diff --git a/javav2/example_code/codecommit/src/main/java/com/example/commit/DeleteRepository.java b/javav2/example_code/codecommit/src/main/java/com/example/commit/DeleteRepository.java index 1da71daa3d8..8e1244db8e8 100644 --- a/javav2/example_code/codecommit/src/main/java/com/example/commit/DeleteRepository.java +++ b/javav2/example_code/codecommit/src/main/java/com/example/commit/DeleteRepository.java @@ -1,11 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[DeleteRepository.java demonstrates how to delete a repository.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CodeCommit] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.commit; @@ -18,7 +12,8 @@ // snippet-end:[codecommit.java2.del_repo.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -29,12 +24,12 @@ public class DeleteRepository { public static void main(String[] args) { final String USAGE = """ - Usage: - \s + Usage: + \s - Where: - repoName - the name of the repository. - """; + Where: + repoName - the name of the repository. + """; if (args.length != 1) { System.out.println(USAGE); @@ -44,8 +39,8 @@ public static void main(String[] args) { String repoName = args[0]; Region region = Region.US_EAST_1; CodeCommitClient codeCommitClient = CodeCommitClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteRepo(codeCommitClient, repoName); codeCommitClient.close(); @@ -54,8 +49,8 @@ public static void main(String[] args) { public static void deleteRepo(CodeCommitClient codeCommitClient, String repoName) { try { DeleteRepositoryRequest deleteRepositoryRequest = DeleteRepositoryRequest.builder() - .repositoryName(repoName) - .build(); + .repositoryName(repoName) + .build(); codeCommitClient.deleteRepository(deleteRepositoryRequest); diff --git a/javav2/example_code/codecommit/src/main/java/com/example/commit/DescribePullRequestEvents.java b/javav2/example_code/codecommit/src/main/java/com/example/commit/DescribePullRequestEvents.java index 77ee8a3eb55..e4fa2b06e1c 100644 --- a/javav2/example_code/codecommit/src/main/java/com/example/commit/DescribePullRequestEvents.java +++ b/javav2/example_code/codecommit/src/main/java/com/example/commit/DescribePullRequestEvents.java @@ -1,11 +1,6 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[DescribePullRequestEvents.java demonstrates how to obtain information about pull request events.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CodeCommit] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.commit; // snippet-start:[codecommit.java2.describe_pr_events.main] @@ -20,7 +15,8 @@ // snippet-end:[codecommit.java2.describe_pr_events.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -32,12 +28,12 @@ public static void main(String[] args) { final String USAGE = """ - Usage: - \s + Usage: + \s - Where: - prId - the id of the pull request.\s - """; + Where: + prId - the id of the pull request.\s + """; if (args.length != 1) { System.out.println(USAGE); @@ -47,8 +43,8 @@ public static void main(String[] args) { String prId = args[0]; Region region = Region.US_EAST_1; CodeCommitClient codeCommitClient = CodeCommitClient.builder() - .region(region) - .build(); + .region(region) + .build(); describePREvents(codeCommitClient, prId); codeCommitClient.close(); @@ -57,10 +53,11 @@ public static void main(String[] args) { public static void describePREvents(CodeCommitClient codeCommitClient, String prId) { try { DescribePullRequestEventsRequest eventsRequest = DescribePullRequestEventsRequest.builder() - .pullRequestId(prId) - .build(); + .pullRequestId(prId) + .build(); - DescribePullRequestEventsResponse eventsResponse = codeCommitClient.describePullRequestEvents(eventsRequest); + DescribePullRequestEventsResponse eventsResponse = codeCommitClient + .describePullRequestEvents(eventsRequest); List events = eventsResponse.pullRequestEvents(); for (PullRequestEvent event : events) { System.out.println("The event name is: " + event.pullRequestEventType().toString()); diff --git a/javav2/example_code/codecommit/src/main/java/com/example/commit/GetMergeOptions.java b/javav2/example_code/codecommit/src/main/java/com/example/commit/GetMergeOptions.java index 2a59e3bb2ce..391e1f2d8d1 100644 --- a/javav2/example_code/codecommit/src/main/java/com/example/commit/GetMergeOptions.java +++ b/javav2/example_code/codecommit/src/main/java/com/example/commit/GetMergeOptions.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[GetMergeOptions.java demonstrates how to get merge options.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CodeCommit] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.commit; @@ -20,7 +13,8 @@ // snippet-end:[codecommit.java2.get_merge_options.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -30,14 +24,14 @@ public class GetMergeOptions { public static void main(String[] args) { final String USAGE = """ - Usage: - \s + Usage: + \s - Where: - repoName - the name of the repository. - destinationReference - the branch of the repository where the pull request changes are merged. - sourceReference - the branch of the repository that contains the changes for the pull request. - """; + Where: + repoName - the name of the repository. + destinationReference - the branch of the repository where the pull request changes are merged. + sourceReference - the branch of the repository that contains the changes for the pull request. + """; if (args.length != 3) { System.out.println(USAGE); @@ -50,8 +44,8 @@ public static void main(String[] args) { Region region = Region.US_EAST_1; CodeCommitClient codeCommitClient = CodeCommitClient.builder() - .region(region) - .build(); + .region(region) + .build(); String commitId = getMergeValues(codeCommitClient, repoName, destinationReference, sourceReference); System.out.println("The id value is " + commitId); @@ -59,15 +53,15 @@ public static void main(String[] args) { } public static String getMergeValues(CodeCommitClient codeCommitClient, - String repoName, - String destinationReference, - String sourceReference) { + String repoName, + String destinationReference, + String sourceReference) { try { GetMergeOptionsRequest optionsRequest = GetMergeOptionsRequest.builder() - .repositoryName(repoName) - .destinationCommitSpecifier(destinationReference) - .sourceCommitSpecifier(sourceReference) - .build(); + .repositoryName(repoName) + .destinationCommitSpecifier(destinationReference) + .sourceCommitSpecifier(sourceReference) + .build(); GetMergeOptionsResponse response = codeCommitClient.getMergeOptions(optionsRequest); return response.baseCommitId(); diff --git a/javav2/example_code/codecommit/src/main/java/com/example/commit/GetPullRequest.java b/javav2/example_code/codecommit/src/main/java/com/example/commit/GetPullRequest.java index 479a4393b77..c72bf9fb007 100644 --- a/javav2/example_code/codecommit/src/main/java/com/example/commit/GetPullRequest.java +++ b/javav2/example_code/codecommit/src/main/java/com/example/commit/GetPullRequest.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[GetPullRequest.java demonstrates how to obtain information about a pull request.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CodeCommit] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.commit; @@ -20,7 +13,8 @@ // snippet-end:[codecommit.java2.get_pull_request.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -31,12 +25,12 @@ public class GetPullRequest { public static void main(String[] args) { final String USAGE = """ - Usage: - \s + Usage: + \s - Where: - pullRequestId - the id of the pull request.\s - """; + Where: + pullRequestId - the id of the pull request.\s + """; if (args.length != 1) { System.out.println(USAGE); @@ -46,8 +40,8 @@ public static void main(String[] args) { String pullRequestId = args[0]; Region region = Region.US_EAST_1; CodeCommitClient codeCommitClient = CodeCommitClient.builder() - .region(region) - .build(); + .region(region) + .build(); getPR(codeCommitClient, pullRequestId); codeCommitClient.close(); @@ -56,8 +50,8 @@ public static void main(String[] args) { public static void getPR(CodeCommitClient codeCommitClient, String pullRequestId) { try { GetPullRequestRequest pullRequestRequest = GetPullRequestRequest.builder() - .pullRequestId(pullRequestId) - .build(); + .pullRequestId(pullRequestId) + .build(); GetPullRequestResponse pullResponse = codeCommitClient.getPullRequest(pullRequestRequest); System.out.println("The title of the pull request is " + pullResponse.pullRequest().title()); diff --git a/javav2/example_code/codecommit/src/main/java/com/example/commit/GetRepository.java b/javav2/example_code/codecommit/src/main/java/com/example/commit/GetRepository.java index 8df012d0911..aba9db325e2 100644 --- a/javav2/example_code/codecommit/src/main/java/com/example/commit/GetRepository.java +++ b/javav2/example_code/codecommit/src/main/java/com/example/commit/GetRepository.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[GetRepository.java demonstrates how to obtain information about a repository.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CodeCommit] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.commit; @@ -20,7 +13,8 @@ // snippet-end:[codecommit.java2.get_repo.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -31,12 +25,12 @@ public class GetRepository { public static void main(String[] args) { final String USAGE = """ - Usage: - \s + Usage: + \s - Where: - repoName - the name of the repository. - """; + Where: + repoName - the name of the repository. + """; if (args.length != 1) { System.out.println(USAGE); @@ -46,8 +40,8 @@ public static void main(String[] args) { String repoName = args[0]; Region region = Region.US_EAST_1; CodeCommitClient codeCommitClient = CodeCommitClient.builder() - .region(region) - .build(); + .region(region) + .build(); getRepInformation(codeCommitClient, repoName); codeCommitClient.close(); @@ -56,8 +50,8 @@ public static void main(String[] args) { public static void getRepInformation(CodeCommitClient codeCommitClient, String repoName) { try { GetRepositoryRequest repositoryRequest = GetRepositoryRequest.builder() - .repositoryName(repoName) - .build(); + .repositoryName(repoName) + .build(); GetRepositoryResponse repositoryResponse = codeCommitClient.getRepository(repositoryRequest); System.out.println("The ARN of the " + repoName + " is " + repositoryResponse.repositoryMetadata().arn()); diff --git a/javav2/example_code/codecommit/src/main/java/com/example/commit/ListRepositories.java b/javav2/example_code/codecommit/src/main/java/com/example/commit/ListRepositories.java index cd538836575..1761a368c26 100644 --- a/javav2/example_code/codecommit/src/main/java/com/example/commit/ListRepositories.java +++ b/javav2/example_code/codecommit/src/main/java/com/example/commit/ListRepositories.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[ListRepositories.java demonstrates how to obtain information about all repositories.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CodeCommit] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.commit; @@ -21,7 +14,8 @@ // snippet-end:[codecommit.java2.get_repos.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -32,8 +26,8 @@ public class ListRepositories { public static void main(String[] args) { Region region = Region.US_EAST_1; CodeCommitClient codeCommitClient = CodeCommitClient.builder() - .region(region) - .build(); + .region(region) + .build(); listRepos(codeCommitClient); codeCommitClient.close(); @@ -55,4 +49,3 @@ public static void listRepos(CodeCommitClient codeCommitClient) { } } // snippet-end:[codecommit.java2.get_repos.main] - diff --git a/javav2/example_code/codecommit/src/main/java/com/example/commit/MergeBranches.java b/javav2/example_code/codecommit/src/main/java/com/example/commit/MergeBranches.java index 7e499ed2e0f..9421f43293e 100644 --- a/javav2/example_code/codecommit/src/main/java/com/example/commit/MergeBranches.java +++ b/javav2/example_code/codecommit/src/main/java/com/example/commit/MergeBranches.java @@ -1,12 +1,6 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[MergeBranches.java demonstrates how to merge two branches.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CodeCommit] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.commit; // snippet-start:[codecommit.java2.merge.main] @@ -19,7 +13,8 @@ // snippet-end:[codecommit.java2.merge.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -30,15 +25,15 @@ public class MergeBranches { public static void main(String[] args) { final String USAGE = """ - Usage: - + Usage: + - Where: - repoName - the name of the repository. - targetBranch - the branch where the merge is applied. - sourceReference - the branch of the repository that contains the changes. - destinationCommitId - a full commit ID. - """; + Where: + repoName - the name of the repository. + targetBranch - the branch where the merge is applied. + sourceReference - the branch of the repository that contains the changes. + destinationCommitId - a full commit ID. + """; if (args.length != 4) { System.out.println(USAGE); @@ -55,26 +50,27 @@ public static void main(String[] args) { .region(region) .build(); - merge(codeCommitClient, repoName, targetBranch, sourceReference, destinationCommitId) ; + merge(codeCommitClient, repoName, targetBranch, sourceReference, destinationCommitId); codeCommitClient.close(); } public static void merge(CodeCommitClient codeCommitClient, - String repoName, - String targetBranch, - String sourceReference, - String destinationCommitId) { + String repoName, + String targetBranch, + String sourceReference, + String destinationCommitId) { try { MergeBranchesByFastForwardRequest fastForwardRequest = MergeBranchesByFastForwardRequest.builder() - .destinationCommitSpecifier(destinationCommitId) - .targetBranch(targetBranch) - .sourceCommitSpecifier(sourceReference) - .repositoryName(repoName) - .build(); + .destinationCommitSpecifier(destinationCommitId) + .targetBranch(targetBranch) + .sourceCommitSpecifier(sourceReference) + .repositoryName(repoName) + .build(); - MergeBranchesByFastForwardResponse response = codeCommitClient.mergeBranchesByFastForward(fastForwardRequest); - System.out.println("The commit id is "+response.commitId()); + MergeBranchesByFastForwardResponse response = codeCommitClient + .mergeBranchesByFastForward(fastForwardRequest); + System.out.println("The commit id is " + response.commitId()); } catch (CodeCommitException e) { System.err.println(e.getMessage()); diff --git a/javav2/example_code/codecommit/src/main/java/com/example/commit/PutFile.java b/javav2/example_code/codecommit/src/main/java/com/example/commit/PutFile.java index 79b1c756ac8..67d51766f13 100644 --- a/javav2/example_code/codecommit/src/main/java/com/example/commit/PutFile.java +++ b/javav2/example_code/codecommit/src/main/java/com/example/commit/PutFile.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[PutFile.java demonstrates how to upload a file to a branch.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS CodeCommit] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.commit; @@ -25,30 +18,30 @@ // snippet-end:[codecommit.java2.put_file.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ - public class PutFile { public static void main(String[] args) { final String USAGE = """ - Usage: - + Usage: + - Where: - repoName - the name of the repository. - branchName - the name of the branch. - filePath - the location of the file on the local drive (i.e., C:/AWS/uploadGlacier.txt). - email - the email of the user whom uploads the file. - name - the name of the user. - repoPath - the location in the repo to store the file. - commitId - the full commit ID of the head commit in the branch (you can retrieve this value from the AWS CodeCommit Console). - """; + Where: + repoName - the name of the repository. + branchName - the name of the branch. + filePath - the location of the file on the local drive (i.e., C:/AWS/uploadGlacier.txt). + email - the email of the user whom uploads the file. + name - the name of the user. + repoPath - the location in the repo to store the file. + commitId - the full commit ID of the head commit in the branch (you can retrieve this value from the AWS CodeCommit Console). + """; if (args.length != 7) { System.out.println(USAGE); @@ -65,36 +58,36 @@ public static void main(String[] args) { Region region = Region.US_EAST_1; CodeCommitClient codeCommitClient = CodeCommitClient.builder() - .region(region) - .build(); + .region(region) + .build(); uploadFile(codeCommitClient, filePath, repoName, branchName, email, name, repoPath, commitId); codeCommitClient.close(); } public static void uploadFile(CodeCommitClient codeCommitClient, - String filePath, - String repoName, - String branchName, - String email, - String name, - String repoPath, - String commitId) { + String filePath, + String repoName, + String branchName, + String email, + String name, + String repoPath, + String commitId) { try { File myFile = new File(filePath); InputStream is = new FileInputStream(myFile); SdkBytes fileToUpload = SdkBytes.fromInputStream(is); PutFileRequest fileRequest = PutFileRequest.builder() - .fileContent(fileToUpload) - .repositoryName(repoName) - .commitMessage("Uploaded via the Java API") - .branchName(branchName) - .filePath(repoPath) - .parentCommitId(commitId) - .email(email) - .name(name) - .build(); + .fileContent(fileToUpload) + .repositoryName(repoName) + .commitMessage("Uploaded via the Java API") + .branchName(branchName) + .filePath(repoPath) + .parentCommitId(commitId) + .email(email) + .name(name) + .build(); PutFileResponse fileResponse = codeCommitClient.putFile(fileRequest); System.out.println("The commit ID is " + fileResponse.commitId()); diff --git a/javav2/example_code/codecommit/src/test/java/CodeCommitTest.java b/javav2/example_code/codecommit/src/test/java/CodeCommitTest.java index 29236eee22f..1a942a1c6b2 100644 --- a/javav2/example_code/codecommit/src/test/java/CodeCommitTest.java +++ b/javav2/example_code/codecommit/src/test/java/CodeCommitTest.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.commit.*; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.codecommit.CodeCommitClient; diff --git a/javav2/example_code/codedeploy/src/main/java/com/example/deploy/CreateApplication.java b/javav2/example_code/codedeploy/src/main/java/com/example/deploy/CreateApplication.java index d26d486e45c..f929f9ec88d 100644 --- a/javav2/example_code/codedeploy/src/main/java/com/example/deploy/CreateApplication.java +++ b/javav2/example_code/codedeploy/src/main/java/com/example/deploy/CreateApplication.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[CreateApplication.java demonstrates how to create an application.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS CodeDeploy] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.deploy; // snippet-start:[codedeploy.java2.create_app.main] @@ -19,7 +14,8 @@ // snippet-end:[codedeploy.java2.create_app.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,12 +27,12 @@ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - appName - The name of the application.\s - """; + Where: + appName - The name of the application.\s + """; if (args.length != 1) { System.out.println(usage); @@ -46,8 +42,8 @@ public static void main(String[] args) { String appName = args[0]; Region region = Region.US_EAST_1; CodeDeployClient deployClient = CodeDeployClient.builder() - .region(region) - .build(); + .region(region) + .build(); createApp(deployClient, appName); deployClient.close(); @@ -56,9 +52,9 @@ public static void main(String[] args) { public static void createApp(CodeDeployClient deployClient, String appName) { try { CreateApplicationRequest applicationRequest = CreateApplicationRequest.builder() - .applicationName(appName) - .computePlatform(ComputePlatform.SERVER) - .build(); + .applicationName(appName) + .computePlatform(ComputePlatform.SERVER) + .build(); CreateApplicationResponse applicationResponse = deployClient.createApplication(applicationRequest); String appId = applicationResponse.applicationId(); diff --git a/javav2/example_code/codedeploy/src/main/java/com/example/deploy/CreateDeploymentGroup.java b/javav2/example_code/codedeploy/src/main/java/com/example/deploy/CreateDeploymentGroup.java index c099075ac13..b5b01bcbf97 100644 --- a/javav2/example_code/codedeploy/src/main/java/com/example/deploy/CreateDeploymentGroup.java +++ b/javav2/example_code/codedeploy/src/main/java/com/example/deploy/CreateDeploymentGroup.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[CreateDeploymentGroup.java demonstrates how to create a deployment group.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS CodeDeploy] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.deploy; @@ -23,9 +18,10 @@ // snippet-end:[codedeploy.java2.create_deployment_group.import] /** - * Before running this code example, it's recommended that you go through the CodeDeploy tutorials at: + * Before running this code example, it's recommended that you go through the + * CodeDeploy tutorials at: * - * https://docs.aws.amazon.com/codedeploy/latest/userguide/tutorials.html + * https://docs.aws.amazon.com/codedeploy/latest/userguide/tutorials.html * * Also, set up your development environment, including your credentials. * @@ -38,68 +34,69 @@ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - deploymentGroupName - The name of the deployment group.\s - appName - The name of the application.\s - serviceRoleArn - A service role Amazon Resource Name (ARN) that allows AWS CodeDeploy to act on the user's behalf. \s - tagKey - The tag filter key (ie, AppName).\s - tagValue - The tag filter value (ie, mywebapp). - """; + Where: + deploymentGroupName - The name of the deployment group.\s + appName - The name of the application.\s + serviceRoleArn - A service role Amazon Resource Name (ARN) that allows AWS CodeDeploy to act on the user's behalf. \s + tagKey - The tag filter key (ie, AppName).\s + tagValue - The tag filter value (ie, mywebapp). + """; if (args.length != 5) { System.out.println(usage); System.exit(1); } - String deploymentGroupName = args[0] ; + String deploymentGroupName = args[0]; String appName = args[1]; - String serviceRoleArn= args[2]; - String tagKey=args[3]; - String tagValue=args[4]; + String serviceRoleArn = args[2]; + String tagKey = args[3]; + String tagValue = args[4]; Region region = Region.US_EAST_1; CodeDeployClient deployClient = CodeDeployClient.builder() - .region(region) - .build(); + .region(region) + .build(); - String groupId = createNewDeploymentGroup(deployClient, deploymentGroupName, appName, serviceRoleArn, tagKey, tagValue ); - System.out.println("The group deployment ID is "+groupId); + String groupId = createNewDeploymentGroup(deployClient, deploymentGroupName, appName, serviceRoleArn, tagKey, + tagValue); + System.out.println("The group deployment ID is " + groupId); deployClient.close(); } // snippet-start:[codedeploy.java2.create_deployment_group.main] public static String createNewDeploymentGroup(CodeDeployClient deployClient, - String deploymentGroupName, - String appName, - String serviceRoleArn, - String tagKey, - String tagValue) { + String deploymentGroupName, + String appName, + String serviceRoleArn, + String tagKey, + String tagValue) { try { DeploymentStyle style = DeploymentStyle.builder() - .deploymentType(DeploymentType.IN_PLACE) - .deploymentOption(DeploymentOption.WITHOUT_TRAFFIC_CONTROL) - .build(); + .deploymentType(DeploymentType.IN_PLACE) + .deploymentOption(DeploymentOption.WITHOUT_TRAFFIC_CONTROL) + .build(); EC2TagFilter tagFilter = EC2TagFilter.builder() - .key(tagKey) - .value(tagValue) - .type("KEY_AND_VALUE") - .build(); + .key(tagKey) + .value(tagValue) + .type("KEY_AND_VALUE") + .build(); List tags = new ArrayList<>(); tags.add(tagFilter); CreateDeploymentGroupRequest groupRequest = CreateDeploymentGroupRequest.builder() - .deploymentGroupName(deploymentGroupName) - .applicationName(appName) - .serviceRoleArn(serviceRoleArn) - .deploymentStyle(style) - .ec2TagFilters(tags) - .build(); + .deploymentGroupName(deploymentGroupName) + .applicationName(appName) + .serviceRoleArn(serviceRoleArn) + .deploymentStyle(style) + .ec2TagFilters(tags) + .build(); CreateDeploymentGroupResponse groupResponse = deployClient.createDeploymentGroup(groupRequest); return groupResponse.deploymentGroupId(); diff --git a/javav2/example_code/codedeploy/src/main/java/com/example/deploy/DeleteApplication.java b/javav2/example_code/codedeploy/src/main/java/com/example/deploy/DeleteApplication.java index ee20206dc65..c3497154847 100644 --- a/javav2/example_code/codedeploy/src/main/java/com/example/deploy/DeleteApplication.java +++ b/javav2/example_code/codedeploy/src/main/java/com/example/deploy/DeleteApplication.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DeleteApplication.java demonstrates how to delete an application.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS CodeDeploy] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.deploy; @@ -18,7 +12,8 @@ // snippet-end:[codedeploy.java2.delete_app.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,23 +25,23 @@ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - appName - The name of the application.\s - """; + Where: + appName - The name of the application.\s + """; if (args.length != 1) { System.out.println(usage); System.exit(1); - } + } String appName = args[0]; Region region = Region.US_EAST_1; CodeDeployClient deployClient = CodeDeployClient.builder() - .region(region) - .build(); + .region(region) + .build(); delApplication(deployClient, appName); deployClient.close(); @@ -56,11 +51,11 @@ public static void delApplication(CodeDeployClient deployClient, String appName) try { DeleteApplicationRequest deleteApplicationRequest = DeleteApplicationRequest.builder() - .applicationName(appName) - .build(); + .applicationName(appName) + .build(); deployClient.deleteApplication(deleteApplicationRequest); - System.out.println(appName +" was deleted!"); + System.out.println(appName + " was deleted!"); } catch (CodeDeployException e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/codedeploy/src/main/java/com/example/deploy/DeleteDeploymentGroup.java b/javav2/example_code/codedeploy/src/main/java/com/example/deploy/DeleteDeploymentGroup.java index 168fa9eafbe..fcaaad631ab 100644 --- a/javav2/example_code/codedeploy/src/main/java/com/example/deploy/DeleteDeploymentGroup.java +++ b/javav2/example_code/codedeploy/src/main/java/com/example/deploy/DeleteDeploymentGroup.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DeleteDeploymentGroup.java demonstrates how to delete a deployment group.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS CodeDeploy] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.deploy; @@ -17,7 +11,8 @@ // snippet-end:[codedeploy.java2.delete_group.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,13 +23,13 @@ public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - appName - The name of the application.\s - deploymentGroupName - The name of the deployment group.\s - """; + Where: + appName - The name of the application.\s + deploymentGroupName - The name of the deployment group.\s + """; if (args.length != 2) { System.out.println(usage); @@ -45,8 +40,8 @@ public static void main(String[] args) { String deploymentGroupName = args[1]; Region region = Region.US_EAST_1; CodeDeployClient deployClient = CodeDeployClient.builder() - .region(region) - .build(); + .region(region) + .build(); delDeploymentGroup(deployClient, appName, deploymentGroupName); deployClient.close(); @@ -54,17 +49,17 @@ public static void main(String[] args) { // snippet-start:[codedeploy.java2.delete_group.main] public static void delDeploymentGroup(CodeDeployClient deployClient, - String appName, - String deploymentGroupName) { + String appName, + String deploymentGroupName) { try { DeleteDeploymentGroupRequest deleteDeploymentGroupRequest = DeleteDeploymentGroupRequest.builder() - .deploymentGroupName(appName) - .applicationName(deploymentGroupName) - .build(); + .deploymentGroupName(appName) + .applicationName(deploymentGroupName) + .build(); deployClient.deleteDeploymentGroup(deleteDeploymentGroupRequest); - System.out.println(deploymentGroupName +" was deleted!"); + System.out.println(deploymentGroupName + " was deleted!"); } catch (CodeDeployException e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/codedeploy/src/main/java/com/example/deploy/DeployApplication.java b/javav2/example_code/codedeploy/src/main/java/com/example/deploy/DeployApplication.java index b87e81eeaa8..4b5e5338a2a 100644 --- a/javav2/example_code/codedeploy/src/main/java/com/example/deploy/DeployApplication.java +++ b/javav2/example_code/codedeploy/src/main/java/com/example/deploy/DeployApplication.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[DeployApplication.java demonstrates how to deploy an application revision.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS CodeDeploy] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.deploy; @@ -20,15 +15,16 @@ // snippet-end:[codedeploy.java2._deploy_app.import] /** - * Before running this code example, it's recommended that you go through the CodeDeploy tutorials at: + * Before running this code example, it's recommended that you go through the + * CodeDeploy tutorials at: * - * https://docs.aws.amazon.com/codedeploy/latest/userguide/tutorials.html + * https://docs.aws.amazon.com/codedeploy/latest/userguide/tutorials.html * * Also, set up your development environment, including your credentials. * * For more information, see the following documentation topic: * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * */ @@ -37,16 +33,16 @@ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - appName - The name of the application.\s - bucketName - The name of the Amazon S3 bucket that contains the ZIP to deploy.\s - bundleType - The bundle type (for example, zip).\s - key - The key located in the S3 bucket (for example, mywebapp.zip).\s - deploymentGroup - The name of the deployment group (for example, group1).\s - """; + Where: + appName - The name of the application.\s + bucketName - The name of the Amazon S3 bucket that contains the ZIP to deploy.\s + bundleType - The bundle type (for example, zip).\s + key - The key located in the S3 bucket (for example, mywebapp.zip).\s + deploymentGroup - The name of the deployment group (for example, group1).\s + """; if (args.length != 5) { System.out.println(usage); @@ -61,40 +57,40 @@ public static void main(String[] args) { Region region = Region.US_EAST_1; CodeDeployClient deployClient = CodeDeployClient.builder() - .region(region) - .build(); + .region(region) + .build(); String deploymentId = createAppDeployment(deployClient, appName, bucketName, bundleType, key, deploymentGroup); - System.out.println("The deployment Id is "+deploymentId); + System.out.println("The deployment Id is " + deploymentId); deployClient.close(); } // snippet-start:[codedeploy.java2._deploy_app.main] public static String createAppDeployment(CodeDeployClient deployClient, - String appName, - String bucketName, - String bundleType, - String key, - String deploymentGroup) { + String appName, + String bucketName, + String bundleType, + String key, + String deploymentGroup) { - try{ + try { S3Location s3Location = S3Location.builder() - .bucket(bucketName) - .bundleType(bundleType) - .key(key) - .build(); + .bucket(bucketName) + .bundleType(bundleType) + .key(key) + .build(); RevisionLocation revisionLocation = RevisionLocation.builder() - .s3Location(s3Location) - .revisionType(RevisionLocationType.S3) - .build(); + .s3Location(s3Location) + .revisionType(RevisionLocationType.S3) + .build(); CreateDeploymentRequest deploymentRequest = CreateDeploymentRequest.builder() - .applicationName(appName) - .deploymentGroupName(deploymentGroup) - .description("A deployment created by the Java API") - .revision(revisionLocation) - .build(); + .applicationName(appName) + .deploymentGroupName(deploymentGroup) + .description("A deployment created by the Java API") + .revision(revisionLocation) + .build(); CreateDeploymentResponse response = deployClient.createDeployment(deploymentRequest); return response.deploymentId(); @@ -106,4 +102,4 @@ public static String createAppDeployment(CodeDeployClient deployClient, return ""; } // snippet-end:[codedeploy.java2._deploy_app.main] - } +} diff --git a/javav2/example_code/codedeploy/src/main/java/com/example/deploy/GetDeployment.java b/javav2/example_code/codedeploy/src/main/java/com/example/deploy/GetDeployment.java index 8d621ddf127..86004d12106 100644 --- a/javav2/example_code/codedeploy/src/main/java/com/example/deploy/GetDeployment.java +++ b/javav2/example_code/codedeploy/src/main/java/com/example/deploy/GetDeployment.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[GetDeployment.java demonstrates how to get information about a deployment.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS CodeDeploy] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.deploy; @@ -18,7 +12,8 @@ // snippet-end:[codedeploy.java2._get_deployment.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,38 +25,39 @@ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - deploymentId - The id of the deployment.\s - """; + Where: + deploymentId - The id of the deployment.\s + """; - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } + if (args.length != 1) { + System.out.println(usage); + System.exit(1); + } - String deploymentId = args[0]; - Region region = Region.US_EAST_1; - CodeDeployClient deployClient = CodeDeployClient.builder() - .region(region) - .build(); + String deploymentId = args[0]; + Region region = Region.US_EAST_1; + CodeDeployClient deployClient = CodeDeployClient.builder() + .region(region) + .build(); - getSpecificDeployment(deployClient, deploymentId); - deployClient.close(); + getSpecificDeployment(deployClient, deploymentId); + deployClient.close(); } // snippet-start:[codedeploy.java2._get_deployment.main] - public static void getSpecificDeployment(CodeDeployClient deployClient, String deploymentId ) { + public static void getSpecificDeployment(CodeDeployClient deployClient, String deploymentId) { try { GetDeploymentRequest deploymentRequest = GetDeploymentRequest.builder() - .deploymentId(deploymentId) - .build(); + .deploymentId(deploymentId) + .build(); GetDeploymentResponse response = deployClient.getDeployment(deploymentRequest); - System.out.println("The application associated with this deployment is "+ response.deploymentInfo().applicationName()); + System.out.println("The application associated with this deployment is " + + response.deploymentInfo().applicationName()); } catch (CodeDeployException e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/codedeploy/src/main/java/com/example/deploy/ListApplications.java b/javav2/example_code/codedeploy/src/main/java/com/example/deploy/ListApplications.java index f32f97816aa..6842f38595f 100644 --- a/javav2/example_code/codedeploy/src/main/java/com/example/deploy/ListApplications.java +++ b/javav2/example_code/codedeploy/src/main/java/com/example/deploy/ListApplications.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[ListApplications.java demonstrates how to information about your applications.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS CodeDeploy] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.deploy; @@ -17,7 +12,8 @@ // snippet-end:[codedeploy.java2._list_apps.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,8 +23,8 @@ public class ListApplications { public static void main(String[] args) { Region region = Region.US_EAST_1; CodeDeployClient deployClient = CodeDeployClient.builder() - .region(region) - .build(); + .region(region) + .build(); listApps(deployClient); deployClient.close(); @@ -40,8 +36,8 @@ public static void listApps(CodeDeployClient deployClient) { try { ListApplicationsResponse applicationsResponse = deployClient.listApplications(); List apps = applicationsResponse.applications(); - for (String app: apps) { - System.out.println("The application name is: "+app); + for (String app : apps) { + System.out.println("The application name is: " + app); } } catch (CodeDeployException e) { diff --git a/javav2/example_code/codedeploy/src/main/java/com/example/deploy/ListDeploymentGroups.java b/javav2/example_code/codedeploy/src/main/java/com/example/deploy/ListDeploymentGroups.java index 6133e6aefb4..963d5a32444 100644 --- a/javav2/example_code/codedeploy/src/main/java/com/example/deploy/ListDeploymentGroups.java +++ b/javav2/example_code/codedeploy/src/main/java/com/example/deploy/ListDeploymentGroups.java @@ -1,10 +1,6 @@ -//snippet-sourcedescription:[ListDeploymentGroups.java demonstrates how to list your deployment groups.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS CodeDeploy] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.deploy; // snippet-start:[codedeploy.java2._list_groups.import] @@ -17,7 +13,8 @@ // snippet-end:[codedeploy.java2._list_groups.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +25,12 @@ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - appName - The application name.\s - """; + Where: + appName - The application name.\s + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +40,8 @@ public static void main(String[] args) { String appName = args[0]; Region region = Region.US_EAST_1; CodeDeployClient deployClient = CodeDeployClient.builder() - .region(region) - .build(); + .region(region) + .build(); listDeployGroups(deployClient, appName); deployClient.close(); @@ -55,19 +52,19 @@ public static void listDeployGroups(CodeDeployClient deployClient, String appNam try { ListDeploymentGroupsRequest groupsRequest = ListDeploymentGroupsRequest.builder() - .applicationName(appName) - .build(); + .applicationName(appName) + .build(); ListDeploymentGroupsResponse response = deployClient.listDeploymentGroups(groupsRequest); List groups = response.deploymentGroups(); - for (String group: groups) { - System.out.println("The deployment group is: "+group); + for (String group : groups) { + System.out.println("The deployment group is: " + group); } } catch (CodeDeployException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } - } - // snippet-end:[codedeploy.java2._list_groups.main] + } + // snippet-end:[codedeploy.java2._list_groups.main] } \ No newline at end of file diff --git a/javav2/example_code/codedeploy/src/test/java/CodeDeployTest.java b/javav2/example_code/codedeploy/src/test/java/CodeDeployTest.java index f4c58ac680f..a464a6d73b0 100644 --- a/javav2/example_code/codedeploy/src/test/java/CodeDeployTest.java +++ b/javav2/example_code/codedeploy/src/test/java/CodeDeployTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.deploy.*; import com.google.gson.Gson; @@ -29,18 +27,18 @@ public class CodeDeployTest { private static String key = ""; private static String bundleType = ""; private static String newDeploymentGroupName = ""; - private static String deploymentId="" ; - private static String serviceRoleArn="" ; - private static String tagKey=""; - private static String tagValue=""; + private static String deploymentId = ""; + private static String serviceRoleArn = ""; + private static String tagKey = ""; + private static String tagValue = ""; @BeforeAll public static void setUp() { Region region = Region.US_EAST_1; deployClient = CodeDeployClient.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); Gson gson = new Gson(); String json = getSecretValues(); @@ -51,44 +49,47 @@ public static void setUp() { bucketName = values.getBucketName(); key = values.getKey(); bundleType = values.getBundleType(); - newDeploymentGroupName = values.getNewDeploymentGroupName(); + newDeploymentGroupName = values.getNewDeploymentGroupName(); serviceRoleArn = values.getServiceRoleArn(); tagKey = values.getTagKey(); tagValue = values.getTagValue(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - try (InputStream input = CodeDeployTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - // Populate the data members required for all tests. - prop.load(input); - appName = prop.getProperty("appName"); - existingApp = prop.getProperty("existingApp"); - existingDeployment = prop.getProperty("existingDeployment"); - bucketName = prop.getProperty("bucketName"); - key = prop.getProperty("key"); - bundleType = prop.getProperty("bundleType"); - newDeploymentGroupName = prop.getProperty("newDeploymentGroupName"); - serviceRoleArn = prop.getProperty("serviceRoleArn"); - tagKey = prop.getProperty("tagKey"); - tagValue = prop.getProperty("tagValue"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * try (InputStream input = + * CodeDeployTest.class.getClassLoader().getResourceAsStream("config.properties" + * )) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * // Populate the data members required for all tests. + * prop.load(input); + * appName = prop.getProperty("appName"); + * existingApp = prop.getProperty("existingApp"); + * existingDeployment = prop.getProperty("existingDeployment"); + * bucketName = prop.getProperty("bucketName"); + * key = prop.getProperty("key"); + * bundleType = prop.getProperty("bundleType"); + * newDeploymentGroupName = prop.getProperty("newDeploymentGroupName"); + * serviceRoleArn = prop.getProperty("serviceRoleArn"); + * tagKey = prop.getProperty("tagKey"); + * tagValue = prop.getProperty("tagValue"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @Tag("IntegrationTest") @Order(1) public void CreateApplication() { - assertDoesNotThrow(() ->CreateApplication.createApp(deployClient, appName)); + assertDoesNotThrow(() -> CreateApplication.createApp(deployClient, appName)); System.out.println("Test 1 passed"); } @@ -96,7 +97,7 @@ public void CreateApplication() { @Tag("IntegrationTest") @Order(2) public void ListApplications() { - assertDoesNotThrow(() ->ListApplications.listApps(deployClient)); + assertDoesNotThrow(() -> ListApplications.listApps(deployClient)); System.out.println("Test 2 passed"); } @@ -104,7 +105,8 @@ public void ListApplications() { @Tag("IntegrationTest") @Order(3) public void DeployApplication() { - deploymentId = DeployApplication.createAppDeployment(deployClient, existingApp, bucketName, bundleType, key, existingDeployment); + deploymentId = DeployApplication.createAppDeployment(deployClient, existingApp, bucketName, bundleType, key, + existingDeployment); assertFalse(deploymentId.isEmpty()); System.out.println("Test 3 passed"); } @@ -113,7 +115,8 @@ public void DeployApplication() { @Tag("IntegrationTest") @Order(4) public void CreateDeploymentGroup() { - assertDoesNotThrow(() ->CreateDeploymentGroup.createNewDeploymentGroup(deployClient, newDeploymentGroupName, appName, serviceRoleArn, tagKey, tagValue)); + assertDoesNotThrow(() -> CreateDeploymentGroup.createNewDeploymentGroup(deployClient, newDeploymentGroupName, + appName, serviceRoleArn, tagKey, tagValue)); System.out.println("Test 4 passed"); } @@ -121,44 +124,45 @@ public void CreateDeploymentGroup() { @Tag("IntegrationTest") @Order(5) public void ListDeploymentGroups() { - assertDoesNotThrow(() ->ListDeploymentGroups.listDeployGroups(deployClient, appName)); + assertDoesNotThrow(() -> ListDeploymentGroups.listDeployGroups(deployClient, appName)); System.out.println("Test 5 passed"); - } + } @Test @Tag("IntegrationTest") @Order(6) - public void GetDeployment(){ - assertDoesNotThrow(() ->GetDeployment.getSpecificDeployment(deployClient,deploymentId)); - System.out.println("Test 6 passed"); - } + public void GetDeployment() { + assertDoesNotThrow(() -> GetDeployment.getSpecificDeployment(deployClient, deploymentId)); + System.out.println("Test 6 passed"); + } @Test @Tag("IntegrationTest") @Order(7) - public void DeleteDeploymentGroup() { - assertDoesNotThrow(() ->DeleteDeploymentGroup.delDeploymentGroup(deployClient, appName, newDeploymentGroupName)); - System.out.println("Test 7 passed"); - } + public void DeleteDeploymentGroup() { + assertDoesNotThrow( + () -> DeleteDeploymentGroup.delDeploymentGroup(deployClient, appName, newDeploymentGroupName)); + System.out.println("Test 7 passed"); + } @Test @Tag("IntegrationTest") @Order(8) - public void DeleteApplication() { - assertDoesNotThrow(() ->DeleteApplication.delApplication(deployClient, appName)); - System.out.println("Test 8 passed"); - } + public void DeleteApplication() { + assertDoesNotThrow(() -> DeleteApplication.delApplication(deployClient, appName)); + System.out.println("Test 8 passed"); + } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/codedeploy"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); diff --git a/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/CreatePipeline.java b/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/CreatePipeline.java index 4cef25a2823..2a598399498 100644 --- a/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/CreatePipeline.java +++ b/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/CreatePipeline.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[CreatePipeline.java demonstrates how to create a pipeline.] -//snippet-keyword:[SDK for Java 2.0] -//snippet-service:[AWS CodePipeline] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pipeline; @@ -30,7 +24,8 @@ // snippet-end:[pipeline.java2.create_pipeline.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -38,127 +33,128 @@ */ public class CreatePipeline { - public static void main(String[] args) { - final String usage = """ - - Usage: - - Where: - name - The name of the pipeline to create.\s - roleArn - The Amazon Resource Name (ARN) for AWS CodePipeline to use. \s - s3Bucket - The name of the Amazon S3 bucket where the code is located. \s - s3OuputBucket - The name of the Amazon S3 bucket where the code is deployed. \s - """; - - if (args.length != 4) { - System.out.println(usage); - System.exit(1); + public static void main(String[] args) { + final String usage = """ + + Usage: + + Where: + name - The name of the pipeline to create.\s + roleArn - The Amazon Resource Name (ARN) for AWS CodePipeline to use. \s + s3Bucket - The name of the Amazon S3 bucket where the code is located. \s + s3OuputBucket - The name of the Amazon S3 bucket where the code is deployed. \s + """; + + if (args.length != 4) { + System.out.println(usage); + System.exit(1); + } + + String name = args[0]; + String roleArn = args[1]; + String s3Bucket = args[2]; + String s3OuputBucket = args[3]; + Region region = Region.US_EAST_1; + CodePipelineClient pipelineClient = CodePipelineClient.builder() + .region(region) + .build(); + + createNewPipeline(pipelineClient, name, roleArn, s3Bucket, s3OuputBucket); + pipelineClient.close(); } - String name = args[0]; - String roleArn = args[1]; - String s3Bucket = args[2]; - String s3OuputBucket = args[3]; - Region region = Region.US_EAST_1; - CodePipelineClient pipelineClient = CodePipelineClient.builder() - .region(region) - .build(); - - createNewPipeline(pipelineClient, name, roleArn, s3Bucket, s3OuputBucket); - pipelineClient.close(); - } - - public static void createNewPipeline(CodePipelineClient pipelineClient, String name, String roleArn, String s3Bucket, String s3OuputBucket) { - try { - ActionTypeId actionTypeSource = ActionTypeId.builder() - .category("Source") - .owner("AWS") - .provider("S3") - .version("1") - .build(); - - // Set Config information - Map mapConfig = new HashMap<>(); - mapConfig.put("PollForSourceChanges", "false"); - mapConfig.put("S3Bucket", s3Bucket); - mapConfig.put("S3ObjectKey", "SampleApp_Windows.zip"); - - OutputArtifact outputArtifact = OutputArtifact.builder() - .name("SourceArtifact") - .build(); - - ActionDeclaration actionDeclarationSource = ActionDeclaration.builder() - .actionTypeId(actionTypeSource) - .region("us-east-1") - .configuration(mapConfig) - .runOrder(1) - .outputArtifacts(outputArtifact) - .name("Source") - .build(); - - // Set Config information. - Map mapConfig1 = new HashMap<>(); - mapConfig1.put("BucketName", s3OuputBucket); - mapConfig1.put("ObjectKey", "SampleApp.zip"); - mapConfig1.put("Extract", "false"); - - ActionTypeId actionTypeDeploy = ActionTypeId.builder() - .category("Deploy") - .owner("AWS") - .provider("S3") - .version("1") - .build(); - - InputArtifact inArtifact = InputArtifact.builder() - .name("SourceArtifact") - .build(); - - ActionDeclaration actionDeclarationDeploy = ActionDeclaration.builder() - .actionTypeId(actionTypeDeploy) - .region("us-east-1") - .configuration(mapConfig1) - .inputArtifacts(inArtifact) - .runOrder(1) - .name("Deploy") - .build(); - - StageDeclaration declaration = StageDeclaration.builder() - .actions(actionDeclarationSource) - .name("Stage") - .build(); - - StageDeclaration deploy = StageDeclaration.builder() - .actions(actionDeclarationDeploy) - .name("Deploy") - .build(); - - List stages = new ArrayList<>(); - stages.add(declaration); - stages.add(deploy); - - ArtifactStore store = ArtifactStore.builder() - .location(s3Bucket) - .type("S3") - .build(); - - PipelineDeclaration pipelineDeclaration = PipelineDeclaration.builder() - .name(name) - .artifactStore(store) - .roleArn(roleArn) - .stages(stages) - .build(); - - CreatePipelineRequest pipelineRequest = CreatePipelineRequest.builder() - .pipeline(pipelineDeclaration) - .build(); - - CreatePipelineResponse response = pipelineClient.createPipeline(pipelineRequest); - System.out.println("Pipeline " + response.pipeline().name() + " was successfully created"); - - } catch (CodePipelineException e) { - System.err.println(e.getMessage()); - System.exit(1); + public static void createNewPipeline(CodePipelineClient pipelineClient, String name, String roleArn, + String s3Bucket, String s3OuputBucket) { + try { + ActionTypeId actionTypeSource = ActionTypeId.builder() + .category("Source") + .owner("AWS") + .provider("S3") + .version("1") + .build(); + + // Set Config information + Map mapConfig = new HashMap<>(); + mapConfig.put("PollForSourceChanges", "false"); + mapConfig.put("S3Bucket", s3Bucket); + mapConfig.put("S3ObjectKey", "SampleApp_Windows.zip"); + + OutputArtifact outputArtifact = OutputArtifact.builder() + .name("SourceArtifact") + .build(); + + ActionDeclaration actionDeclarationSource = ActionDeclaration.builder() + .actionTypeId(actionTypeSource) + .region("us-east-1") + .configuration(mapConfig) + .runOrder(1) + .outputArtifacts(outputArtifact) + .name("Source") + .build(); + + // Set Config information. + Map mapConfig1 = new HashMap<>(); + mapConfig1.put("BucketName", s3OuputBucket); + mapConfig1.put("ObjectKey", "SampleApp.zip"); + mapConfig1.put("Extract", "false"); + + ActionTypeId actionTypeDeploy = ActionTypeId.builder() + .category("Deploy") + .owner("AWS") + .provider("S3") + .version("1") + .build(); + + InputArtifact inArtifact = InputArtifact.builder() + .name("SourceArtifact") + .build(); + + ActionDeclaration actionDeclarationDeploy = ActionDeclaration.builder() + .actionTypeId(actionTypeDeploy) + .region("us-east-1") + .configuration(mapConfig1) + .inputArtifacts(inArtifact) + .runOrder(1) + .name("Deploy") + .build(); + + StageDeclaration declaration = StageDeclaration.builder() + .actions(actionDeclarationSource) + .name("Stage") + .build(); + + StageDeclaration deploy = StageDeclaration.builder() + .actions(actionDeclarationDeploy) + .name("Deploy") + .build(); + + List stages = new ArrayList<>(); + stages.add(declaration); + stages.add(deploy); + + ArtifactStore store = ArtifactStore.builder() + .location(s3Bucket) + .type("S3") + .build(); + + PipelineDeclaration pipelineDeclaration = PipelineDeclaration.builder() + .name(name) + .artifactStore(store) + .roleArn(roleArn) + .stages(stages) + .build(); + + CreatePipelineRequest pipelineRequest = CreatePipelineRequest.builder() + .pipeline(pipelineDeclaration) + .build(); + + CreatePipelineResponse response = pipelineClient.createPipeline(pipelineRequest); + System.out.println("Pipeline " + response.pipeline().name() + " was successfully created"); + + } catch (CodePipelineException e) { + System.err.println(e.getMessage()); + System.exit(1); + } } - } } // snippet-end:[pipeline.java2.create_pipeline.main] diff --git a/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/DeletePipeline.java b/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/DeletePipeline.java index 3762c2bd7e7..8cbf279df9f 100644 --- a/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/DeletePipeline.java +++ b/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/DeletePipeline.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[DeletePipeline.java demonstrates how to delete a pipeline.] -//snippet-keyword:[SDK for Java 2.0] -//snippet-service:[AWS CodePipeline] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pipeline; @@ -17,7 +12,8 @@ // snippet-end:[pipeline.java2.delete_pipeline.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,11 +23,11 @@ public class DeletePipeline { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - name - The name of the pipeline to delete\s - """; + Where: + name - The name of the pipeline to delete\s + """; if (args.length != 1) { System.out.println(usage); @@ -41,8 +37,8 @@ public static void main(String[] args) { String name = args[0]; Region region = Region.US_EAST_1; CodePipelineClient pipelineClient = CodePipelineClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteSpecificPipeline(pipelineClient, name); pipelineClient.close(); @@ -51,8 +47,8 @@ public static void main(String[] args) { public static void deleteSpecificPipeline(CodePipelineClient pipelineClient, String name) { try { DeletePipelineRequest deletePipelineRequest = DeletePipelineRequest.builder() - .name(name) - .build(); + .name(name) + .build(); pipelineClient.deletePipeline(deletePipelineRequest); System.out.println(name + " was successfully deleted"); @@ -63,6 +59,4 @@ public static void deleteSpecificPipeline(CodePipelineClient pipelineClient, Str } } } - // snippet-end:[pipeline.java2.delete_pipeline.main] - - +// snippet-end:[pipeline.java2.delete_pipeline.main] diff --git a/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/GetPipeline.java b/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/GetPipeline.java index 851f253cf38..a9222beaef4 100644 --- a/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/GetPipeline.java +++ b/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/GetPipeline.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[GetPipeline.java demonstrates how to retrieve a specific pipeline.] -//snippet-keyword:[SDK for Java 2.0] -//snippet-service:[AWS CodePipeline] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pipeline; @@ -22,7 +16,8 @@ // snippet-end:[pipeline.java2.get_pipeline.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,11 +27,11 @@ public class GetPipeline { public static void main(String[] args) { final String usage = """ - Usage: \s + Usage: \s - Where: - name - The name of the pipeline to retrieve\s - """; + Where: + name - The name of the pipeline to retrieve\s + """; if (args.length != 1) { System.out.println(usage); @@ -46,8 +41,8 @@ public static void main(String[] args) { String name = args[0]; Region region = Region.US_EAST_1; CodePipelineClient pipelineClient = CodePipelineClient.builder() - .region(region) - .build(); + .region(region) + .build(); getSpecificPipeline(pipelineClient, name); pipelineClient.close(); @@ -56,16 +51,16 @@ public static void main(String[] args) { public static void getSpecificPipeline(CodePipelineClient pipelineClient, String name) { try { GetPipelineRequest pipelineRequest = GetPipelineRequest.builder() - .name(name) - .version(1) - .build(); + .name(name) + .version(1) + .build(); GetPipelineResponse response = pipelineClient.getPipeline(pipelineRequest); List stages = response.pipeline().stages(); for (StageDeclaration stage : stages) { System.out.println("Stage name is " + stage.name() + " and actions are:"); - //Get the stage actions. + // Get the stage actions. List actions = stage.actions(); for (ActionDeclaration action : actions) { System.out.println("Action name is " + action.name()); diff --git a/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/ListPipelineExecutions.java b/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/ListPipelineExecutions.java index 223dd970da1..ef1319fab9b 100644 --- a/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/ListPipelineExecutions.java +++ b/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/ListPipelineExecutions.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[ListPipelineExecutions.java demonstrates how to get all executions for a specific pipeline.] -//snippet-keyword:[SDK for Java 2.0] -//snippet-service:[AWS CodePipeline] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pipeline; @@ -21,7 +15,8 @@ // snippet-end:[pipeline.java2.list_pipeline_exe.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,12 +27,12 @@ public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - name - The name of the pipeline.\s + Where: + name - The name of the pipeline.\s - """; + """; if (args.length != 1) { System.out.println(usage); @@ -47,8 +42,8 @@ public static void main(String[] args) { String name = args[0]; Region region = Region.US_EAST_1; CodePipelineClient pipelineClient = CodePipelineClient.builder() - .region(region) - .build(); + .region(region) + .build(); listExecutions(pipelineClient, name); pipelineClient.close(); @@ -57,9 +52,9 @@ public static void main(String[] args) { public static void listExecutions(CodePipelineClient pipelineClient, String name) { try { ListPipelineExecutionsRequest executionsRequest = ListPipelineExecutionsRequest.builder() - .maxResults(10) - .pipelineName(name) - .build(); + .maxResults(10) + .pipelineName(name) + .build(); ListPipelineExecutionsResponse response = pipelineClient.listPipelineExecutions(executionsRequest); List executionSummaryList = response.pipelineExecutionSummaries(); diff --git a/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/ListPipelines.java b/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/ListPipelines.java index fea106219b1..18b1a7e1453 100644 --- a/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/ListPipelines.java +++ b/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/ListPipelines.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[ListPipelines.java demonstrates how to retrieve all pipelines.] -//snippet-keyword:[SDK for Java 2.0] -//snippet-service:[AWS CodePipeline] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pipeline; @@ -19,7 +13,8 @@ // snippet-end:[pipeline.java2.list_pipelines.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,8 +24,8 @@ public class ListPipelines { public static void main(String[] args) { Region region = Region.US_EAST_1; CodePipelineClient pipelineClient = CodePipelineClient.builder() - .region(region) - .build(); + .region(region) + .build(); getAllPipelines(pipelineClient); pipelineClient.close(); @@ -42,8 +37,8 @@ public static void getAllPipelines(CodePipelineClient pipelineClient) { try { ListPipelinesResponse response = pipelineClient.listPipelines(); List pipelines = response.pipelines(); - for (PipelineSummary pipeline: pipelines) { - System.out.println("The name of the pipeline is "+pipeline.name()); + for (PipelineSummary pipeline : pipelines) { + System.out.println("The name of the pipeline is " + pipeline.name()); } } catch (CodePipelineException e) { diff --git a/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/StartPipelineExecution.java b/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/StartPipelineExecution.java index ade896d37e7..456d4f7a2fb 100644 --- a/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/StartPipelineExecution.java +++ b/javav2/example_code/codepipeline/src/main/java/com/example/pipeline/StartPipelineExecution.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[StartPipelineExecution.java demonstrates how to execute a pipeline.] -//snippet-keyword:[SDK for Java 2.0] -//snippet-service:[AWS CodePipeline] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pipeline; @@ -18,7 +13,8 @@ // snippet-end:[pipeline.java2.start_pipeline.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,11 +24,11 @@ public class StartPipelineExecution { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - name - The name of the pipeline to execute\s - """; + Where: + name - The name of the pipeline to execute\s + """; if (args.length != 1) { System.out.println(usage); @@ -42,8 +38,8 @@ public static void main(String[] args) { String name = args[0]; Region region = Region.US_EAST_1; CodePipelineClient pipelineClient = CodePipelineClient.builder() - .region(region) - .build(); + .region(region) + .build(); executePipeline(pipelineClient, name); pipelineClient.close(); @@ -53,8 +49,8 @@ public static void executePipeline(CodePipelineClient pipelineClient, String nam try { StartPipelineExecutionRequest pipelineExecutionRequest = StartPipelineExecutionRequest.builder() - .name(name) - .build(); + .name(name) + .build(); StartPipelineExecutionResponse response = pipelineClient.startPipelineExecution(pipelineExecutionRequest); System.out.println("Piepline " + response.pipelineExecutionId() + " was successfully executed"); diff --git a/javav2/example_code/cognito/run_example.sh b/javav2/example_code/cognito/run_example.sh index c2f38f6c8d4..0fb308e647d 100644 --- a/javav2/example_code/cognito/run_example.sh +++ b/javav2/example_code/cognito/run_example.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 if [[ -z $* ]] ; then echo 'Supply the name of one of the example classes as an argument.' echo 'If there are arguments to the class, put them in quotes after the class name.' diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/AddLoginProvider.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/AddLoginProvider.java index cb41d60b1ed..31ac7c76447 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/AddLoginProvider.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/AddLoginProvider.java @@ -1,16 +1,10 @@ -//snippet-sourcedescription:[AddLoginProvider.java demonstrates how to associate an Amazon Cognito identity pool with an identity provider.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Cognito] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cognito; -//snippet-start:[cognito.java2.add_login_provider.main] -//snippet-start:[cognito.java2.add_login_provider.import] +// snippet-start:[cognito.java2.add_login_provider.main] +// snippet-start:[cognito.java2.add_login_provider.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient; import software.amazon.awssdk.services.cognitoidentity.model.CognitoIdentityProvider; @@ -19,10 +13,11 @@ import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException; import java.util.ArrayList; import java.util.List; -//snippet-end:[cognito.java2.add_login_provider.import] +// snippet-end:[cognito.java2.add_login_provider.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,15 +27,15 @@ public class AddLoginProvider { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - appId - The application ID value from the login provider. - identityPoolName - The name of your identity pool. - identityPoolId - The Id value of your identity pool. - providerName - The provider name (i.e., cognito-idp.us-east-1.amazonaws.com/us-east-1_Taz4Yxxxx). - """; + Where: + appId - The application ID value from the login provider. + identityPoolName - The name of your identity pool. + identityPoolId - The Id value of your identity pool. + providerName - The provider name (i.e., cognito-idp.us-east-1.amazonaws.com/us-east-1_Taz4Yxxxx). + """; if (args.length != 4) { System.out.println(usage); @@ -53,33 +48,33 @@ public static void main(String[] args) { String providerName = args[3]; CognitoIdentityClient cognitoclient = CognitoIdentityClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); setLoginProvider(cognitoclient, appId, identityPoolName, identityPoolId, providerName); cognitoclient.close(); } public static void setLoginProvider(CognitoIdentityClient cognitoclient, - String appId, - String identityPoolName, - String identityPoolId, - String providerName) { + String appId, + String identityPoolName, + String identityPoolId, + String providerName) { CognitoIdentityProvider identityProvider = CognitoIdentityProvider.builder() - .providerName(providerName) - .clientId(appId) - .build(); + .providerName(providerName) + .clientId(appId) + .build(); List proList = new ArrayList<>(); proList.add(identityProvider); try { UpdateIdentityPoolRequest poolRequest = UpdateIdentityPoolRequest.builder() - .allowUnauthenticatedIdentities(true) - .identityPoolName(identityPoolName) - .identityPoolId(identityPoolId) - .cognitoIdentityProviders(proList) - .build(); + .allowUnauthenticatedIdentities(true) + .identityPoolName(identityPoolName) + .identityPoolId(identityPoolId) + .cognitoIdentityProviders(proList) + .build(); UpdateIdentityPoolResponse response = cognitoclient.updateIdentityPool(poolRequest); List providers = response.cognitoIdentityProviders(); @@ -94,4 +89,4 @@ public static void setLoginProvider(CognitoIdentityClient cognitoclient, } } } -//snippet-end:[cognito.java2.add_login_provider.main] \ No newline at end of file +// snippet-end:[cognito.java2.add_login_provider.main] \ No newline at end of file diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/AdminInitiateAuth.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/AdminInitiateAuth.java index 5a3ae28be34..95b5835b53b 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/AdminInitiateAuth.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/AdminInitiateAuth.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cognito; import software.amazon.awssdk.regions.Region; diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/CognitoMVP.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/CognitoMVP.java index 85d66122106..5a6bb6046f5 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/CognitoMVP.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/CognitoMVP.java @@ -1,14 +1,10 @@ -//snippet-sourcedescription:[CognitoMVP.java demonstrates how to sign up a new user with Amazon Cognito and associate the user with an MFA application for multi-factor authentication.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Cognito] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.cognito; -//snippet-start:[cognito.java2.mvp.main] -//snippet-start:[cognito.java2.mvp.import] +// snippet-start:[cognito.java2.mvp.main] +// snippet-start:[cognito.java2.mvp.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminGetUserRequest; @@ -36,42 +32,52 @@ import java.util.List; import java.util.Map; import java.util.Scanner; -//snippet-end:[cognito.java2.mvp.import] +// snippet-end:[cognito.java2.mvp.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * TIP: To set up the required user pool, run the AWS Cloud Development Kit (AWS CDK) script provided in this GitHub repo at resources/cdk/cognito_scenario_user_pool_with_mfa. + * TIP: To set up the required user pool, run the AWS Cloud Development Kit (AWS + * CDK) script provided in this GitHub repo at + * resources/cdk/cognito_scenario_user_pool_with_mfa. * * This code example performs the following operations: * * 1. Invokes the signUp method to sign up a user. * 2. Invokes the adminGetUser method to get the user's confirmation status. - * 3. Invokes the ResendConfirmationCode method if the user requested another code. + * 3. Invokes the ResendConfirmationCode method if the user requested another + * code. * 4. Invokes the confirmSignUp method. - * 5. Invokes the AdminInitiateAuth to sign in. This results in being prompted to set up TOTP (time-based one-time password). (The response is “ChallengeName”: “MFA_SETUP”). - * 6. Invokes the AssociateSoftwareToken method to generate a TOTP MFA private key. This can be used with Google Authenticator. - * 7. Invokes the VerifySoftwareToken method to verify the TOTP and register for MFA. - * 8. Invokes the AdminInitiateAuth to sign in again. This results in being prompted to submit a TOTP (Response: “ChallengeName”: “SOFTWARE_TOKEN_MFA”). - * 9. Invokes the AdminRespondToAuthChallenge to get back a token. + * 5. Invokes the AdminInitiateAuth to sign in. This results in being prompted + * to set up TOTP (time-based one-time password). (The response is + * “ChallengeName”: “MFA_SETUP”). + * 6. Invokes the AssociateSoftwareToken method to generate a TOTP MFA private + * key. This can be used with Google Authenticator. + * 7. Invokes the VerifySoftwareToken method to verify the TOTP and register for + * MFA. + * 8. Invokes the AdminInitiateAuth to sign in again. This results in being + * prompted to submit a TOTP (Response: “ChallengeName”: “SOFTWARE_TOKEN_MFA”). + * 9. Invokes the AdminRespondToAuthChallenge to get back a token. */ public class CognitoMVP { public static final String DASHES = new String(new char[80]).replace("\0", "-"); + public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException { final String usage = """ - Usage: - + Usage: + - Where: - clientId - The app client Id value that you can get from the AWS CDK script. - poolId - The pool Id that you can get from the AWS CDK script.\s - """; + Where: + clientId - The app client Id value that you can get from the AWS CDK script. + poolId - The pool Id that you can get from the AWS CDK script.\s + """; if (args.length != 2) { System.out.println(usage); @@ -81,8 +87,8 @@ public static void main(String[] args) throws NoSuchAlgorithmException, InvalidK String clientId = args[0]; String poolId = args[1]; CognitoIdentityProviderClient identityProviderClient = CognitoIdentityProviderClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); System.out.println(DASHES); System.out.println("Welcome to the Amazon Cognito example scenario."); @@ -107,7 +113,8 @@ public static void main(String[] args) throws NoSuchAlgorithmException, InvalidK System.out.println("2. Getting " + userName + " in the user pool"); getAdminUser(identityProviderClient, userName, poolId); - System.out.println("*** Conformation code sent to " + userName + ". Would you like to send a new code? (Yes/No)"); + System.out + .println("*** Conformation code sent to " + userName + ". Would you like to send a new code? (Yes/No)"); System.out.println(DASHES); System.out.println(DASHES); @@ -129,8 +136,9 @@ public static void main(String[] args) throws NoSuchAlgorithmException, InvalidK System.out.println(DASHES); System.out.println("5. Invokes the initiateAuth to sign in"); - AdminInitiateAuthResponse authResponse = initiateAuth(identityProviderClient, clientId, userName, password, poolId) ; - String mySession = authResponse.session() ; + AdminInitiateAuthResponse authResponse = initiateAuth(identityProviderClient, clientId, userName, password, + poolId); + String mySession = authResponse.session(); System.out.println(DASHES); System.out.println(DASHES); @@ -151,7 +159,8 @@ public static void main(String[] args) throws NoSuchAlgorithmException, InvalidK System.out.println(DASHES); System.out.println("8. Re-enter a 6-digit code displayed in Google Authenticator"); String mfaCode = in.nextLine(); - AdminInitiateAuthResponse authResponse1 = initiateAuth(identityProviderClient, clientId, userName, password, poolId); + AdminInitiateAuthResponse authResponse1 = initiateAuth(identityProviderClient, clientId, userName, password, + poolId); System.out.println(DASHES); System.out.println(DASHES); @@ -165,9 +174,10 @@ public static void main(String[] args) throws NoSuchAlgorithmException, InvalidK System.out.println(DASHES); } - //snippet-start:[cognito.java2.verify.main] + // snippet-start:[cognito.java2.verify.main] // Respond to an authentication challenge. - public static void adminRespondToAuthChallenge(CognitoIdentityProviderClient identityProviderClient, String userName, String clientId, String mfaCode, String session) { + public static void adminRespondToAuthChallenge(CognitoIdentityProviderClient identityProviderClient, + String userName, String clientId, String mfaCode, String session) { System.out.println("SOFTWARE_TOKEN_MFA challenge is generated"); Map challengeResponses = new HashMap<>(); @@ -175,158 +185,165 @@ public static void adminRespondToAuthChallenge(CognitoIdentityProviderClient ide challengeResponses.put("SOFTWARE_TOKEN_MFA_CODE", mfaCode); AdminRespondToAuthChallengeRequest respondToAuthChallengeRequest = AdminRespondToAuthChallengeRequest.builder() - .challengeName(ChallengeNameType.SOFTWARE_TOKEN_MFA) - .clientId(clientId) - .challengeResponses(challengeResponses) - .session(session) - .build(); - - AdminRespondToAuthChallengeResponse respondToAuthChallengeResult = identityProviderClient.adminRespondToAuthChallenge(respondToAuthChallengeRequest); - System.out.println("respondToAuthChallengeResult.getAuthenticationResult()" + respondToAuthChallengeResult.authenticationResult()); + .challengeName(ChallengeNameType.SOFTWARE_TOKEN_MFA) + .clientId(clientId) + .challengeResponses(challengeResponses) + .session(session) + .build(); + + AdminRespondToAuthChallengeResponse respondToAuthChallengeResult = identityProviderClient + .adminRespondToAuthChallenge(respondToAuthChallengeRequest); + System.out.println("respondToAuthChallengeResult.getAuthenticationResult()" + + respondToAuthChallengeResult.authenticationResult()); } - //snippet-end:[cognito.java2.verify.main] + // snippet-end:[cognito.java2.verify.main] - //snippet-start:[cognito.java2.token.verify.main] + // snippet-start:[cognito.java2.token.verify.main] // Verify the TOTP and register for MFA. public static void verifyTOTP(CognitoIdentityProviderClient identityProviderClient, String session, String code) { try { VerifySoftwareTokenRequest tokenRequest = VerifySoftwareTokenRequest.builder() - .userCode(code) - .session(session) - .build(); + .userCode(code) + .session(session) + .build(); VerifySoftwareTokenResponse verifyResponse = identityProviderClient.verifySoftwareToken(tokenRequest); - System.out.println("The status of the token is " +verifyResponse.statusAsString()); + System.out.println("The status of the token is " + verifyResponse.statusAsString()); - } catch(CognitoIdentityProviderException e) { + } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } - //snippet-end:[cognito.java2.token.verify.main] + // snippet-end:[cognito.java2.token.verify.main] - //snippet-start:[cognito.java2.initiateauth.main] - public static AdminInitiateAuthResponse initiateAuth(CognitoIdentityProviderClient identityProviderClient, String clientId, String userName, String password, String userPoolId) { + // snippet-start:[cognito.java2.initiateauth.main] + public static AdminInitiateAuthResponse initiateAuth(CognitoIdentityProviderClient identityProviderClient, + String clientId, String userName, String password, String userPoolId) { try { - Map authParameters = new HashMap<>(); + Map authParameters = new HashMap<>(); authParameters.put("USERNAME", userName); authParameters.put("PASSWORD", password); AdminInitiateAuthRequest authRequest = AdminInitiateAuthRequest.builder() - .clientId(clientId) - .userPoolId(userPoolId) - .authParameters(authParameters) - .authFlow(AuthFlowType.ADMIN_USER_PASSWORD_AUTH) - .build(); + .clientId(clientId) + .userPoolId(userPoolId) + .authParameters(authParameters) + .authFlow(AuthFlowType.ADMIN_USER_PASSWORD_AUTH) + .build(); AdminInitiateAuthResponse response = identityProviderClient.adminInitiateAuth(authRequest); - System.out.println("Result Challenge is : " + response.challengeName() ); + System.out.println("Result Challenge is : " + response.challengeName()); return response; - } catch(CognitoIdentityProviderException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + } catch (CognitoIdentityProviderException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); } return null; } - //snippet-end:[cognito.java2.initiateauth.main] + // snippet-end:[cognito.java2.initiateauth.main] - //snippet-start:[cognito.java2.token.main] + // snippet-start:[cognito.java2.token.main] public static String getSecretForAppMFA(CognitoIdentityProviderClient identityProviderClient, String session) { AssociateSoftwareTokenRequest softwareTokenRequest = AssociateSoftwareTokenRequest.builder() - .session(session) - .build(); + .session(session) + .build(); - AssociateSoftwareTokenResponse tokenResponse = identityProviderClient.associateSoftwareToken(softwareTokenRequest) ; + AssociateSoftwareTokenResponse tokenResponse = identityProviderClient + .associateSoftwareToken(softwareTokenRequest); String secretCode = tokenResponse.secretCode(); System.out.println("Enter this token into Google Authenticator"); System.out.println(secretCode); return tokenResponse.session(); } - //snippet-end:[cognito.java2.token.main] + // snippet-end:[cognito.java2.token.main] - //snippet-start:[cognito.java2.confirm.signup.mvp.main] - public static void confirmSignUp(CognitoIdentityProviderClient identityProviderClient, String clientId, String code, String userName) { + // snippet-start:[cognito.java2.confirm.signup.mvp.main] + public static void confirmSignUp(CognitoIdentityProviderClient identityProviderClient, String clientId, String code, + String userName) { try { ConfirmSignUpRequest signUpRequest = ConfirmSignUpRequest.builder() - .clientId(clientId) - .confirmationCode(code) - .username(userName) - .build(); + .clientId(clientId) + .confirmationCode(code) + .username(userName) + .build(); identityProviderClient.confirmSignUp(signUpRequest); - System.out.println(userName +" was confirmed"); + System.out.println(userName + " was confirmed"); - } catch(CognitoIdentityProviderException e) { + } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } - //snippet-end:[cognito.java2.confirm.signup.mvp.main] + // snippet-end:[cognito.java2.confirm.signup.mvp.main] - //snippet-start:[cognito.java2.confirm.resend.mvp.main] - public static void resendConfirmationCode(CognitoIdentityProviderClient identityProviderClient, String clientId, String userName) { + // snippet-start:[cognito.java2.confirm.resend.mvp.main] + public static void resendConfirmationCode(CognitoIdentityProviderClient identityProviderClient, String clientId, + String userName) { try { ResendConfirmationCodeRequest codeRequest = ResendConfirmationCodeRequest.builder() - .clientId(clientId) - .username(userName) - .build(); + .clientId(clientId) + .username(userName) + .build(); ResendConfirmationCodeResponse response = identityProviderClient.resendConfirmationCode(codeRequest); - System.out.println("Method of delivery is "+response.codeDeliveryDetails().deliveryMediumAsString()); + System.out.println("Method of delivery is " + response.codeDeliveryDetails().deliveryMediumAsString()); - } catch(CognitoIdentityProviderException e) { + } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } - //snippet-end:[cognito.java2.confirm.resend.mvp.main] + // snippet-end:[cognito.java2.confirm.resend.mvp.main] - //snippet-start:[cognito.java2.signup.mvp.main] - public static void signUp(CognitoIdentityProviderClient identityProviderClient, String clientId, String userName, String password, String email) { + // snippet-start:[cognito.java2.signup.mvp.main] + public static void signUp(CognitoIdentityProviderClient identityProviderClient, String clientId, String userName, + String password, String email) { AttributeType userAttrs = AttributeType.builder() - .name("email") - .value(email) - .build(); + .name("email") + .value(email) + .build(); List userAttrsList = new ArrayList<>(); userAttrsList.add(userAttrs); try { SignUpRequest signUpRequest = SignUpRequest.builder() - .userAttributes(userAttrsList) - .username(userName) - .clientId(clientId) - .password(password) - .build(); + .userAttributes(userAttrsList) + .username(userName) + .clientId(clientId) + .password(password) + .build(); identityProviderClient.signUp(signUpRequest); System.out.println("User has been signed up "); - } catch(CognitoIdentityProviderException e) { + } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } - //snippet-end:[cognito.java2.signup.mvp.main] - + // snippet-end:[cognito.java2.signup.mvp.main] - //snippet-start:[cognito.java2.confirm.getuser.mvp.main] - public static void getAdminUser(CognitoIdentityProviderClient identityProviderClient, String userName, String poolId) { + // snippet-start:[cognito.java2.confirm.getuser.mvp.main] + public static void getAdminUser(CognitoIdentityProviderClient identityProviderClient, String userName, + String poolId) { try { AdminGetUserRequest userRequest = AdminGetUserRequest.builder() - .username(userName) - .userPoolId(poolId) - .build(); + .username(userName) + .userPoolId(poolId) + .build(); AdminGetUserResponse response = identityProviderClient.adminGetUser(userRequest); - System.out.println("User status "+response.userStatusAsString()); + System.out.println("User status " + response.userStatusAsString()); - } catch (CognitoIdentityProviderException e){ + } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } - //snippet-end:[cognito.java2.confirm.getuser.mvp.main] + // snippet-end:[cognito.java2.confirm.getuser.mvp.main] } -//snippet-end:[cognito.java2.mvp.main] \ No newline at end of file +// snippet-end:[cognito.java2.mvp.main] \ No newline at end of file diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/ConfirmSignUp.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/ConfirmSignUp.java index 3bb00b96ac6..e5df106f76c 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/ConfirmSignUp.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/ConfirmSignUp.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cognito; import software.amazon.awssdk.regions.Region; diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/CreateIdentityPool.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/CreateIdentityPool.java index 752b770694c..ec71f3c9ccf 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/CreateIdentityPool.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/CreateIdentityPool.java @@ -1,24 +1,20 @@ -//snippet-sourcedescription:[CreateIdentityPool.java demonstrates how to create a new Amazon Cognito identity pool. The identity pool is a store of user identity information that is specific to your AWS account.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Cognito] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cognito; -//snippet-start:[cognito.java2.create_identity_pool.main] -//snippet-start:[cognito.java2.create_identity_pool.import] +// snippet-start:[cognito.java2.create_identity_pool.main] +// snippet-start:[cognito.java2.create_identity_pool.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient; import software.amazon.awssdk.services.cognitoidentity.model.CreateIdentityPoolRequest; import software.amazon.awssdk.services.cognitoidentity.model.CreateIdentityPoolResponse; import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException; -//snippet-end:[cognito.java2.create_identity_pool.import] +// snippet-end:[cognito.java2.create_identity_pool.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,12 +23,12 @@ public class CreateIdentityPool { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - identityPoolName - The name to give your identity pool. - """; + Where: + identityPoolName - The name to give your identity pool. + """; if (args.length != 1) { System.out.println(usage); @@ -41,8 +37,8 @@ public static void main(String[] args) { String identityPoolName = args[0]; CognitoIdentityClient cognitoClient = CognitoIdentityClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); String identityPoolId = createIdPool(cognitoClient, identityPoolName); System.out.println("Unity pool ID " + identityPoolId); @@ -52,9 +48,9 @@ public static void main(String[] args) { public static String createIdPool(CognitoIdentityClient cognitoClient, String identityPoolName) { try { CreateIdentityPoolRequest poolRequest = CreateIdentityPoolRequest.builder() - .allowUnauthenticatedIdentities(false) - .identityPoolName(identityPoolName) - .build(); + .allowUnauthenticatedIdentities(false) + .identityPoolName(identityPoolName) + .build(); CreateIdentityPoolResponse response = cognitoClient.createIdentityPool(poolRequest); return response.identityPoolId(); @@ -66,4 +62,4 @@ public static String createIdPool(CognitoIdentityClient cognitoClient, String id return ""; } } -//snippet-end:[cognito.java2.create_identity_pool.main] \ No newline at end of file +// snippet-end:[cognito.java2.create_identity_pool.main] \ No newline at end of file diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/CreateUser.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/CreateUser.java index ddd5defb24d..4a7919e903a 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/CreateUser.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/CreateUser.java @@ -1,25 +1,21 @@ -//snippet-sourcedescription:[CreateUser.java demonstrates how to add a new user to your user pool.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Cognito] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cognito; -//snippet-start:[cognito.java2.new_admin_user.main] -//snippet-start:[cognito.java2.new_admin_user.import] +// snippet-start:[cognito.java2.new_admin_user.main] +// snippet-start:[cognito.java2.new_admin_user.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminCreateUserRequest; import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminCreateUserResponse; import software.amazon.awssdk.services.cognitoidentityprovider.model.AttributeType; import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException; -//snippet-end:[cognito.java2.new_admin_user.import] +// snippet-end:[cognito.java2.new_admin_user.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,15 +25,15 @@ public class CreateUser { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - userPoolId - The Id value for the user pool where the user is created. - userName - The user name for the new user. - email - The email to use for verifying the user. - password - The password for this user. - """; + Where: + userPoolId - The Id value for the user pool where the user is created. + userName - The user name for the new user. + email - The email to use for verifying the user. + password - The password for this user. + """; if (args.length != 4) { System.out.println(usage); @@ -50,35 +46,36 @@ public static void main(String[] args) { String password = args[3]; CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); createNewUser(cognitoClient, userPoolId, userName, email, password); cognitoClient.close(); } public static void createNewUser(CognitoIdentityProviderClient cognitoClient, - String userPoolId, - String name, - String email, - String password) { + String userPoolId, + String name, + String email, + String password) { try { AttributeType userAttrs = AttributeType.builder() - .name("email") - .value(email) - .build(); + .name("email") + .value(email) + .build(); AdminCreateUserRequest userRequest = AdminCreateUserRequest.builder() - .userPoolId(userPoolId) - .username(name) - .temporaryPassword(password) - .userAttributes(userAttrs) - .messageAction("SUPPRESS") - .build(); + .userPoolId(userPoolId) + .username(name) + .temporaryPassword(password) + .userAttributes(userAttrs) + .messageAction("SUPPRESS") + .build(); AdminCreateUserResponse response = cognitoClient.adminCreateUser(userRequest); - System.out.println("User " + response.user().username() + "is created. Status: " + response.user().userStatus()); + System.out.println( + "User " + response.user().username() + "is created. Status: " + response.user().userStatus()); } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -86,4 +83,4 @@ public static void createNewUser(CognitoIdentityProviderClient cognitoClient, } } } -//snippet-end:[cognito.java2.new_admin_user.main] \ No newline at end of file +// snippet-end:[cognito.java2.new_admin_user.main] \ No newline at end of file diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/CreateUserPool.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/CreateUserPool.java index ef9d83ce1ab..9fa9e2dabde 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/CreateUserPool.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/CreateUserPool.java @@ -1,24 +1,20 @@ -//snippet-sourcedescription:[CreateUserPool.java demonstrates how to create a user pool for Amazon Cognito.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Cognito] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cognito; -//snippet-start:[cognito.java2.create_user_pool.main] -//snippet-start:[cognito.java2.create_user_pool.import] +// snippet-start:[cognito.java2.create_user_pool.main] +// snippet-start:[cognito.java2.create_user_pool.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException; import software.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolRequest; import software.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolResponse; -//snippet-end:[cognito.java2.create_user_pool.import] +// snippet-end:[cognito.java2.create_user_pool.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,12 +25,12 @@ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - userPoolName - The name to give your user pool when it's created. - """; + Where: + userPoolName - The name to give your user pool when it's created. + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +39,8 @@ public static void main(String[] args) { String userPoolName = args[0]; CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); String id = createPool(cognitoClient, userPoolName); System.out.println("User pool ID: " + id); @@ -54,8 +50,8 @@ public static void main(String[] args) { public static String createPool(CognitoIdentityProviderClient cognitoClient, String userPoolName) { try { CreateUserPoolRequest request = CreateUserPoolRequest.builder() - .poolName(userPoolName) - .build(); + .poolName(userPoolName) + .build(); CreateUserPoolResponse response = cognitoClient.createUserPool(request); return response.userPool().id(); @@ -67,4 +63,4 @@ public static String createPool(CognitoIdentityProviderClient cognitoClient, Str return ""; } } -//snippet-end:[cognito.java2.create_user_pool.main] \ No newline at end of file +// snippet-end:[cognito.java2.create_user_pool.main] \ No newline at end of file diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/CreateUserPoolClient.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/CreateUserPoolClient.java index 27db08a24b2..f02118fd874 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/CreateUserPoolClient.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/CreateUserPoolClient.java @@ -1,28 +1,29 @@ -//snippet-sourcedescription:[CreateUserPoolClient.java demonstrates how to create a user pool client for Amazon Cognito.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Cognito] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cognito; -//snippet-start:[cognito.java2.user_pool.create_user_pool_client.main] -//snippet-start:[cognito.java2.user_pool.create_user_pool_client.import] +// snippet-start:[cognito.java2.user_pool.create_user_pool_client.main] +// snippet-start:[cognito.java2.user_pool.create_user_pool_client.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException; import software.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolClientRequest; import software.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolClientResponse; -//snippet-end:[cognito.java2.user_pool.create_user_pool_client.import] +// snippet-end:[cognito.java2.user_pool.create_user_pool_client.import] + /** - * A user pool client app is an application that authenticates with Amazon Cognito user pools. - * When you create a user pool, you can configure app clients that allow mobile or web applications - * to call API operations to authenticate users, manage user attributes and profiles, + * A user pool client app is an application that authenticates with Amazon + * Cognito user pools. + * When you create a user pool, you can configure app clients that allow mobile + * or web applications + * to call API operations to authenticate users, manage user attributes and + * profiles, * and implement sign-up and sign-in flows. * - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * * For more information, see the following documentation topic: * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ @@ -30,13 +31,13 @@ public class CreateUserPoolClient { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - clientName - The name for the user pool client to create. - userPoolId - The ID for the user pool. - """; + Where: + clientName - The name for the user pool client to create. + userPoolId - The ID for the user pool. + """; if (args.length != 2) { System.out.println(usage); @@ -46,22 +47,24 @@ public static void main(String[] args) { String clientName = args[0]; String userPoolId = args[1]; CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); createPoolClient(cognitoClient, clientName, userPoolId); cognitoClient.close(); } - public static void createPoolClient(CognitoIdentityProviderClient cognitoClient, String clientName, String userPoolId) { + public static void createPoolClient(CognitoIdentityProviderClient cognitoClient, String clientName, + String userPoolId) { try { CreateUserPoolClientRequest request = CreateUserPoolClientRequest.builder() - .clientName(clientName) - .userPoolId(userPoolId) - .build(); + .clientName(clientName) + .userPoolId(userPoolId) + .build(); CreateUserPoolClientResponse response = cognitoClient.createUserPoolClient(request); - System.out.println("User pool " + response.userPoolClient().clientName() + " created. ID: " + response.userPoolClient().clientId()); + System.out.println("User pool " + response.userPoolClient().clientName() + " created. ID: " + + response.userPoolClient().clientId()); } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -69,4 +72,4 @@ public static void createPoolClient(CognitoIdentityProviderClient cognitoClient, } } } -//snippet-end:[cognito.java2.user_pool.create_user_pool_client.main] \ No newline at end of file +// snippet-end:[cognito.java2.user_pool.create_user_pool_client.main] \ No newline at end of file diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/DeleteIdentityPool.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/DeleteIdentityPool.java index 480d9c3850a..ffe18e9acec 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/DeleteIdentityPool.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/DeleteIdentityPool.java @@ -1,24 +1,20 @@ -//snippet-sourcedescription:[DeleteIdentityPool.java demonstrates how to delete an existing Amazon Cognito identity pool.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Cognito] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cognito; -//snippet-start:[cognito.java2.deleteidpool.main] -//snippet-start:[cognito.java2.deleteidpool.import] +// snippet-start:[cognito.java2.deleteidpool.main] +// snippet-start:[cognito.java2.deleteidpool.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient; import software.amazon.awssdk.services.cognitoidentity.model.DeleteIdentityPoolRequest; -//snippet-end:[cognito.java2.deleteidpool.import] +// snippet-end:[cognito.java2.deleteidpool.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,12 +25,12 @@ public class DeleteIdentityPool { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - identityPoolId - The Id value of your identity pool. - """; + Where: + identityPoolId - The Id value of your identity pool. + """; if (args.length != 1) { System.out.println(usage); @@ -43,9 +39,9 @@ public static void main(String[] args) { String identityPoold = args[0]; CognitoIdentityClient cognitoIdClient = CognitoIdentityClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(ProfileCredentialsProvider.create()) + .build(); deleteIdPool(cognitoIdClient, identityPoold); cognitoIdClient.close(); @@ -55,8 +51,8 @@ public static void deleteIdPool(CognitoIdentityClient cognitoIdClient, String id try { DeleteIdentityPoolRequest identityPoolRequest = DeleteIdentityPoolRequest.builder() - .identityPoolId(identityPoold) - .build(); + .identityPoolId(identityPoold) + .build(); cognitoIdClient.deleteIdentityPool(identityPoolRequest); System.out.println("Done"); @@ -67,4 +63,4 @@ public static void deleteIdPool(CognitoIdentityClient cognitoIdClient, String id } } } -//snippet-end:[cognito.java2.deleteidpool.main] \ No newline at end of file +// snippet-end:[cognito.java2.deleteidpool.main] \ No newline at end of file diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/DeleteUserPool.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/DeleteUserPool.java index 5c1ea02c058..3819ff8182c 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/DeleteUserPool.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/DeleteUserPool.java @@ -1,23 +1,20 @@ -//snippet-sourcedescription:[DeleteUserPool.java demonstrates how to delete an existing user pool.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Cognito] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.cognito; -//snippet-start:[cognito.java2.DeleteUserPool.main] -//snippet-start:[cognito.java2.DeleteUserPool.import] +// snippet-start:[cognito.java2.DeleteUserPool.main] +// snippet-start:[cognito.java2.DeleteUserPool.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException; import software.amazon.awssdk.services.cognitoidentityprovider.model.DeleteUserPoolRequest; import software.amazon.awssdk.services.cognitoidentityprovider.model.DeleteUserPoolResponse; -//snippet-end:[cognito.java2.DeleteUserPool.import] +// snippet-end:[cognito.java2.DeleteUserPool.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +25,12 @@ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - userPoolId - The Id value given to your user pool. - """; + Where: + userPoolId - The Id value given to your user pool. + """; if (args.length != 1) { System.out.println(usage); @@ -42,8 +39,8 @@ public static void main(String[] args) { String userPoolId = args[0]; CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); deletePool(cognitoClient, userPoolId); cognitoClient.close(); @@ -52,8 +49,8 @@ public static void main(String[] args) { public static void deletePool(CognitoIdentityProviderClient cognitoClient, String userPoolId) { try { DeleteUserPoolRequest request = DeleteUserPoolRequest.builder() - .userPoolId(userPoolId) - .build(); + .userPoolId(userPoolId) + .build(); DeleteUserPoolResponse response = cognitoClient.deleteUserPool(request); System.out.println("User pool " + response.toString() + " deleted. ID: " + request.userPoolId()); @@ -64,4 +61,4 @@ public static void deletePool(CognitoIdentityProviderClient cognitoClient, Strin } } } -//snippet-end:[cognito.java2.DeleteUserPool.main] \ No newline at end of file +// snippet-end:[cognito.java2.DeleteUserPool.main] \ No newline at end of file diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/GetId.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/GetId.java index d20afb6bb5c..4f7131b609b 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/GetId.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/GetId.java @@ -1,24 +1,20 @@ -//snippet-sourcedescription:[GetId.java demonstrates how to retrieve the client ID from an identity provider.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Cognito] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cognito; -//snippet-start:[cognito.java2.GetID.main] -//snippet-start:[cognito.java2.GetId.import] +// snippet-start:[cognito.java2.GetID.main] +// snippet-start:[cognito.java2.GetId.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient; import software.amazon.awssdk.services.cognitoidentity.model.GetIdRequest; import software.amazon.awssdk.services.cognitoidentity.model.GetIdResponse; import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException; -//snippet-end:[cognito.java2.GetId.import] +// snippet-end:[cognito.java2.GetId.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,15 +24,15 @@ public class GetId { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - identityPoolId - The GUID value of your identity pool. + Where: + identityPoolId - The GUID value of your identity pool. - Example: - GetId us-east-1:00eb915b-c521-417b-af0d-ebad008axxxx - """; + Example: + GetId us-east-1:00eb915b-c521-417b-af0d-ebad008axxxx + """; if (args.length != 1) { System.out.println(usage); @@ -45,8 +41,8 @@ public static void main(String[] args) { String identityPoolId = args[0]; CognitoIdentityClient cognitoClient = CognitoIdentityClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); getClientID(cognitoClient, identityPoolId); cognitoClient.close(); @@ -55,8 +51,8 @@ public static void main(String[] args) { public static void getClientID(CognitoIdentityClient cognitoClient, String identityPoolId) { try { GetIdRequest request = GetIdRequest.builder() - .identityPoolId(identityPoolId) - .build(); + .identityPoolId(identityPoolId) + .build(); GetIdResponse response = cognitoClient.getId(request); System.out.println("Identity ID " + response.identityId()); @@ -67,4 +63,4 @@ public static void getClientID(CognitoIdentityClient cognitoClient, String ident } } } -//snippet-end:[cognito.java2.GetID.main] +// snippet-end:[cognito.java2.GetID.main] diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/GetIdentityCredentials.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/GetIdentityCredentials.java index 00e9d6f8001..e9c92fd9903 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/GetIdentityCredentials.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/GetIdentityCredentials.java @@ -1,23 +1,20 @@ -//snippet-sourcedescription:[GetIdentityCredentials.java demonstrates how to retrieve credentials for an identity in an Amazon Cognito identity pool.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Cognito] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.cognito; -//snippet-start:[cognito.java2.GetIdentityCredentials.main] -//snippet-start:[cognito.java2.GetIdentityCredentials.import] +// snippet-start:[cognito.java2.GetIdentityCredentials.main] +// snippet-start:[cognito.java2.GetIdentityCredentials.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient; import software.amazon.awssdk.services.cognitoidentity.model.GetCredentialsForIdentityRequest; import software.amazon.awssdk.services.cognitoidentity.model.GetCredentialsForIdentityResponse; import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException; -//snippet-end:[cognito.java2.GetIdentityCredentials.import] +// snippet-end:[cognito.java2.GetIdentityCredentials.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,8 +25,8 @@ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s Where: identityId - The Id of an existing identity in the format REGION:GUID. @@ -42,22 +39,29 @@ public static void main(String[] args) { String identityId = args[0]; CognitoIdentityClient cognitoClient = CognitoIdentityClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); getCredsForIdentity(cognitoClient, identityId); cognitoClient.close(); } - public static void getCredsForIdentity(CognitoIdentityClient cognitoClient, String identityId) { try { - GetCredentialsForIdentityRequest getCredentialsForIdentityRequest = GetCredentialsForIdentityRequest.builder() - .identityId(identityId) - .build(); + GetCredentialsForIdentityRequest getCredentialsForIdentityRequest = GetCredentialsForIdentityRequest + .builder() + .identityId(identityId) + .build(); +<<<<<<< HEAD GetCredentialsForIdentityResponse response = cognitoClient.getCredentialsForIdentity(getCredentialsForIdentityRequest); System.out.println("Identity ID " + response.identityId() + ", Expiration " + response.credentials().expiration()); +======= + GetCredentialsForIdentityResponse response = cognitoClient + .getCredentialsForIdentity(getCredentialsForIdentityRequest); + System.out.println( + "Identity ID " + response.identityId() + ", Access key ID " + response.credentials().accessKeyId()); +>>>>>>> 965f9e416 (Tools: Normalize & enforce SPDX headers) } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -65,4 +69,4 @@ public static void getCredsForIdentity(CognitoIdentityClient cognitoClient, Stri } } } -//snippet-end:[cognito.java2.GetIdentityCredentials.main] +// snippet-end:[cognito.java2.GetIdentityCredentials.main] diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/ListIdentities.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/ListIdentities.java index 231b73ff909..8a256da4686 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/ListIdentities.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/ListIdentities.java @@ -1,24 +1,20 @@ -//snippet-sourcedescription:[ListIdentities.java demonstrates how to list identities that belong to an Amazon Cognito identity pool.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Cognito] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cognito; -//snippet-start:[cognito.java2.listidentities.main] -//snippet-start:[cognito.java2.listidentities.import] +// snippet-start:[cognito.java2.listidentities.main] +// snippet-start:[cognito.java2.listidentities.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient; import software.amazon.awssdk.services.cognitoidentity.model.ListIdentitiesRequest; import software.amazon.awssdk.services.cognitoidentity.model.ListIdentitiesResponse; import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException; -//snippet-end:[cognito.java2.listidentities.import] +// snippet-end:[cognito.java2.listidentities.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +24,12 @@ public class ListIdentities { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - identityPoolId - The id value of your identity pool (for example, us-east-1:00eb915b-c521-417b-af0d-ebad008axxxx). - """; + Where: + identityPoolId - The id value of your identity pool (for example, us-east-1:00eb915b-c521-417b-af0d-ebad008axxxx). + """; if (args.length != 1) { System.out.println(usage); @@ -42,8 +38,8 @@ public static void main(String[] args) { String identityPoolId = args[0]; CognitoIdentityClient cognitoClient = CognitoIdentityClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); listPoolIdentities(cognitoClient, identityPoolId); cognitoClient.close(); @@ -52,9 +48,9 @@ public static void main(String[] args) { public static void listPoolIdentities(CognitoIdentityClient cognitoClient, String identityPoolId) { try { ListIdentitiesRequest identitiesRequest = ListIdentitiesRequest.builder() - .identityPoolId(identityPoolId) - .maxResults(15) - .build(); + .identityPoolId(identityPoolId) + .maxResults(15) + .build(); ListIdentitiesResponse response = cognitoClient.listIdentities(identitiesRequest); response.identities().forEach(identity -> { @@ -67,4 +63,4 @@ public static void listPoolIdentities(CognitoIdentityClient cognitoClient, Strin } } } -//snippet-end:[cognito.java2.listidentities.main] \ No newline at end of file +// snippet-end:[cognito.java2.listidentities.main] \ No newline at end of file diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/ListIdentityPools.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/ListIdentityPools.java index 369c8b322f4..26b04092954 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/ListIdentityPools.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/ListIdentityPools.java @@ -1,24 +1,20 @@ -//snippet-sourcedescription:[ListIdentityPools.java demonstrates how to list Amazon Cognito identity pools.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Cognito] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cognito; -//snippet-start:[cognito.java2.listidentitypools.main] -//snippet-start:[cognito.java2.listidentitypools.import] +// snippet-start:[cognito.java2.listidentitypools.main] +// snippet-start:[cognito.java2.listidentitypools.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient; import software.amazon.awssdk.services.cognitoidentity.model.ListIdentityPoolsRequest; import software.amazon.awssdk.services.cognitoidentity.model.ListIdentityPoolsResponse; import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException; -//snippet-end:[cognito.java2.listidentitypools.import] +// snippet-end:[cognito.java2.listidentitypools.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,8 +23,8 @@ public class ListIdentityPools { public static void main(String[] args) { CognitoIdentityClient cognitoClient = CognitoIdentityClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); listIdPools(cognitoClient); cognitoClient.close(); @@ -37,8 +33,8 @@ public static void main(String[] args) { public static void listIdPools(CognitoIdentityClient cognitoClient) { try { ListIdentityPoolsRequest poolsRequest = ListIdentityPoolsRequest.builder() - .maxResults(15) - .build(); + .maxResults(15) + .build(); ListIdentityPoolsResponse response = cognitoClient.listIdentityPools(poolsRequest); response.identityPools().forEach(pool -> { @@ -52,4 +48,4 @@ public static void listIdPools(CognitoIdentityClient cognitoClient) { } } } -//snippet-end:[cognito.java2.listidentitypools.main] +// snippet-end:[cognito.java2.listidentitypools.main] diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/ListUserPoolClients.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/ListUserPoolClients.java index 37072923742..e0ba5ac4fc3 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/ListUserPoolClients.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/ListUserPoolClients.java @@ -1,23 +1,20 @@ -//snippet-sourcedescription:[ListUserPoolClients.java demonstrates how to list existing user pool clients that are available in the specified AWS Region in your current AWS account.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Cognito] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.cognito; -//snippet-start:[cognito.java2.ListUserPoolClients.main] -//snippet-start:[cognito.java2.ListUserPoolClients.import] +// snippet-start:[cognito.java2.ListUserPoolClients.main] +// snippet-start:[cognito.java2.ListUserPoolClients.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException; import software.amazon.awssdk.services.cognitoidentityprovider.model.ListUserPoolClientsRequest; import software.amazon.awssdk.services.cognitoidentityprovider.model.ListUserPoolClientsResponse; -//snippet-end:[cognito.java2.ListUserPoolClients.import] +// snippet-end:[cognito.java2.ListUserPoolClients.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +25,12 @@ public class ListUserPoolClients { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - userPoolId - The ID given to your user pool. - """; + Where: + userPoolId - The ID given to your user pool. + """; if (args.length != 1) { System.out.println(usage); @@ -42,8 +39,8 @@ public static void main(String[] args) { String userPoolId = args[0]; CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); listAllUserPoolClients(cognitoClient, userPoolId); cognitoClient.close(); @@ -51,12 +48,14 @@ public static void main(String[] args) { public static void listAllUserPoolClients(CognitoIdentityProviderClient cognitoClient, String userPoolId) { try { - ListUserPoolClientsResponse response = cognitoClient.listUserPoolClients(ListUserPoolClientsRequest.builder() - .userPoolId(userPoolId) - .build()); + ListUserPoolClientsResponse response = cognitoClient + .listUserPoolClients(ListUserPoolClientsRequest.builder() + .userPoolId(userPoolId) + .build()); response.userPoolClients().forEach(userPoolClient -> { - System.out.println("User pool client " + userPoolClient.clientName() + ", Pool ID " + userPoolClient.userPoolId() + ", Client ID " + userPoolClient.clientId()); + System.out.println("User pool client " + userPoolClient.clientName() + ", Pool ID " + + userPoolClient.userPoolId() + ", Client ID " + userPoolClient.clientId()); }); } catch (CognitoIdentityProviderException e) { @@ -65,4 +64,4 @@ public static void listAllUserPoolClients(CognitoIdentityProviderClient cognitoC } } } -//snippet-end:[cognito.java2.ListUserPoolClients.main] \ No newline at end of file +// snippet-end:[cognito.java2.ListUserPoolClients.main] \ No newline at end of file diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/ListUserPools.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/ListUserPools.java index 7d18089486c..5e76c52d4c5 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/ListUserPools.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/ListUserPools.java @@ -1,25 +1,21 @@ -//snippet-sourcedescription:[ListUserPools.java demonstrates how to to list existing users in the specified user pool.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Cognito] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cognito; -//snippet-start:[cognito.java2.hello.main] -//snippet-start:[cognito.java2.ListUserPools.main] -//snippet-start:[cognito.java2.ListUserPools.import] +// snippet-start:[cognito.java2.hello.main] +// snippet-start:[cognito.java2.ListUserPools.main] +// snippet-start:[cognito.java2.ListUserPools.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException; import software.amazon.awssdk.services.cognitoidentityprovider.model.ListUserPoolsResponse; import software.amazon.awssdk.services.cognitoidentityprovider.model.ListUserPoolsRequest; -//snippet-end:[cognito.java2.ListUserPools.import] +// snippet-end:[cognito.java2.ListUserPools.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,29 +24,29 @@ public class ListUserPools { public static void main(String[] args) { CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); - listAllUserPools(cognitoClient) ; + listAllUserPools(cognitoClient); cognitoClient.close(); } - public static void listAllUserPools(CognitoIdentityProviderClient cognitoClient ) { + public static void listAllUserPools(CognitoIdentityProviderClient cognitoClient) { try { ListUserPoolsRequest request = ListUserPoolsRequest.builder() - .maxResults(10) - .build(); + .maxResults(10) + .build(); ListUserPoolsResponse response = cognitoClient.listUserPools(request); response.userPools().forEach(userpool -> { - System.out.println("User pool " + userpool.name() + ", User ID " + userpool.id() ); + System.out.println("User pool " + userpool.name() + ", User ID " + userpool.id()); }); - } catch (CognitoIdentityProviderException e){ + } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } -//snippet-end:[cognito.java2.ListUserPools.main] -//snippet-end:[cognito.java2.hello.main] \ No newline at end of file +// snippet-end:[cognito.java2.ListUserPools.main] +// snippet-end:[cognito.java2.hello.main] \ No newline at end of file diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/ListUsers.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/ListUsers.java index 63f48a38262..4241cc35814 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/ListUsers.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/ListUsers.java @@ -1,23 +1,20 @@ -//snippet-sourcedescription:[ListUsers.java demonstrates how to list users in the specified user pool.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Cognito] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cognito; -//snippet-start:[cognito.java2.ListUsers.main] -//snippet-start:[cognito.java2.ListUsers.import] + +// snippet-start:[cognito.java2.ListUsers.main] +// snippet-start:[cognito.java2.ListUsers.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException; import software.amazon.awssdk.services.cognitoidentityprovider.model.ListUsersRequest; import software.amazon.awssdk.services.cognitoidentityprovider.model.ListUsersResponse; -//snippet-end:[cognito.java2.ListUsers.import] +// snippet-end:[cognito.java2.ListUsers.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +25,12 @@ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - userPoolId - The ID given to your user pool when it's created. - """; + Where: + userPoolId - The ID given to your user pool when it's created. + """; if (args.length != 1) { System.out.println(usage); @@ -42,50 +39,52 @@ public static void main(String[] args) { String userPoolId = args[0]; CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); - listAllUsers(cognitoClient, userPoolId ); - listUsersFilter(cognitoClient, userPoolId ); + listAllUsers(cognitoClient, userPoolId); + listUsersFilter(cognitoClient, userPoolId); cognitoClient.close(); } - public static void listAllUsers(CognitoIdentityProviderClient cognitoClient, String userPoolId ) { + public static void listAllUsers(CognitoIdentityProviderClient cognitoClient, String userPoolId) { try { ListUsersRequest usersRequest = ListUsersRequest.builder() - .userPoolId(userPoolId) - .build(); + .userPoolId(userPoolId) + .build(); ListUsersResponse response = cognitoClient.listUsers(usersRequest); response.users().forEach(user -> { - System.out.println("User " + user.username() + " Status " + user.userStatus() + " Created " + user.userCreateDate() ); + System.out.println("User " + user.username() + " Status " + user.userStatus() + " Created " + + user.userCreateDate()); }); - } catch (CognitoIdentityProviderException e){ + } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } // Shows how to list users by using a filter. - public static void listUsersFilter(CognitoIdentityProviderClient cognitoClient, String userPoolId ) { + public static void listUsersFilter(CognitoIdentityProviderClient cognitoClient, String userPoolId) { try { String filter = "email = \"tblue@noserver.com\""; ListUsersRequest usersRequest = ListUsersRequest.builder() - .userPoolId(userPoolId) - .filter(filter) - .build(); + .userPoolId(userPoolId) + .filter(filter) + .build(); ListUsersResponse response = cognitoClient.listUsers(usersRequest); response.users().forEach(user -> { - System.out.println("User with filter applied " + user.username() + " Status " + user.userStatus() + " Created " + user.userCreateDate() ); + System.out.println("User with filter applied " + user.username() + " Status " + user.userStatus() + + " Created " + user.userCreateDate()); }); - } catch (CognitoIdentityProviderException e){ + } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } -//snippet-end:[cognito.java2.ListUsers.main] \ No newline at end of file +// snippet-end:[cognito.java2.ListUsers.main] \ No newline at end of file diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/SignUpUser.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/SignUpUser.java index 8f11e752381..b2d01183682 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/SignUpUser.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/SignUpUser.java @@ -1,15 +1,10 @@ -//snippet-sourcedescription:[SignUp.java demonstrates how to register a user in the specified Amazon Cognito user pool.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Cognito] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cognito; -//snippet-start:[cognito.java2.signup.main] -//snippet-start:[cognito.java2.signup.import] +// snippet-start:[cognito.java2.signup.main] +// snippet-start:[cognito.java2.signup.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException; @@ -22,15 +17,16 @@ import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; -//snippet-end:[cognito.java2.signup.import] +// snippet-end:[cognito.java2.signup.import] /** - * To run this Java code example, you need to create a client app in a user pool with a secret key. For details, see: + * To run this Java code example, you need to create a client app in a user pool + * with a secret key. For details, see: * https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-client-apps.html * * In addition, set up your development environment, including your credentials. * - * For more information, see the following documentation topic: + * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * @@ -41,16 +37,16 @@ public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - clientId - The app client id value that you can obtain from the AWS Management Console. - secretkey - The app client secret value that you can obtain from the AWS Management Console. - userName - The user name of the user you wish to register. - password - The password for the user. - email - The email address for the user. - """; + Where: + clientId - The app client id value that you can obtain from the AWS Management Console. + secretkey - The app client secret value that you can obtain from the AWS Management Console. + userName - The user name of the user you wish to register. + password - The password for the user. + email - The email address for the user. + """; if (args.length != 5) { System.out.println(usage); @@ -64,36 +60,36 @@ public static void main(String[] args) { String email = args[4]; CognitoIdentityProviderClient identityProviderClient = CognitoIdentityProviderClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); signUp(identityProviderClient, clientId, secretKey, userName, password, email); identityProviderClient.close(); } public static void signUp(CognitoIdentityProviderClient identityProviderClient, - String clientId, - String secretKey, - String userName, - String password, - String email) { + String clientId, + String secretKey, + String userName, + String password, + String email) { AttributeType attributeType = AttributeType.builder() - .name("email") - .value(email) - .build(); + .name("email") + .value(email) + .build(); List attrs = new ArrayList<>(); attrs.add(attributeType); try { String secretVal = calculateSecretHash(clientId, secretKey, userName); SignUpRequest signUpRequest = SignUpRequest.builder() - .userAttributes(attrs) - .username(userName) - .clientId(clientId) - .password(password) - .secretHash(secretVal) - .build(); + .userAttributes(attrs) + .username(userName) + .clientId(clientId) + .password(password) + .secretHash(secretVal) + .build(); identityProviderClient.signUp(signUpRequest); System.out.println("User has been signed up"); @@ -108,12 +104,13 @@ public static void signUp(CognitoIdentityProviderClient identityProviderClient, } } - public static String calculateSecretHash(String userPoolClientId, String userPoolClientSecret, String userName) throws NoSuchAlgorithmException, InvalidKeyException { + public static String calculateSecretHash(String userPoolClientId, String userPoolClientSecret, String userName) + throws NoSuchAlgorithmException, InvalidKeyException { final String HMAC_SHA256_ALGORITHM = "HmacSHA256"; SecretKeySpec signingKey = new SecretKeySpec( - userPoolClientSecret.getBytes(StandardCharsets.UTF_8), - HMAC_SHA256_ALGORITHM); + userPoolClientSecret.getBytes(StandardCharsets.UTF_8), + HMAC_SHA256_ALGORITHM); Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM); mac.init(signingKey); @@ -122,5 +119,4 @@ public static String calculateSecretHash(String userPoolClientId, String userPoo return java.util.Base64.getEncoder().encodeToString(rawHmac); } } -//snippet-end:[cognito.java2.signup.main] - +// snippet-end:[cognito.java2.signup.main] diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/SRPDemo.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/SRPDemo.java index 90a97ab20e9..03405612993 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/SRPDemo.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/SRPDemo.java @@ -1,16 +1,6 @@ -/* Copyright 2010-2023 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.cognito.srp; import com.example.cognito.srp.usecases.*; @@ -21,116 +11,127 @@ import java.util.Scanner; public class SRPDemo { - private static final String COGNITO_USERNAME = "test_user-auth-device-tracking"; - private static final String COGNITO_PASSWORD = "changeme-0okm9IJN~"; - private static final String COGNITO_POOL_ID; - private static final String COGNITO_USER_CLIENT_ID; - private static final String COGNITO_ADMIN_CLIENT_ID; - private static final String COGNITO_ADMIN_CLIENT_SECRET; - private static final CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder() - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + private static final String COGNITO_USERNAME = "test_user-auth-device-tracking"; + private static final String COGNITO_PASSWORD = "changeme-0okm9IJN~"; + private static final String COGNITO_POOL_ID; + private static final String COGNITO_USER_CLIENT_ID; + private static final String COGNITO_ADMIN_CLIENT_ID; + private static final String COGNITO_ADMIN_CLIENT_SECRET; + private static final CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder() + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); - static { - // Create user pool. - DeviceConfigurationType deviceConfig = DeviceConfigurationType.builder() - .challengeRequiredOnNewDevice(true) - .deviceOnlyRememberedOnUserPrompt(true) - .build(); - CreateUserPoolRequest poolRequest = CreateUserPoolRequest.builder() - .poolName("my awesome user pool") - .deviceConfiguration(deviceConfig) - .build(); - CreateUserPoolResponse pool = cognitoClient.createUserPool(poolRequest); - COGNITO_POOL_ID = pool.userPool().id(); - System.out.println("User pool is: " + COGNITO_POOL_ID); - SetUserPoolMfaConfigRequest mfaRequest = SetUserPoolMfaConfigRequest.builder() - .userPoolId(COGNITO_POOL_ID) - .mfaConfiguration(UserPoolMfaType.ON) - .softwareTokenMfaConfiguration(SoftwareTokenMfaConfigType.builder().enabled(true).build()) - .build(); - cognitoClient.setUserPoolMfaConfig(mfaRequest); - // Create user application client. - CreateUserPoolClientRequest userClientRequest = CreateUserPoolClientRequest.builder() - .clientName("my awesome application client for user") - .userPoolId(COGNITO_POOL_ID) - .explicitAuthFlows(ExplicitAuthFlowsType.ALLOW_USER_SRP_AUTH, ExplicitAuthFlowsType.ALLOW_REFRESH_TOKEN_AUTH) - .generateSecret(false) - .build(); - CreateUserPoolClientResponse userClientResponse = cognitoClient.createUserPoolClient(userClientRequest); - COGNITO_USER_CLIENT_ID = userClientResponse.userPoolClient().clientId(); - System.out.println("Application client for user is: " + COGNITO_USER_CLIENT_ID); - // Create admin application client. - CreateUserPoolClientRequest adminClientRequest = CreateUserPoolClientRequest.builder() - .clientName("my awesome application client for admin") - .userPoolId(COGNITO_POOL_ID) - .explicitAuthFlows(ExplicitAuthFlowsType.ALLOW_ADMIN_USER_PASSWORD_AUTH, ExplicitAuthFlowsType.ALLOW_REFRESH_TOKEN_AUTH) - .generateSecret(true) - .build(); - CreateUserPoolClientResponse adminClientResponse = cognitoClient.createUserPoolClient(adminClientRequest); - COGNITO_ADMIN_CLIENT_ID = adminClientResponse.userPoolClient().clientId(); - COGNITO_ADMIN_CLIENT_SECRET = adminClientResponse.userPoolClient().clientSecret(); - System.out.println("Application client for admin is: " + COGNITO_ADMIN_CLIENT_ID); - // Create user. - AdminCreateUserRequest userRequest = AdminCreateUserRequest.builder() - .userPoolId(COGNITO_POOL_ID) - .username(COGNITO_USERNAME) - .build(); - cognitoClient.adminCreateUser(userRequest); - AdminSetUserPasswordRequest passwordRequest = AdminSetUserPasswordRequest.builder() - .userPoolId(COGNITO_POOL_ID) - .username(COGNITO_USERNAME) - .password(COGNITO_PASSWORD) - .permanent(true) - .build(); - cognitoClient.adminSetUserPassword(passwordRequest); - } + static { + // Create user pool. + DeviceConfigurationType deviceConfig = DeviceConfigurationType.builder() + .challengeRequiredOnNewDevice(true) + .deviceOnlyRememberedOnUserPrompt(true) + .build(); + CreateUserPoolRequest poolRequest = CreateUserPoolRequest.builder() + .poolName("my awesome user pool") + .deviceConfiguration(deviceConfig) + .build(); + CreateUserPoolResponse pool = cognitoClient.createUserPool(poolRequest); + COGNITO_POOL_ID = pool.userPool().id(); + System.out.println("User pool is: " + COGNITO_POOL_ID); + SetUserPoolMfaConfigRequest mfaRequest = SetUserPoolMfaConfigRequest.builder() + .userPoolId(COGNITO_POOL_ID) + .mfaConfiguration(UserPoolMfaType.ON) + .softwareTokenMfaConfiguration( + SoftwareTokenMfaConfigType.builder().enabled(true).build()) + .build(); + cognitoClient.setUserPoolMfaConfig(mfaRequest); + // Create user application client. + CreateUserPoolClientRequest userClientRequest = CreateUserPoolClientRequest.builder() + .clientName("my awesome application client for user") + .userPoolId(COGNITO_POOL_ID) + .explicitAuthFlows(ExplicitAuthFlowsType.ALLOW_USER_SRP_AUTH, + ExplicitAuthFlowsType.ALLOW_REFRESH_TOKEN_AUTH) + .generateSecret(false) + .build(); + CreateUserPoolClientResponse userClientResponse = cognitoClient.createUserPoolClient(userClientRequest); + COGNITO_USER_CLIENT_ID = userClientResponse.userPoolClient().clientId(); + System.out.println("Application client for user is: " + COGNITO_USER_CLIENT_ID); + // Create admin application client. + CreateUserPoolClientRequest adminClientRequest = CreateUserPoolClientRequest.builder() + .clientName("my awesome application client for admin") + .userPoolId(COGNITO_POOL_ID) + .explicitAuthFlows(ExplicitAuthFlowsType.ALLOW_ADMIN_USER_PASSWORD_AUTH, + ExplicitAuthFlowsType.ALLOW_REFRESH_TOKEN_AUTH) + .generateSecret(true) + .build(); + CreateUserPoolClientResponse adminClientResponse = cognitoClient + .createUserPoolClient(adminClientRequest); + COGNITO_ADMIN_CLIENT_ID = adminClientResponse.userPoolClient().clientId(); + COGNITO_ADMIN_CLIENT_SECRET = adminClientResponse.userPoolClient().clientSecret(); + System.out.println("Application client for admin is: " + COGNITO_ADMIN_CLIENT_ID); + // Create user. + AdminCreateUserRequest userRequest = AdminCreateUserRequest.builder() + .userPoolId(COGNITO_POOL_ID) + .username(COGNITO_USERNAME) + .build(); + cognitoClient.adminCreateUser(userRequest); + AdminSetUserPasswordRequest passwordRequest = AdminSetUserPasswordRequest.builder() + .userPoolId(COGNITO_POOL_ID) + .username(COGNITO_USERNAME) + .password(COGNITO_PASSWORD) + .permanent(true) + .build(); + cognitoClient.adminSetUserPassword(passwordRequest); + } - public static void main(String[] args) { - // 1. Start authentication with Admin credentials. - AdminInitiateAuthResponse authResponse = new AdminAuthDemo(cognitoClient, COGNITO_POOL_ID, COGNITO_ADMIN_CLIENT_ID, COGNITO_ADMIN_CLIENT_SECRET) - .adminInitiateAuth(COGNITO_USERNAME, COGNITO_PASSWORD); - System.out.println(authResponse); + public static void main(String[] args) { + // 1. Start authentication with Admin credentials. + AdminInitiateAuthResponse authResponse = new AdminAuthDemo(cognitoClient, COGNITO_POOL_ID, + COGNITO_ADMIN_CLIENT_ID, COGNITO_ADMIN_CLIENT_SECRET) + .adminInitiateAuth(COGNITO_USERNAME, COGNITO_PASSWORD); + System.out.println(authResponse); - // 2. Get a token to associate an MFA application. - String session = authResponse.session(); - AssociateSoftwareTokenResponse associateResponse = new SoftwareTokenMFADemo(cognitoClient).associateSoftwareToken(session); - session = associateResponse.session(); - String secretCode = associateResponse.secretCode(); - System.out.println("Please enter this token into Google Authenticator: " + secretCode); + // 2. Get a token to associate an MFA application. + String session = authResponse.session(); + AssociateSoftwareTokenResponse associateResponse = new SoftwareTokenMFADemo(cognitoClient) + .associateSoftwareToken(session); + session = associateResponse.session(); + String secretCode = associateResponse.secretCode(); + System.out.println("Please enter this token into Google Authenticator: " + secretCode); - Scanner scanner = new Scanner(System.in); - System.out.println("Enter TOTP from Google authenticator: "); - String code = scanner.nextLine(); - VerifySoftwareTokenResponse verifyResponse = new SoftwareTokenMFADemo(cognitoClient).verifySoftwareToken(session, code); + Scanner scanner = new Scanner(System.in); + System.out.println("Enter TOTP from Google authenticator: "); + String code = scanner.nextLine(); + VerifySoftwareTokenResponse verifyResponse = new SoftwareTokenMFADemo(cognitoClient) + .verifySoftwareToken(session, code); - // 3. Respond to an auth challenge [MFA_SETUP]. - session = verifyResponse.session(); - AdminRespondToAuthChallengeResponse challengeResponse = new AdminAuthDemo(cognitoClient, COGNITO_POOL_ID, COGNITO_ADMIN_CLIENT_ID, COGNITO_ADMIN_CLIENT_SECRET) - .adminRespondToAuthChallenge(session, COGNITO_USERNAME); - System.out.println("Challenge response: " + challengeResponse); + // 3. Respond to an auth challenge [MFA_SETUP]. + session = verifyResponse.session(); + AdminRespondToAuthChallengeResponse challengeResponse = new AdminAuthDemo(cognitoClient, + COGNITO_POOL_ID, COGNITO_ADMIN_CLIENT_ID, COGNITO_ADMIN_CLIENT_SECRET) + .adminRespondToAuthChallenge(session, COGNITO_USERNAME); + System.out.println("Challenge response: " + challengeResponse); - // 4. Confirm an MFA device for tracking. - String accessToken = challengeResponse.authenticationResult().accessToken(); - String deviceGroupKey = challengeResponse.authenticationResult().newDeviceMetadata().deviceGroupKey(); - String deviceKey = challengeResponse.authenticationResult().newDeviceMetadata().deviceKey(); - String deviceName = "my cool device name"; - String devicePassword = "my secret device password"; - ConfirmDeviceResponse confirmResponse = new DeviceTrackingDemo(cognitoClient) - .confirmDevice(accessToken, deviceGroupKey, deviceKey, deviceName, devicePassword); - System.out.println("Confirm response: " + confirmResponse); - if (confirmResponse.userConfirmationNecessary()) { - UpdateDeviceStatusResponse deviceResponse = new DeviceTrackingDemo(cognitoClient) - .updateDeviceStatus(accessToken, deviceKey); - } + // 4. Confirm an MFA device for tracking. + String accessToken = challengeResponse.authenticationResult().accessToken(); + String deviceGroupKey = challengeResponse.authenticationResult().newDeviceMetadata().deviceGroupKey(); + String deviceKey = challengeResponse.authenticationResult().newDeviceMetadata().deviceKey(); + String deviceName = "my cool device name"; + String devicePassword = "my secret device password"; + ConfirmDeviceResponse confirmResponse = new DeviceTrackingDemo(cognitoClient) + .confirmDevice(accessToken, deviceGroupKey, deviceKey, deviceName, devicePassword); + System.out.println("Confirm response: " + confirmResponse); + if (confirmResponse.userConfirmationNecessary()) { + UpdateDeviceStatusResponse deviceResponse = new DeviceTrackingDemo(cognitoClient) + .updateDeviceStatus(accessToken, deviceKey); + } - // 5. User SRP auth. - RespondToAuthChallengeResponse userSrpResponse = new UserAuthDemo(cognitoClient, COGNITO_POOL_ID, COGNITO_USER_CLIENT_ID) - .userSrpAuth(COGNITO_USERNAME, COGNITO_PASSWORD, deviceKey); - System.out.println("User SRP response: " + userSrpResponse); + // 5. User SRP auth. + RespondToAuthChallengeResponse userSrpResponse = new UserAuthDemo(cognitoClient, COGNITO_POOL_ID, + COGNITO_USER_CLIENT_ID) + .userSrpAuth(COGNITO_USERNAME, COGNITO_PASSWORD, deviceKey); + System.out.println("User SRP response: " + userSrpResponse); - // 6. Device SRP Auth. - RespondToAuthChallengeResponse deviceSrpResponse = new DeviceAuthDemo(cognitoClient, COGNITO_USER_CLIENT_ID).deviceSrpAuth(COGNITO_USERNAME, deviceGroupKey, deviceKey, devicePassword); - System.out.println("Device SRP response: " + deviceSrpResponse); - } + // 6. Device SRP Auth. + RespondToAuthChallengeResponse deviceSrpResponse = new DeviceAuthDemo(cognitoClient, + COGNITO_USER_CLIENT_ID) + .deviceSrpAuth(COGNITO_USERNAME, deviceGroupKey, deviceKey, devicePassword); + System.out.println("Device SRP response: " + deviceSrpResponse); + } } diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/usecases/AdminAuthDemo.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/usecases/AdminAuthDemo.java index 907d1f58f1d..a7d44cae00f 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/usecases/AdminAuthDemo.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/usecases/AdminAuthDemo.java @@ -1,16 +1,6 @@ -/* Copyright 2010-2023 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.cognito.srp.usecases; import java.util.HashMap; @@ -21,7 +11,6 @@ import software.amazon.awssdk.services.cognitoidentityprovider.model.*; import software.amazon.awssdk.utils.StringUtils; - public class AdminAuthDemo { private final CognitoIdentityProviderClient cognitoClient; @@ -29,7 +18,8 @@ public class AdminAuthDemo { private final String clientId; private final String clientSecret; - public AdminAuthDemo(CognitoIdentityProviderClient cognitoClient, String poolId, String clientId, String clientSecret) { + public AdminAuthDemo(CognitoIdentityProviderClient cognitoClient, String poolId, String clientId, + String clientSecret) { this.cognitoClient = cognitoClient; this.poolId = poolId; this.clientId = clientId; @@ -37,7 +27,7 @@ public AdminAuthDemo(CognitoIdentityProviderClient cognitoClient, String poolId, } public AdminInitiateAuthResponse adminInitiateAuth(String username, String password) { - Map authParameters = new HashMap<>(); + Map authParameters = new HashMap<>(); authParameters.put("USERNAME", username); authParameters.put("PASSWORD", password); @@ -56,7 +46,7 @@ public AdminInitiateAuthResponse adminInitiateAuth(String username, String passw try { AdminInitiateAuthResponse response = this.cognitoClient.adminInitiateAuth(authRequest); return response; - } catch(CognitoIdentityProviderException e) { + } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } @@ -82,9 +72,10 @@ public AdminRespondToAuthChallengeResponse adminRespondToAuthChallenge(String se .build(); try { - AdminRespondToAuthChallengeResponse response = this.cognitoClient.adminRespondToAuthChallenge(challengeRequest); + AdminRespondToAuthChallengeResponse response = this.cognitoClient + .adminRespondToAuthChallenge(challengeRequest); return response; - } catch(CognitoIdentityProviderException e) { + } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/usecases/DeviceAuthDemo.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/usecases/DeviceAuthDemo.java index d96c1d20c75..12f648efaeb 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/usecases/DeviceAuthDemo.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/usecases/DeviceAuthDemo.java @@ -1,16 +1,6 @@ -/* Copyright 2010-2023 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.cognito.srp.usecases; import com.example.cognito.srp.utils.SRPUtils; @@ -32,11 +22,13 @@ public DeviceAuthDemo(CognitoIdentityProviderClient cognitoClient, String client this.clientId = clientId; } - public RespondToAuthChallengeResponse deviceSrpAuth(String username, String deviceGroupKey, String deviceKey, String devicePassword) { + public RespondToAuthChallengeResponse deviceSrpAuth(String username, String deviceGroupKey, String deviceKey, + String devicePassword) { Pair clientKeys = SRPUtils.generateSrpClientKeys(); BigInteger a = clientKeys.left(); BigInteger A = clientKeys.right(); - RespondToAuthChallengeResponse deviceSrpChallengeResponse = respondToDeviceSrpAuthChallenge(username, deviceKey, A.toString(16)); + RespondToAuthChallengeResponse deviceSrpChallengeResponse = respondToDeviceSrpAuthChallenge(username, deviceKey, + A.toString(16)); System.out.println("DeviceSrpAuth response: " + deviceSrpChallengeResponse); // Get response from SRP initial auth. BigInteger B = new BigInteger(deviceSrpChallengeResponse.challengeParameters().get("SRP_B"), 16); @@ -47,7 +39,7 @@ public RespondToAuthChallengeResponse deviceSrpAuth(String username, String devi String timestamp = SRPUtils.getCurrentTimestamp(); System.out.println("Current timestamp: " + timestamp); byte[] passwordClaimSignature = SRPUtils.calculatePasswordClaimSignature( - deviceGroupKey+deviceKey, devicePassword, timestamp, + deviceGroupKey + deviceKey, devicePassword, timestamp, a, A, B, salt, Base64.getDecoder().decode(secretBlock)); @@ -58,7 +50,7 @@ public RespondToAuthChallengeResponse deviceSrpAuth(String username, String devi } public RespondToAuthChallengeResponse respondToDeviceSrpAuthChallenge(String username, String deviceKey, String A) { - Map challengeResponses = new HashMap<>(); + Map challengeResponses = new HashMap<>(); challengeResponses.put("USERNAME", username); challengeResponses.put("DEVICE_KEY", deviceKey); challengeResponses.put("SRP_A", A); @@ -72,7 +64,7 @@ public RespondToAuthChallengeResponse respondToDeviceSrpAuthChallenge(String use try { RespondToAuthChallengeResponse response = this.cognitoClient.respondToAuthChallenge(challengeRequest); return response; - } catch(CognitoIdentityProviderException e) { + } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } @@ -80,7 +72,7 @@ public RespondToAuthChallengeResponse respondToDeviceSrpAuthChallenge(String use } public RespondToAuthChallengeResponse respondToAuthChallenge(String username, String secretBlock, String timestamp, - String passwordClaimSignature, String deviceKey) { + String passwordClaimSignature, String deviceKey) { Map challengeResponses = new HashMap<>(); challengeResponses.put("USERNAME", username); challengeResponses.put("PASSWORD_CLAIM_SECRET_BLOCK", secretBlock); @@ -88,7 +80,6 @@ public RespondToAuthChallengeResponse respondToAuthChallenge(String username, St challengeResponses.put("TIMESTAMP", timestamp); challengeResponses.put("DEVICE_KEY", deviceKey); - RespondToAuthChallengeRequest challengeRequest = RespondToAuthChallengeRequest.builder() .clientId(clientId) .challengeName(ChallengeNameType.DEVICE_PASSWORD_VERIFIER) @@ -98,7 +89,7 @@ public RespondToAuthChallengeResponse respondToAuthChallenge(String username, St try { RespondToAuthChallengeResponse response = this.cognitoClient.respondToAuthChallenge(challengeRequest); return response; - } catch(CognitoIdentityProviderException e) { + } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/usecases/DeviceTrackingDemo.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/usecases/DeviceTrackingDemo.java index f4305a54952..400c57922fb 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/usecases/DeviceTrackingDemo.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/usecases/DeviceTrackingDemo.java @@ -1,16 +1,6 @@ -/* Copyright 2010-2023 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.cognito.srp.usecases; import com.example.cognito.srp.utils.SRPUtils; @@ -30,9 +20,11 @@ public DeviceTrackingDemo(CognitoIdentityProviderClient cognitoClient) { this.cognitoClient = cognitoClient; } - public ConfirmDeviceResponse confirmDevice(String accessToken, String deviceGroupKey, String deviceKey, String deviceName, String devicePassword) { + public ConfirmDeviceResponse confirmDevice(String accessToken, String deviceGroupKey, String deviceKey, + String deviceName, String devicePassword) { BigInteger salt = SRPUtils.generateSalt(); - BigInteger passwordVerifier = SRPUtils.generatePasswordVerifier(deviceGroupKey + deviceKey, devicePassword, salt); + BigInteger passwordVerifier = SRPUtils.generatePasswordVerifier(deviceGroupKey + deviceKey, devicePassword, + salt); DeviceSecretVerifierConfigType verifierConfig = DeviceSecretVerifierConfigType.builder() .salt(Base64.getEncoder().encodeToString(salt.toByteArray())) diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/usecases/SoftwareTokenMFADemo.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/usecases/SoftwareTokenMFADemo.java index c8654f8c92a..c361bb2d6bf 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/usecases/SoftwareTokenMFADemo.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/usecases/SoftwareTokenMFADemo.java @@ -1,16 +1,5 @@ -/* Copyright 2010-2023 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.cognito.srp.usecases; import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient; diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/usecases/UserAuthDemo.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/usecases/UserAuthDemo.java index a2efcdb8f7b..31122b74b79 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/usecases/UserAuthDemo.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/usecases/UserAuthDemo.java @@ -1,16 +1,6 @@ -/* Copyright 2010-2023 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.cognito.srp.usecases; import com.example.cognito.srp.utils.SRPUtils; @@ -54,14 +44,15 @@ public RespondToAuthChallengeResponse userSrpAuth(String username, String passwo a, A, B, salt, Base64.getDecoder().decode(secretBlock)); - RespondToAuthChallengeResponse challengeResponse = respondToAuthChallengeResponse(userId, secretBlock, timestamp, + RespondToAuthChallengeResponse challengeResponse = respondToAuthChallengeResponse(userId, secretBlock, + timestamp, Base64.getEncoder().encodeToString(passwordClaimSignature), deviceKey); System.out.println("RespondToAuthChallenge response: " + challengeResponse); return challengeResponse; } public InitiateAuthResponse initiateAuth(String username, String A) { - Map authParameters = new HashMap<>(); + Map authParameters = new HashMap<>(); authParameters.put("USERNAME", username); authParameters.put("SRP_A", A); @@ -74,7 +65,7 @@ public InitiateAuthResponse initiateAuth(String username, String A) { try { InitiateAuthResponse response = this.cognitoClient.initiateAuth(authRequest); return response; - } catch(CognitoIdentityProviderException e) { + } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } @@ -82,8 +73,9 @@ public InitiateAuthResponse initiateAuth(String username, String A) { return null; } - public RespondToAuthChallengeResponse respondToAuthChallengeResponse(String userId, String secretBlock, String timestamp, - String passwordClaimSignature, String deviceKey) { + public RespondToAuthChallengeResponse respondToAuthChallengeResponse(String userId, String secretBlock, + String timestamp, + String passwordClaimSignature, String deviceKey) { Map challengeResponses = new HashMap<>(); challengeResponses.put("USERNAME", userId); challengeResponses.put("PASSWORD_CLAIM_SECRET_BLOCK", secretBlock); @@ -91,7 +83,6 @@ public RespondToAuthChallengeResponse respondToAuthChallengeResponse(String user challengeResponses.put("TIMESTAMP", timestamp); challengeResponses.put("DEVICE_KEY", deviceKey); - RespondToAuthChallengeRequest challengeRequest = RespondToAuthChallengeRequest.builder() .clientId(clientId) .challengeName(ChallengeNameType.PASSWORD_VERIFIER) @@ -101,7 +92,7 @@ public RespondToAuthChallengeResponse respondToAuthChallengeResponse(String user try { RespondToAuthChallengeResponse response = this.cognitoClient.respondToAuthChallenge(challengeRequest); return response; - } catch(CognitoIdentityProviderException e) { + } catch (CognitoIdentityProviderException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/utils/HashUtils.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/utils/HashUtils.java index bdaf7cb0459..09dd4a0fefd 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/utils/HashUtils.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/utils/HashUtils.java @@ -1,16 +1,6 @@ -/* Copyright 2010-2023 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.cognito.srp.utils; import javax.crypto.Mac; @@ -25,8 +15,10 @@ public class HashUtils { private static final String HMAC_ALGORITHM = "HmacSHA256"; private static final String HASH_ALGORITHM = "SHA-256"; + public static String computeSecretHash(String clientId, String clientSecret, String username) { - byte[] output = hmac(clientSecret.getBytes(StandardCharsets.UTF_8), username.getBytes(StandardCharsets.UTF_8), clientId.getBytes(StandardCharsets.UTF_8)); + byte[] output = hmac(clientSecret.getBytes(StandardCharsets.UTF_8), username.getBytes(StandardCharsets.UTF_8), + clientId.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(output); } @@ -41,7 +33,7 @@ public static byte[] hmac(byte[] key, byte[]... inputs) { } catch (InvalidKeyException e) { throw new RuntimeException(e); } - for (byte[] input : inputs) { + for (byte[] input : inputs) { mac.update(input); } return mac.doFinal(); diff --git a/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/utils/SRPUtils.java b/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/utils/SRPUtils.java index f65b56c5539..bd8e39b0ac0 100644 --- a/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/utils/SRPUtils.java +++ b/javav2/example_code/cognito/src/main/java/com/example/cognito/srp/utils/SRPUtils.java @@ -1,16 +1,6 @@ -/* Copyright 2010-2023 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. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.cognito.srp.utils; import software.amazon.awssdk.utils.Pair; @@ -25,21 +15,21 @@ public class SRPUtils { private static final String RNG_ALGORIGHM = "SHA1PRNG"; private static final String HEX_N = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" - + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" - + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" - + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" - + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" - + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" - + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" - + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" - + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" - + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" - + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" - + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" - + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" - + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" - + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" - + "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF"; + + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" + + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" + + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" + + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" + + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" + + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" + + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" + + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" + + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" + + "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF"; public static final BigInteger N = new BigInteger(HEX_N, 16); public static final BigInteger g = BigInteger.valueOf(2); public static final BigInteger k; @@ -48,7 +38,8 @@ public class SRPUtils { private static final int DERIVED_KEY_SIZE = 16; private static final String DERIVED_KEY_INFO = "Caldera Derived Key"; private static final SecureRandom SECURE_RANDOM; - private static final SimpleDateFormat DATE_TIME_FORMATTER = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy", Locale.US); + private static final SimpleDateFormat DATE_TIME_FORMATTER = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy", + Locale.US); static { try { @@ -85,8 +76,8 @@ public static BigInteger generatePasswordVerifier(String name, String password, } public static byte[] calculatePasswordClaimSignature(String name, String password, String timestamp, - BigInteger a, BigInteger A, BigInteger B, BigInteger salt, - byte[] secretBlock) { + BigInteger a, BigInteger A, BigInteger B, BigInteger salt, + byte[] secretBlock) { BigInteger x = calculateX(name, password, salt); // u = H(A, B) BigInteger u = HashUtils.sha256(A, B); @@ -100,7 +91,7 @@ public static byte[] calculatePasswordClaimSignature(String name, String passwor private static byte[] hkdf(byte[] ikm, byte[] salt) { byte[] prk = HashUtils.hmac(salt, ikm); - byte[] end = {(byte)1}; + byte[] end = { (byte) 1 }; byte[] output = HashUtils.hmac(prk, DERIVED_KEY_INFO.getBytes(StandardCharsets.UTF_8), end); return Arrays.copyOfRange(output, 0, DERIVED_KEY_SIZE); } diff --git a/javav2/example_code/cognito/src/test/java/AmazonCognitoTest.java b/javav2/example_code/cognito/src/test/java/AmazonCognitoTest.java index 01bb30c9ea9..eada795e077 100644 --- a/javav2/example_code/cognito/src/test/java/AmazonCognitoTest.java +++ b/javav2/example_code/cognito/src/test/java/AmazonCognitoTest.java @@ -1,7 +1,6 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + import com.example.cognito.*; import com.google.gson.Gson; import org.junit.jupiter.api.*; @@ -24,65 +23,66 @@ @Tag("integ") public class AmazonCognitoTest { private static CognitoIdentityProviderClient cognitoclient; - private static CognitoIdentityProviderClient cognitoIdentityProviderClient ; - private static CognitoIdentityClient cognitoIdclient ; - private static String userPoolName=""; - private static String identityId=""; - private static String userPoolId="" ; - private static String identityPoolId =""; - private static String username=""; - private static String email=""; - private static String clientName=""; - private static String identityPoolName=""; - private static String appId=""; - private static String existingUserPoolId=""; + private static CognitoIdentityProviderClient cognitoIdentityProviderClient; + private static CognitoIdentityClient cognitoIdclient; + private static String userPoolName = ""; + private static String identityId = ""; + private static String userPoolId = ""; + private static String identityPoolId = ""; + private static String username = ""; + private static String email = ""; + private static String clientName = ""; + private static String identityPoolName = ""; + private static String appId = ""; + private static String existingUserPoolId = ""; private static String existingIdentityPoolId = ""; - private static String providerName=""; - private static String existingPoolName=""; - private static String clientId=""; - private static String secretkey=""; - private static String password=""; - private static String poolIdMVP=""; - private static String clientIdMVP=""; - private static String userNameMVP=""; - private static String passwordMVP=""; - private static String emailMVP=""; - private static String confirmationCode=""; - private static String authFlow=""; + private static String providerName = ""; + private static String existingPoolName = ""; + private static String clientId = ""; + private static String secretkey = ""; + private static String password = ""; + private static String poolIdMVP = ""; + private static String clientIdMVP = ""; + private static String userNameMVP = ""; + private static String passwordMVP = ""; + private static String emailMVP = ""; + private static String confirmationCode = ""; + private static String authFlow = ""; + @BeforeAll public static void setUp() throws IOException { // Run tests on Real AWS Resources cognitoclient = CognitoIdentityProviderClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); - cognitoIdclient = CognitoIdentityClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + cognitoIdclient = CognitoIdentityClient.builder() + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); - cognitoIdentityProviderClient = CognitoIdentityProviderClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + cognitoIdentityProviderClient = CognitoIdentityProviderClient.builder() + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); Gson gson = new Gson(); String json = getSecretValues(); SecretValues values = gson.fromJson(json, SecretValues.class); userPoolName = values.getUserPoolName(); - username= values.getUsername()+"_"+ java.util.UUID.randomUUID(); - email= values.getEmail(); + username = values.getUsername() + "_" + java.util.UUID.randomUUID(); + email = values.getEmail(); clientName = values.getClientName(); - identityPoolName = values.getIdentityPoolName(); + identityPoolName = values.getIdentityPoolName(); identityId = values.getIdentityId(); appId = values.getAppId(); existingUserPoolId = values.getExistingUserPoolId(); existingIdentityPoolId = values.getExistingIdentityPoolId(); providerName = values.getProviderName(); - existingPoolName = values.getExistingPoolName(); - clientId = values.getClientId(); - secretkey = values.getSecretkey(); + existingPoolName = values.getExistingPoolName(); + clientId = values.getClientId(); + secretkey = values.getSecretkey(); password = values.getPassword(); poolIdMVP = values.getPoolIdMVP(); clientIdMVP = values.getClientIdMVP(); @@ -90,45 +90,49 @@ public static void setUp() throws IOException { passwordMVP = values.getPasswordMVP(); emailMVP = values.getEmailMVP(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - try (InputStream input = AmazonCognitoTest.class.getClassLoader().getResourceAsStream("config.properties")) { - - Properties prop = new Properties(); - - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - //load a properties file from class path, inside static method - prop.load(input); - - // Populate the data members required for all tests - userPoolName = prop.getProperty("userPoolName"); - username= prop.getProperty("username")+"_"+ java.util.UUID.randomUUID(); - email= prop.getProperty("email"); - clientName = prop.getProperty("clientName"); - identityPoolName = prop.getProperty("identityPoolName"); - identityId = prop.getProperty("identityId"); // used in the GetIdentityCredentials test - appId = prop.getProperty("appId"); - existingUserPoolId = prop.getProperty("existingUserPoolId"); - existingIdentityPoolId = prop.getProperty("existingIdentityPoolId"); - providerName = prop.getProperty("providerName"); - existingPoolName = prop.getProperty("existingPoolName"); - clientId = prop.getProperty("clientId"); - secretkey = prop.getProperty("secretkey"); - password = prop.getProperty("password"); - poolIdMVP = prop.getProperty("poolIdMVP"); - clientIdMVP = prop.getProperty("clientIdMVP"); - userNameMVP = prop.getProperty("userNameMVP"); - passwordMVP = prop.getProperty("passwordMVP"); - emailMVP = prop.getProperty("emailMVP"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * try (InputStream input = + * AmazonCognitoTest.class.getClassLoader().getResourceAsStream( + * "config.properties")) { + * + * Properties prop = new Properties(); + * + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * //load a properties file from class path, inside static method + * prop.load(input); + * + * // Populate the data members required for all tests + * userPoolName = prop.getProperty("userPoolName"); + * username= prop.getProperty("username")+"_"+ java.util.UUID.randomUUID(); + * email= prop.getProperty("email"); + * clientName = prop.getProperty("clientName"); + * identityPoolName = prop.getProperty("identityPoolName"); + * identityId = prop.getProperty("identityId"); // used in the + * GetIdentityCredentials test + * appId = prop.getProperty("appId"); + * existingUserPoolId = prop.getProperty("existingUserPoolId"); + * existingIdentityPoolId = prop.getProperty("existingIdentityPoolId"); + * providerName = prop.getProperty("providerName"); + * existingPoolName = prop.getProperty("existingPoolName"); + * clientId = prop.getProperty("clientId"); + * secretkey = prop.getProperty("secretkey"); + * password = prop.getProperty("password"); + * poolIdMVP = prop.getProperty("poolIdMVP"); + * clientIdMVP = prop.getProperty("clientIdMVP"); + * userNameMVP = prop.getProperty("userNameMVP"); + * passwordMVP = prop.getProperty("passwordMVP"); + * emailMVP = prop.getProperty("emailMVP"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @@ -144,7 +148,7 @@ public void CreateUserPool() { @Tag("IntegrationTest") @Order(2) public void CreateUser() { - assertDoesNotThrow(() -> CreateUser.createNewUser(cognitoclient,userPoolId ,username, email, password)); + assertDoesNotThrow(() -> CreateUser.createNewUser(cognitoclient, userPoolId, username, email, password)); System.out.println("Test 2 passed"); } @@ -152,7 +156,7 @@ public void CreateUser() { @Tag("IntegrationTest") @Order(3) public void CreateUserPoolClient() { - assertDoesNotThrow(() ->CreateUserPoolClient.createPoolClient(cognitoclient,clientName, userPoolId)); + assertDoesNotThrow(() -> CreateUserPoolClient.createPoolClient(cognitoclient, clientName, userPoolId)); System.out.println("Test 3 passed"); } @@ -185,23 +189,24 @@ public void ListIdentityPools() { @Tag("IntegrationTest") @Order(7) public void ListUserPoolClients() { - assertDoesNotThrow(() ->ListUserPoolClients.listAllUserPoolClients(cognitoIdentityProviderClient, existingUserPoolId)); - System.out.println("Test 7 passed"); + assertDoesNotThrow( + () -> ListUserPoolClients.listAllUserPoolClients(cognitoIdentityProviderClient, existingUserPoolId)); + System.out.println("Test 7 passed"); } @Test @Tag("IntegrationTest") @Order(8) public void ListUsers() { - assertDoesNotThrow(() ->ListUsers.listAllUsers(cognitoclient, existingUserPoolId)); - System.out.println("Test 8 passed"); + assertDoesNotThrow(() -> ListUsers.listAllUsers(cognitoclient, existingUserPoolId)); + System.out.println("Test 8 passed"); } @Test @Tag("IntegrationTest") @Order(9) public void ListIdentities() { - assertDoesNotThrow(() -> ListIdentities.listPoolIdentities(cognitoIdclient, existingIdentityPoolId)); + assertDoesNotThrow(() -> ListIdentities.listPoolIdentities(cognitoIdclient, existingIdentityPoolId)); System.out.println("Test 9 passed"); } @@ -209,8 +214,9 @@ public void ListIdentities() { @Tag("IntegrationTest") @Order(10) public void AddLoginProvider() { - assertDoesNotThrow(() ->AddLoginProvider.setLoginProvider(cognitoIdclient, appId, existingPoolName, existingIdentityPoolId, providerName)); - System.out.println("Test 10 passed"); + assertDoesNotThrow(() -> AddLoginProvider.setLoginProvider(cognitoIdclient, appId, existingPoolName, + existingIdentityPoolId, providerName)); + System.out.println("Test 10 passed"); } @Test @@ -233,36 +239,37 @@ public void GetId() { @Tag("IntegrationTest") @Order(13) public void DeleteUserPool() { - assertDoesNotThrow(() ->DeleteUserPool.deletePool(cognitoclient, userPoolId)); + assertDoesNotThrow(() -> DeleteUserPool.deletePool(cognitoclient, userPoolId)); System.out.println("Test 13 passed"); } @Test @Tag("IntegrationTest") @Order(14) - public void SignUp() { - assertDoesNotThrow(() ->SignUpUser.signUp(cognitoIdentityProviderClient, clientId, secretkey, username, password, email)); + public void SignUp() { + assertDoesNotThrow( + () -> SignUpUser.signUp(cognitoIdentityProviderClient, clientId, secretkey, username, password, email)); System.out.println("Test 14 passed"); - } + } @Test @Tag("IntegrationTest") @Order(15) public void DeleteIdentityPool() { - assertDoesNotThrow(() ->DeleteIdentityPool.deleteIdPool(cognitoIdclient, identityPoolId)); + assertDoesNotThrow(() -> DeleteIdentityPool.deleteIdPool(cognitoIdclient, identityPoolId)); System.out.println("Test 15 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/cognito"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); diff --git a/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DetectEntities.java b/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DetectEntities.java index dbd36e770d3..175cd6d31b9 100644 --- a/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DetectEntities.java +++ b/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DetectEntities.java @@ -1,16 +1,10 @@ -// snippet-sourcedescription:[DetectEntities demonstrates how to retrieve named entities.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Comprehend] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.comprehend; -//snippet-start:[comprehend.java2.detect_entities.main] -//snippet-start:[comprehend.java2.detect_entities.import] +// snippet-start:[comprehend.java2.detect_entities.main] +// snippet-start:[comprehend.java2.detect_entities.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.comprehend.ComprehendClient; import software.amazon.awssdk.services.comprehend.model.DetectEntitiesRequest; @@ -18,9 +12,11 @@ import software.amazon.awssdk.services.comprehend.model.Entity; import software.amazon.awssdk.services.comprehend.model.ComprehendException; import java.util.List; -//snippet-end:[comprehend.java2.detect_entities.import] + +// snippet-end:[comprehend.java2.detect_entities.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,8 +27,8 @@ public static void main(String[] args) { String text = "Amazon.com, Inc. is located in Seattle, WA and was founded July 5th, 1994 by Jeff Bezos, allowing customers to buy everything from books to blenders. Seattle is north of Portland and south of Vancouver, BC. Other notable Seattle - based companies are Starbucks and Boeing."; Region region = Region.US_EAST_1; ComprehendClient comClient = ComprehendClient.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.println("Calling DetectEntities"); detectAllEntities(comClient, text); @@ -42,9 +38,9 @@ public static void main(String[] args) { public static void detectAllEntities(ComprehendClient comClient, String text) { try { DetectEntitiesRequest detectEntitiesRequest = DetectEntitiesRequest.builder() - .text(text) - .languageCode("en") - .build(); + .text(text) + .languageCode("en") + .build(); DetectEntitiesResponse detectEntitiesResult = comClient.detectEntities(detectEntitiesRequest); List entList = detectEntitiesResult.entities(); @@ -58,5 +54,4 @@ public static void detectAllEntities(ComprehendClient comClient, String text) { } } } -//snippet-end:[comprehend.java2.detect_entities.main] - +// snippet-end:[comprehend.java2.detect_entities.main] diff --git a/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DetectKeyPhrases.java b/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DetectKeyPhrases.java index 15a6842c9eb..9e46ecc5d9c 100644 --- a/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DetectKeyPhrases.java +++ b/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DetectKeyPhrases.java @@ -1,16 +1,10 @@ -// snippet-sourcedescription:[DetectKeyPhrases demonstrates how to detect key phrases.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Comprehend] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.comprehend; -//snippet-start:[comprehend.java2.detect_keyphrases.main] -//snippet-start:[comprehend.java2.detect_keyphrases.import] +// snippet-start:[comprehend.java2.detect_keyphrases.main] +// snippet-start:[comprehend.java2.detect_keyphrases.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.comprehend.ComprehendClient; import software.amazon.awssdk.services.comprehend.model.DetectKeyPhrasesRequest; @@ -18,9 +12,11 @@ import software.amazon.awssdk.services.comprehend.model.KeyPhrase; import software.amazon.awssdk.services.comprehend.model.ComprehendException; import java.util.List; -//snippet-end:[comprehend.java2.detect_keyphrases.import] + +// snippet-end:[comprehend.java2.detect_keyphrases.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,8 +27,8 @@ public static void main(String[] args) { String text = "Amazon.com, Inc. is located in Seattle, WA and was founded July 5th, 1994 by Jeff Bezos, allowing customers to buy everything from books to blenders. Seattle is north of Portland and south of Vancouver, BC. Other notable Seattle - based companies are Starbucks and Boeing."; Region region = Region.US_EAST_1; ComprehendClient comClient = ComprehendClient.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.println("Calling DetectKeyPhrases"); detectAllKeyPhrases(comClient, text); @@ -42,9 +38,9 @@ public static void main(String[] args) { public static void detectAllKeyPhrases(ComprehendClient comClient, String text) { try { DetectKeyPhrasesRequest detectKeyPhrasesRequest = DetectKeyPhrasesRequest.builder() - .text(text) - .languageCode("en") - .build(); + .text(text) + .languageCode("en") + .build(); DetectKeyPhrasesResponse detectKeyPhrasesResult = comClient.detectKeyPhrases(detectKeyPhrasesRequest); List phraseList = detectKeyPhrasesResult.keyPhrases(); @@ -58,5 +54,4 @@ public static void detectAllKeyPhrases(ComprehendClient comClient, String text) } } } -//snippet-end:[comprehend.java2.detect_keyphrases.main] - +// snippet-end:[comprehend.java2.detect_keyphrases.main] diff --git a/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DetectLanguage.java b/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DetectLanguage.java index 286392c8fef..2036ce36acd 100644 --- a/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DetectLanguage.java +++ b/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DetectLanguage.java @@ -1,16 +1,10 @@ -// snippet-sourcedescription:[DetectLanguage demonstrates how to detect the language of the text.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Comprehend] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.comprehend; -//snippet-start:[comprehend.java2.detect_language.main] -//snippet-start:[comprehend.java2.detect_language.import] +// snippet-start:[comprehend.java2.detect_language.main] +// snippet-start:[comprehend.java2.detect_language.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.comprehend.ComprehendClient; import software.amazon.awssdk.services.comprehend.model.ComprehendException; @@ -18,10 +12,11 @@ import software.amazon.awssdk.services.comprehend.model.DetectDominantLanguageResponse; import software.amazon.awssdk.services.comprehend.model.DominantLanguage; import java.util.List; -//snippet-end:[comprehend.java2.detect_language.import] +// snippet-end:[comprehend.java2.detect_language.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -34,8 +29,8 @@ public static void main(String[] args) { Region region = Region.US_EAST_1; ComprehendClient comClient = ComprehendClient.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.println("Calling DetectDominantLanguage"); detectTheDominantLanguage(comClient, text); @@ -45,8 +40,8 @@ public static void main(String[] args) { public static void detectTheDominantLanguage(ComprehendClient comClient, String text) { try { DetectDominantLanguageRequest request = DetectDominantLanguageRequest.builder() - .text(text) - .build(); + .text(text) + .build(); DetectDominantLanguageResponse resp = comClient.detectDominantLanguage(request); List allLanList = resp.languages(); @@ -60,5 +55,4 @@ public static void detectTheDominantLanguage(ComprehendClient comClient, String } } } -//snippet-end:[comprehend.java2.detect_language.main] - +// snippet-end:[comprehend.java2.detect_language.main] diff --git a/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DetectSentiment.java b/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DetectSentiment.java index 980f35e2c9a..28ff152e4bc 100644 --- a/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DetectSentiment.java +++ b/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DetectSentiment.java @@ -1,24 +1,20 @@ -// snippet-sourcedescription:[DetectSentiment demonstrates how to detect sentiments in the text.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Comprehend] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.comprehend; -//snippet-start:[comprehend.java2.detect_sentiment.main] -//snippet-start:[comprehend.java2.detect_sentiment.import] +// snippet-start:[comprehend.java2.detect_sentiment.main] +// snippet-start:[comprehend.java2.detect_sentiment.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.comprehend.ComprehendClient; import software.amazon.awssdk.services.comprehend.model.ComprehendException; import software.amazon.awssdk.services.comprehend.model.DetectSentimentRequest; import software.amazon.awssdk.services.comprehend.model.DetectSentimentResponse; -//snippet-end:[comprehend.java2.detect_sentiment.import] +// snippet-end:[comprehend.java2.detect_sentiment.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,8 +25,8 @@ public static void main(String[] args) { String text = "Amazon.com, Inc. is located in Seattle, WA and was founded July 5th, 1994 by Jeff Bezos, allowing customers to buy everything from books to blenders. Seattle is north of Portland and south of Vancouver, BC. Other notable Seattle - based companies are Starbucks and Boeing."; Region region = Region.US_EAST_1; ComprehendClient comClient = ComprehendClient.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.println("Calling DetectSentiment"); detectSentiments(comClient, text); @@ -40,9 +36,9 @@ public static void main(String[] args) { public static void detectSentiments(ComprehendClient comClient, String text) { try { DetectSentimentRequest detectSentimentRequest = DetectSentimentRequest.builder() - .text(text) - .languageCode("en") - .build(); + .text(text) + .languageCode("en") + .build(); DetectSentimentResponse detectSentimentResult = comClient.detectSentiment(detectSentimentRequest); System.out.println("The Neutral value is " + detectSentimentResult.sentimentScore().neutral()); @@ -53,4 +49,4 @@ public static void detectSentiments(ComprehendClient comClient, String text) { } } } -//snippet-end:[comprehend.java2.detect_sentiment.main] \ No newline at end of file +// snippet-end:[comprehend.java2.detect_sentiment.main] \ No newline at end of file diff --git a/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DetectSyntax.java b/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DetectSyntax.java index ae55ba8ca71..df585bee48f 100644 --- a/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DetectSyntax.java +++ b/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DetectSyntax.java @@ -1,15 +1,10 @@ -// snippet-sourcedescription:[DetectSyntax demonstrates how to detect syntax in the text.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Comprehend] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.comprehend; -//snippet-start:[comprehend.java2.detect_syntax.main] -//snippet-start:[comprehend.java2.detect_syntax.import] +// snippet-start:[comprehend.java2.detect_syntax.main] +// snippet-start:[comprehend.java2.detect_syntax.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.comprehend.ComprehendClient; import software.amazon.awssdk.services.comprehend.model.ComprehendException; @@ -17,10 +12,11 @@ import software.amazon.awssdk.services.comprehend.model.DetectSyntaxResponse; import software.amazon.awssdk.services.comprehend.model.SyntaxToken; import java.util.List; -//snippet-end:[comprehend.java2.detect_syntax.import] +// snippet-end:[comprehend.java2.detect_syntax.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,8 +27,8 @@ public static void main(String[] args) { String text = "Amazon.com, Inc. is located in Seattle, WA and was founded July 5th, 1994 by Jeff Bezos, allowing customers to buy everything from books to blenders. Seattle is north of Portland and south of Vancouver, BC. Other notable Seattle - based companies are Starbucks and Boeing."; Region region = Region.US_EAST_1; ComprehendClient comClient = ComprehendClient.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.println("Calling DetectSyntax"); detectAllSyntax(comClient, text); @@ -42,9 +38,9 @@ public static void main(String[] args) { public static void detectAllSyntax(ComprehendClient comClient, String text) { try { DetectSyntaxRequest detectSyntaxRequest = DetectSyntaxRequest.builder() - .text(text) - .languageCode("en") - .build(); + .text(text) + .languageCode("en") + .build(); DetectSyntaxResponse detectSyntaxResult = comClient.detectSyntax(detectSyntaxRequest); List syntaxTokens = detectSyntaxResult.syntaxTokens(); @@ -59,4 +55,4 @@ public static void detectAllSyntax(ComprehendClient comClient, String text) { } } } -//snippet-end:[comprehend.java2.detect_syntax.main] +// snippet-end:[comprehend.java2.detect_syntax.main] diff --git a/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DocumentClassifierDemo.java b/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DocumentClassifierDemo.java index 73e2ff0ba4c..7af8a4a6703 100644 --- a/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DocumentClassifierDemo.java +++ b/javav2/example_code/comprehend/src/main/java/com/example/comprehend/DocumentClassifierDemo.java @@ -1,26 +1,22 @@ -// snippet-sourcedescription:[DocumentClassifierDemo demonstrates how to train a custom classifier.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Comprehend] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.comprehend; -//snippet-start:[comprehend.java2.classifier.main] -//snippet-start:[comprehend.java2.classifier.import] +// snippet-start:[comprehend.java2.classifier.main] +// snippet-start:[comprehend.java2.classifier.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.comprehend.ComprehendClient; import software.amazon.awssdk.services.comprehend.model.ComprehendException; import software.amazon.awssdk.services.comprehend.model.CreateDocumentClassifierRequest; import software.amazon.awssdk.services.comprehend.model.CreateDocumentClassifierResponse; import software.amazon.awssdk.services.comprehend.model.DocumentClassifierInputDataConfig; -//snippet-end:[comprehend.java2.classifier.import] +// snippet-end:[comprehend.java2.classifier.import] /** - * Before running this code example, you can setup the necessary resources, such as the CSV file and IAM Roles, by following this document: - * https://aws.amazon.com/blogs/machine-learning/building-a-custom-classifier-using-amazon-comprehend/ + * Before running this code example, you can setup the necessary resources, such + * as the CSV file and IAM Roles, by following this document: + * https://aws.amazon.com/blogs/machine-learning/building-a-custom-classifier-using-amazon-comprehend/ * * Also, set up your development environment, including your credentials. * @@ -32,13 +28,13 @@ public class DocumentClassifierDemo { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - dataAccessRoleArn - The ARN value of the role used for this operation. - s3Uri - The Amazon S3 bucket that contains the CSV file. - documentClassifierName - The name of the document classifier. - """; + Where: + dataAccessRoleArn - The ARN value of the role used for this operation. + s3Uri - The Amazon S3 bucket that contains the CSV file. + documentClassifierName - The name of the document classifier. + """; if (args.length != 3) { System.out.println(usage); @@ -51,27 +47,29 @@ public static void main(String[] args) { Region region = Region.US_EAST_1; ComprehendClient comClient = ComprehendClient.builder() - .region(region) - .build(); + .region(region) + .build(); createDocumentClassifier(comClient, dataAccessRoleArn, s3Uri, documentClassifierName); comClient.close(); } - public static void createDocumentClassifier(ComprehendClient comClient, String dataAccessRoleArn, String s3Uri, String documentClassifierName) { + public static void createDocumentClassifier(ComprehendClient comClient, String dataAccessRoleArn, String s3Uri, + String documentClassifierName) { try { DocumentClassifierInputDataConfig config = DocumentClassifierInputDataConfig.builder() - .s3Uri(s3Uri) - .build(); + .s3Uri(s3Uri) + .build(); CreateDocumentClassifierRequest createDocumentClassifierRequest = CreateDocumentClassifierRequest.builder() - .documentClassifierName(documentClassifierName) - .dataAccessRoleArn(dataAccessRoleArn) - .languageCode("en") - .inputDataConfig(config) - .build(); + .documentClassifierName(documentClassifierName) + .dataAccessRoleArn(dataAccessRoleArn) + .languageCode("en") + .inputDataConfig(config) + .build(); - CreateDocumentClassifierResponse createDocumentClassifierResult = comClient.createDocumentClassifier(createDocumentClassifierRequest); + CreateDocumentClassifierResponse createDocumentClassifierResult = comClient + .createDocumentClassifier(createDocumentClassifierRequest); String documentClassifierArn = createDocumentClassifierResult.documentClassifierArn(); System.out.println("Document Classifier ARN: " + documentClassifierArn); @@ -81,4 +79,4 @@ public static void createDocumentClassifier(ComprehendClient comClient, String d } } } -//snippet-end:[comprehend.java2.classifier.main] \ No newline at end of file +// snippet-end:[comprehend.java2.classifier.main] \ No newline at end of file diff --git a/javav2/example_code/comprehend/src/main/java/com/example/comprehend/medical/DetectMedicalEntities.java b/javav2/example_code/comprehend/src/main/java/com/example/comprehend/medical/DetectMedicalEntities.java index 7429cb78028..38d1cd289c1 100644 --- a/javav2/example_code/comprehend/src/main/java/com/example/comprehend/medical/DetectMedicalEntities.java +++ b/javav2/example_code/comprehend/src/main/java/com/example/comprehend/medical/DetectMedicalEntities.java @@ -1,20 +1,10 @@ -// snippet-sourcedescription:[DetectEntities demonstrates how to retrieve named entities.] -//snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Comprehend Medical] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[09/28/2021] -// snippet-sourceauthor:[scmacdon - AWS] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.comprehend.medical; -//snippet-start:[comprehendmed.java2.detect_entities.main] -//snippet-start:[comprehendmed.java2.detect_entities.import] +// snippet-start:[comprehendmed.java2.detect_entities.main] +// snippet-start:[comprehendmed.java2.detect_entities.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.comprehendmedical.ComprehendMedicalClient; import software.amazon.awssdk.services.comprehendmedical.model.DetectEntitiesRequest; @@ -23,9 +13,11 @@ import software.amazon.awssdk.services.comprehendmedical.model.ComprehendMedicalException; import java.util.Iterator; import java.util.List; -//snippet-end:[comprehendmed.java2.detect_entities.import] + +// snippet-end:[comprehendmed.java2.detect_entities.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -36,21 +28,22 @@ public class DetectMedicalEntities { public static void main(String[] args) { String text = "Pt is 87 yo woman, highschool teacher with past medical history that includes\n" + - " - status post cardiac catheterization in April 2019.\n" + - "She presents today with palpitations and chest pressure.\n" + - "HPI : Sleeping trouble on present dosage of Clonidine. Severe Rash on face and leg, slightly itchy \n" + - "Meds : Vyvanse 50 mgs po at breakfast daily, \n" + - " Clonidine 0.2 mgs -- 1 and 1 / 2 tabs po qhs \n" + - "HEENT : Boggy inferior turbinates, No oropharyngeal lesion \n" + - "Lungs : clear \n" + - "Heart : Regular rhythm \n" + - "Skin : Mild erythematous eruption to hairline \n" + - "\n" + - "Follow-up as scheduled"; + " - status post cardiac catheterization in April 2019.\n" + + "She presents today with palpitations and chest pressure.\n" + + "HPI : Sleeping trouble on present dosage of Clonidine. Severe Rash on face and leg, slightly itchy \n" + + + "Meds : Vyvanse 50 mgs po at breakfast daily, \n" + + " Clonidine 0.2 mgs -- 1 and 1 / 2 tabs po qhs \n" + + "HEENT : Boggy inferior turbinates, No oropharyngeal lesion \n" + + "Lungs : clear \n" + + "Heart : Regular rhythm \n" + + "Skin : Mild erythematous eruption to hairline \n" + + "\n" + + "Follow-up as scheduled"; Region region = Region.US_EAST_1; ComprehendMedicalClient medClient = ComprehendMedicalClient.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.println("Calling Detect Medical Entities"); detectAllEntities(medClient, text); @@ -62,8 +55,8 @@ public static void detectAllEntities(ComprehendMedicalClient medClient, String t try { DetectEntitiesRequest detectEntitiesRequest = DetectEntitiesRequest.builder() - .text(text) - .build(); + .text(text) + .build(); DetectEntitiesResponse detectEntitiesResult = medClient.detectEntities(detectEntitiesRequest); List entList = detectEntitiesResult.entities(); @@ -80,5 +73,4 @@ public static void detectAllEntities(ComprehendMedicalClient medClient, String t } } } -//snippet-end:[comprehendmed.java2.detect_entities.main] - +// snippet-end:[comprehendmed.java2.detect_entities.main] diff --git a/javav2/example_code/comprehend/src/main/java/com/example/comprehend/medical/DetectPHI.java b/javav2/example_code/comprehend/src/main/java/com/example/comprehend/medical/DetectPHI.java index 7f32ead10fb..28ebdcb542d 100644 --- a/javav2/example_code/comprehend/src/main/java/com/example/comprehend/medical/DetectPHI.java +++ b/javav2/example_code/comprehend/src/main/java/com/example/comprehend/medical/DetectPHI.java @@ -1,20 +1,10 @@ -// snippet-sourcedescription:[DetectPHI demonstrates how to retrieve protected health information (PHI).] -//snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Comprehend Medical] -// snippet-keyword:[Code Sample] -// snippet-sourcetype:[full-example] -// snippet-sourcedate:[09/28/2021] -// snippet-sourceauthor:[scmacdon - AWS] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.comprehend.medical; -//snippet-start:[comprehendmed.java2.detect_phi.main] -//snippet-start:[comprehendmed.java2.detect_phi.import] +// snippet-start:[comprehendmed.java2.detect_phi.main] +// snippet-start:[comprehendmed.java2.detect_phi.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.comprehendmedical.ComprehendMedicalClient; import software.amazon.awssdk.services.comprehendmedical.model.ComprehendMedicalException; @@ -23,9 +13,11 @@ import software.amazon.awssdk.services.comprehendmedical.model.Entity; import java.util.Iterator; import java.util.List; -//snippet-end:[comprehendmed.java2.detect_phi.import] + +// snippet-end:[comprehendmed.java2.detect_phi.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -35,21 +27,22 @@ public class DetectPHI { public static void main(String[] args) { String text = "Pt is 87 yo woman, highschool teacher with past medical history that includes\n" + - " - status post cardiac catheterization in April 2019.\n" + - "She presents today with palpitations and chest pressure.\n" + - "HPI : Sleeping trouble on present dosage of Clonidine. Severe Rash on face and leg, slightly itchy \n" + - "Meds : Vyvanse 50 mgs po at breakfast daily, \n" + - " Clonidine 0.2 mgs -- 1 and 1 / 2 tabs po qhs \n" + - "HEENT : Boggy inferior turbinates, No oropharyngeal lesion \n" + - "Lungs : clear \n" + - "Heart : Regular rhythm \n" + - "Skin : Mild erythematous eruption to hairline \n" + - "\n" + - "Follow-up as scheduled"; + " - status post cardiac catheterization in April 2019.\n" + + "She presents today with palpitations and chest pressure.\n" + + "HPI : Sleeping trouble on present dosage of Clonidine. Severe Rash on face and leg, slightly itchy \n" + + + "Meds : Vyvanse 50 mgs po at breakfast daily, \n" + + " Clonidine 0.2 mgs -- 1 and 1 / 2 tabs po qhs \n" + + "HEENT : Boggy inferior turbinates, No oropharyngeal lesion \n" + + "Lungs : clear \n" + + "Heart : Regular rhythm \n" + + "Skin : Mild erythematous eruption to hairline \n" + + "\n" + + "Follow-up as scheduled"; Region region = Region.US_EAST_1; ComprehendMedicalClient medClient = ComprehendMedicalClient.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.println("Calling Detect Medical Entities"); detectPHIValues(medClient, text); @@ -60,8 +53,8 @@ public static void detectPHIValues(ComprehendMedicalClient medClient, String tex try { DetectPhiRequest detectRequest = DetectPhiRequest.builder() - .text(text) - .build(); + .text(text) + .build(); DetectPhiResponse detectResult = medClient.detectPHI(detectRequest); List entList = detectResult.entities(); @@ -78,4 +71,4 @@ public static void detectPHIValues(ComprehendMedicalClient medClient, String tex } } } -//snippet-end:[comprehendmed.java2.detect_phi.main] +// snippet-end:[comprehendmed.java2.detect_phi.main] diff --git a/javav2/example_code/comprehend/src/test/java/AmazonComprehendTest.java b/javav2/example_code/comprehend/src/test/java/AmazonComprehendTest.java index 9930654a7e6..9b52539c1c2 100644 --- a/javav2/example_code/comprehend/src/test/java/AmazonComprehendTest.java +++ b/javav2/example_code/comprehend/src/test/java/AmazonComprehendTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.comprehend.*; import com.google.gson.Gson; @@ -23,9 +21,9 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AmazonComprehendTest { - private static ComprehendClient comClient; - private static String text = "Amazon.com, Inc. is located in Seattle, WA and was founded July 5th, 1994 by Jeff Bezos, allowing customers to buy everything from books to blenders. Seattle is north of Portland and south of Vancouver, BC. Other notable Seattle - based companies are Starbucks and Boeing" ; - private static String frText = "Il pleut aujourd'hui à Seattle" ; + private static ComprehendClient comClient; + private static String text = "Amazon.com, Inc. is located in Seattle, WA and was founded July 5th, 1994 by Jeff Bezos, allowing customers to buy everything from books to blenders. Seattle is north of Portland and south of Vancouver, BC. Other notable Seattle - based companies are Starbucks and Boeing"; + private static String frText = "Il pleut aujourd'hui à Seattle"; private static String dataAccessRoleArn; private static String s3Uri; private static String documentClassifierName; @@ -45,29 +43,32 @@ public static void setUp() throws IOException { s3Uri = values.getS3Uri(); documentClassifierName = values.getDocumentClassifier(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - try (InputStream input = AmazonComprehendTest.class.getClassLoader().getResourceAsStream("config.properties")) { - - Properties prop = new Properties(); - - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - //load a properties file from class path, inside static method - prop.load(input); - - // Populate the data members required for all tests - dataAccessRoleArn = prop.getProperty("dataAccessRoleArn"); - s3Uri = prop.getProperty("s3Uri"); - documentClassifierName = prop.getProperty("documentClassifier"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * try (InputStream input = + * AmazonComprehendTest.class.getClassLoader().getResourceAsStream( + * "config.properties")) { + * + * Properties prop = new Properties(); + * + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * //load a properties file from class path, inside static method + * prop.load(input); + * + * // Populate the data members required for all tests + * dataAccessRoleArn = prop.getProperty("dataAccessRoleArn"); + * s3Uri = prop.getProperty("s3Uri"); + * documentClassifierName = prop.getProperty("documentClassifier"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @@ -75,7 +76,7 @@ public static void setUp() throws IOException { @Tag("IntegrationTest") @Order(1) public void DetectEntities() { - assertDoesNotThrow(() ->DetectEntities.detectAllEntities(comClient, text)); + assertDoesNotThrow(() -> DetectEntities.detectAllEntities(comClient, text)); System.out.println("Test 1 passed"); } @@ -84,7 +85,7 @@ public void DetectEntities() { @Tag("IntegrationTest") @Order(2) public void DetectKeyPhrases() { - assertDoesNotThrow(() ->DetectKeyPhrases.detectAllKeyPhrases(comClient, text)); + assertDoesNotThrow(() -> DetectKeyPhrases.detectAllKeyPhrases(comClient, text)); System.out.println("Test 2 passed"); } @@ -93,7 +94,7 @@ public void DetectKeyPhrases() { @Tag("IntegrationTest") @Order(3) public void DetectLanguage() { - assertDoesNotThrow(() ->DetectLanguage.detectTheDominantLanguage(comClient, frText)); + assertDoesNotThrow(() -> DetectLanguage.detectTheDominantLanguage(comClient, frText)); System.out.println("Test 3 passed"); } @@ -102,7 +103,7 @@ public void DetectLanguage() { @Tag("IntegrationTest") @Order(4) public void DetectSentiment() { - assertDoesNotThrow(() ->DetectSentiment.detectSentiments(comClient, text)); + assertDoesNotThrow(() -> DetectSentiment.detectSentiments(comClient, text)); System.out.println("Test 4 passed"); } @@ -117,14 +118,14 @@ public void DetectSyntax() { private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/comprehend"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); diff --git a/javav2/example_code/connect/src/main/java/com/example/connect/CreateInstance.java b/javav2/example_code/connect/src/main/java/com/example/connect/CreateInstance.java index f9c665b0bc8..67720614d30 100644 --- a/javav2/example_code/connect/src/main/java/com/example/connect/CreateInstance.java +++ b/javav2/example_code/connect/src/main/java/com/example/connect/CreateInstance.java @@ -1,24 +1,19 @@ -//snippet-sourcedescription:[CreateInstance.java demonstrates how to create an Amazon Connect instance.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Connect] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.connect; // snippet-start:[connect.java2.create.main] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.connect.ConnectClient; -import software.amazon.awssdk.services.connect.model.CreateInstanceRequest ; +import software.amazon.awssdk.services.connect.model.CreateInstanceRequest; import software.amazon.awssdk.services.connect.model.CreateInstanceResponse; import software.amazon.awssdk.services.connect.model.DirectoryType; import software.amazon.awssdk.services.connect.model.ConnectException; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,11 +23,11 @@ public class CreateInstance { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - instanceAlias - The name for your instance. - """; + Where: + instanceAlias - The name for your instance. + """; if (args.length != 1) { System.out.println(usage); @@ -42,8 +37,8 @@ public static void main(String[] args) { String instanceAlias = args[0]; Region region = Region.US_WEST_2; ConnectClient connectClient = ConnectClient.builder() - .region(region) - .build(); + .region(region) + .build(); createConnectInstance(connectClient, instanceAlias); } @@ -51,11 +46,11 @@ public static void main(String[] args) { public static String createConnectInstance(ConnectClient connectClient, String instanceAlias) { try { CreateInstanceRequest instanceRequest = CreateInstanceRequest.builder() - .identityManagementType(DirectoryType.CONNECT_MANAGED) - .instanceAlias(instanceAlias) - .inboundCallsEnabled(true) - .outboundCallsEnabled(true) - .build(); + .identityManagementType(DirectoryType.CONNECT_MANAGED) + .instanceAlias(instanceAlias) + .inboundCallsEnabled(true) + .outboundCallsEnabled(true) + .build(); CreateInstanceResponse response = connectClient.createInstance(instanceRequest); System.out.println("The instance ARN is " + response.arn()); diff --git a/javav2/example_code/connect/src/main/java/com/example/connect/DeleteInstance.java b/javav2/example_code/connect/src/main/java/com/example/connect/DeleteInstance.java index c2369a7a3d9..2cae31ab993 100644 --- a/javav2/example_code/connect/src/main/java/com/example/connect/DeleteInstance.java +++ b/javav2/example_code/connect/src/main/java/com/example/connect/DeleteInstance.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DeleteInstance.java demonstrates how to delete an Amazon Connect instance.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Connect] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.connect; @@ -16,7 +10,8 @@ import software.amazon.awssdk.services.connect.model.DeleteInstanceRequest; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -26,12 +21,12 @@ public class DeleteInstance { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - instanceId - The id of the instance to delete. + Where: + instanceId - The id of the instance to delete. - """; + """; if (args.length != 1) { System.out.println(usage); @@ -41,8 +36,8 @@ public static void main(String[] args) { String instanceId = args[0]; Region region = Region.US_EAST_1; ConnectClient connectClient = ConnectClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteSpecificInstance(connectClient, instanceId); } @@ -50,8 +45,8 @@ public static void main(String[] args) { public static void deleteSpecificInstance(ConnectClient connectClient, String instanceId) { try { DeleteInstanceRequest instanceRequest = DeleteInstanceRequest.builder() - .instanceId(instanceId) - .build(); + .instanceId(instanceId) + .build(); connectClient.deleteInstance(instanceRequest); System.out.println("Instance was successfully deleted."); diff --git a/javav2/example_code/connect/src/main/java/com/example/connect/DescribeContact.java b/javav2/example_code/connect/src/main/java/com/example/connect/DescribeContact.java index 2e28cc6d1af..c0c518c1b4b 100644 --- a/javav2/example_code/connect/src/main/java/com/example/connect/DescribeContact.java +++ b/javav2/example_code/connect/src/main/java/com/example/connect/DescribeContact.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeContact.java demonstrates how to describe the specified contact.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Connect] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.connect; @@ -17,7 +11,8 @@ import software.amazon.awssdk.services.connect.model.DescribeContactResponse; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,13 +23,13 @@ public class DescribeContact { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - instanceId - The id of your instance. - contactId - The id of the contact to describe. + Where: + instanceId - The id of your instance. + contactId - The id of the contact to describe. - """; + """; if (args.length != 2) { System.out.println(usage); @@ -45,8 +40,8 @@ public static void main(String[] args) { String contactId = args[1]; Region region = Region.US_EAST_1; ConnectClient connectClient = ConnectClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeSpecificContact(connectClient, instanceId, contactId); } @@ -54,9 +49,9 @@ public static void main(String[] args) { public static void describeSpecificContact(ConnectClient connectClient, String instanceId, String contactId) { try { DescribeContactRequest contactRequest = DescribeContactRequest.builder() - .contactId(contactId) - .instanceId(instanceId) - .build(); + .contactId(contactId) + .instanceId(instanceId) + .build(); DescribeContactResponse response = connectClient.describeContact(contactRequest); System.out.println("The queue info is " + response.contact().queueInfo().toString()); diff --git a/javav2/example_code/connect/src/main/java/com/example/connect/DescribeInstance.java b/javav2/example_code/connect/src/main/java/com/example/connect/DescribeInstance.java index ea646a999ad..0d93bea250b 100644 --- a/javav2/example_code/connect/src/main/java/com/example/connect/DescribeInstance.java +++ b/javav2/example_code/connect/src/main/java/com/example/connect/DescribeInstance.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeInstance.java demonstrates how to describe the specified instance.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Connect] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.connect; @@ -17,7 +11,8 @@ import software.amazon.awssdk.services.connect.model.DescribeInstanceResponse; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,11 +22,11 @@ public class DescribeInstance { public static void main(String[] args) throws InterruptedException { final String usage = """ - Usage: + Usage: - Where: - instanceId - The id of the instance to describe. - """; + Where: + instanceId - The id of the instance to describe. + """; if (args.length != 1) { System.out.println(usage); @@ -41,18 +36,19 @@ public static void main(String[] args) throws InterruptedException { String instanceId = args[0]; Region region = Region.US_EAST_1; ConnectClient connectClient = ConnectClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeSpecificInstance(connectClient, instanceId); } - public static void describeSpecificInstance(ConnectClient connectClient, String instanceId) throws InterruptedException { + public static void describeSpecificInstance(ConnectClient connectClient, String instanceId) + throws InterruptedException { boolean status = false; try { DescribeInstanceRequest instanceRequest = DescribeInstanceRequest.builder() - .instanceId(instanceId) - .build(); + .instanceId(instanceId) + .build(); while (!status) { DescribeInstanceResponse response = connectClient.describeInstance(instanceRequest); diff --git a/javav2/example_code/connect/src/main/java/com/example/connect/DescribeInstanceAttribute.java b/javav2/example_code/connect/src/main/java/com/example/connect/DescribeInstanceAttribute.java index 8c00110fcd7..363c72b57d4 100644 --- a/javav2/example_code/connect/src/main/java/com/example/connect/DescribeInstanceAttribute.java +++ b/javav2/example_code/connect/src/main/java/com/example/connect/DescribeInstanceAttribute.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeInstanceAttribute.java demonstrates how to describe the specified instance attributes.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Connect] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.connect; @@ -18,7 +12,8 @@ import software.amazon.awssdk.services.connect.model.InstanceAttributeType; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +23,12 @@ public class DescribeInstanceAttribute { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - instanceId - The identifier of the Amazon Connect instance. + Where: + instanceId - The identifier of the Amazon Connect instance. - """; + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +38,8 @@ public static void main(String[] args) { String instanceId = args[0]; Region region = Region.US_EAST_1; ConnectClient connectClient = ConnectClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeAttribute(connectClient, instanceId); } @@ -52,9 +47,9 @@ public static void main(String[] args) { public static void describeAttribute(ConnectClient connectClient, String instanceId) { try { DescribeInstanceAttributeRequest request = DescribeInstanceAttributeRequest.builder() - .instanceId(instanceId) - .attributeType(InstanceAttributeType.USE_CUSTOM_TTS_VOICES) - .build(); + .instanceId(instanceId) + .attributeType(InstanceAttributeType.USE_CUSTOM_TTS_VOICES) + .build(); DescribeInstanceAttributeResponse response = connectClient.describeInstanceAttribute(request); System.out.println("The attribute value is " + response.attribute().attributeType().toString()); diff --git a/javav2/example_code/connect/src/main/java/com/example/connect/GetContactAttributes.java b/javav2/example_code/connect/src/main/java/com/example/connect/GetContactAttributes.java index c3b9a0d561b..7654e1b25de 100644 --- a/javav2/example_code/connect/src/main/java/com/example/connect/GetContactAttributes.java +++ b/javav2/example_code/connect/src/main/java/com/example/connect/GetContactAttributes.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[GetContactAttributes.java demonstrates how to describe the specified contact attributes.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Connect] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.connect; @@ -18,7 +12,8 @@ import java.util.Map; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +23,12 @@ public class GetContactAttributes { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - instanceId - The identifier of the Amazon Connect instance. - contactId - The identifier of the contact. - """; + Where: + instanceId - The identifier of the Amazon Connect instance. + contactId - The identifier of the contact. + """; if (args.length != 2) { System.out.println(usage); @@ -44,8 +39,8 @@ public static void main(String[] args) { String contactId = args[1]; Region region = Region.US_EAST_1; ConnectClient connectClient = ConnectClient.builder() - .region(region) - .build(); + .region(region) + .build(); getContactAttrs(connectClient, instanceId, contactId); } @@ -53,9 +48,9 @@ public static void main(String[] args) { public static void getContactAttrs(ConnectClient connectClient, String instanceId, String contactId) { try { GetContactAttributesRequest attributesRequest = GetContactAttributesRequest.builder() - .instanceId(instanceId) - .initialContactId(contactId) - .build(); + .instanceId(instanceId) + .initialContactId(contactId) + .build(); GetContactAttributesResponse response = connectClient.getContactAttributes(attributesRequest); Map attributeMap = response.attributes(); @@ -69,4 +64,3 @@ public static void getContactAttrs(ConnectClient connectClient, String instanceI } } // snippet-end:[connect.java2.contact.attr.main] - diff --git a/javav2/example_code/connect/src/main/java/com/example/connect/GetMetricData.java b/javav2/example_code/connect/src/main/java/com/example/connect/GetMetricData.java index 85ea9fbf00b..51dfbf8b900 100644 --- a/javav2/example_code/connect/src/main/java/com/example/connect/GetMetricData.java +++ b/javav2/example_code/connect/src/main/java/com/example/connect/GetMetricData.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[GetMetricData.java demonstrates how to get historical metric data from the specified Amazon Connect instance.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Connect] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.connect; @@ -33,7 +27,8 @@ import java.util.Locale; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -47,13 +42,13 @@ public class GetMetricData { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - instanceId - The identifier of the Amazon Connect instance. - queueId - The identifier of the queue. + Where: + instanceId - The identifier of the Amazon Connect instance. + queueId - The identifier of the queue. - """; + """; if (args.length != 2) { System.out.println(usage); @@ -64,8 +59,8 @@ public static void main(String[] args) { String queueId = args[1]; Region region = Region.US_EAST_1; ConnectClient connectClient = ConnectClient.builder() - .region(region) - .build(); + .region(region) + .build(); getHistoricalMetrics(connectClient, instanceId, queueId); } @@ -74,21 +69,21 @@ public static void getHistoricalMetrics(ConnectClient connectClient, String inst try { // Define the metrics to retrieve. Threshold threshold = Threshold.builder() - .comparison(Comparison.LT) - .thresholdValue(10.0) - .build(); + .comparison(Comparison.LT) + .thresholdValue(10.0) + .build(); HistoricalMetric contactMetric = HistoricalMetric.builder() - .name(HistoricalMetricName.CONTACTS_HANDLED) - .statistic(Statistic.SUM) - .threshold(threshold) - .unit(Unit.COUNT) - .build(); + .name(HistoricalMetricName.CONTACTS_HANDLED) + .statistic(Statistic.SUM) + .threshold(threshold) + .unit(Unit.COUNT) + .build(); Filters filter = Filters.builder() - .channels(Channel.VOICE) - .queues(queueId) - .build(); + .channels(Channel.VOICE) + .queues(queueId) + .build(); String stringDate = "09:05:00 AM, Tue 01/03/2023"; // Add a new date value. String pattern = "hh:mm:ss a, EEE M/d/uuuu"; @@ -102,13 +97,13 @@ public static void getHistoricalMetrics(ConnectClient connectClient, String inst Instant endInstant = localDateTime2.toInstant(ZoneOffset.UTC); GetMetricDataRequest dataRequest = GetMetricDataRequest.builder() - .instanceId(instanceId) - .endTime(endInstant) - .startTime(startInstant) - .filters(filter) - .maxResults(10) - .historicalMetrics(contactMetric) - .build(); + .instanceId(instanceId) + .endTime(endInstant) + .startTime(startInstant) + .filters(filter) + .maxResults(10) + .historicalMetrics(contactMetric) + .build(); GetMetricDataResponse response = connectClient.getMetricData(dataRequest); List resultList = response.metricResults(); diff --git a/javav2/example_code/connect/src/main/java/com/example/connect/ListInstances.java b/javav2/example_code/connect/src/main/java/com/example/connect/ListInstances.java index 4dc1dea25b5..1dd8d7cc39d 100644 --- a/javav2/example_code/connect/src/main/java/com/example/connect/ListInstances.java +++ b/javav2/example_code/connect/src/main/java/com/example/connect/ListInstances.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[ListInstances.java demonstrates how to list Amazon Connect instances.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Connect] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.connect; @@ -19,7 +13,8 @@ import java.util.List; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,8 +24,8 @@ public class ListInstances { public static void main(String[] args) { Region region = Region.US_EAST_1; ConnectClient connectClient = ConnectClient.builder() - .region(region) - .build(); + .region(region) + .build(); listAllInstances(connectClient); } @@ -38,8 +33,8 @@ public static void main(String[] args) { public static void listAllInstances(ConnectClient connectClient) { try { ListInstancesRequest instancesRequest = ListInstancesRequest.builder() - .maxResults(10) - .build(); + .maxResults(10) + .build(); ListInstancesResponse response = connectClient.listInstances(instancesRequest); List instances = response.instanceSummaryList(); diff --git a/javav2/example_code/connect/src/main/java/com/example/connect/ListPhoneNumbers.java b/javav2/example_code/connect/src/main/java/com/example/connect/ListPhoneNumbers.java index 4c3b87931b6..7c2e6d714aa 100644 --- a/javav2/example_code/connect/src/main/java/com/example/connect/ListPhoneNumbers.java +++ b/javav2/example_code/connect/src/main/java/com/example/connect/ListPhoneNumbers.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[ListPhoneNumbers.java demonstrates how to list Amazon Connect instance phone numbers.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Connect] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.connect; // snippet-start:[connect.java2.list.phone.numbers.main] @@ -19,7 +14,8 @@ import java.util.List; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,10 +24,10 @@ public class ListPhoneNumbers { public static void main(String[] args) { final String usage = "\n" + - "Usage: " + - " \n\n" + - "Where:\n" + - " targetArn - The ARN of the Amazon Connect instance.\n\n"; + "Usage: " + + " \n\n" + + "Where:\n" + + " targetArn - The ARN of the Amazon Connect instance.\n\n"; if (args.length != 1) { System.out.println(usage); @@ -41,8 +37,8 @@ public static void main(String[] args) { String targetArn = args[0]; Region region = Region.US_EAST_1; ConnectClient connectClient = ConnectClient.builder() - .region(region) - .build(); + .region(region) + .build(); getPhoneNumbers(connectClient, targetArn); } @@ -50,10 +46,10 @@ public static void main(String[] args) { public static void getPhoneNumbers(ConnectClient connectClient, String targetArn) { try { ListPhoneNumbersV2Request numbersV2Request = ListPhoneNumbersV2Request.builder() - .maxResults(10) - .phoneNumberTypes(PhoneNumberType.TOLL_FREE) - .targetArn(targetArn) - .build(); + .maxResults(10) + .phoneNumberTypes(PhoneNumberType.TOLL_FREE) + .targetArn(targetArn) + .build(); ListPhoneNumbersV2Response response = connectClient.listPhoneNumbersV2(numbersV2Request); List numbers = response.listPhoneNumbersSummaryList(); diff --git a/javav2/example_code/connect/src/main/java/com/example/connect/ListUsers.java b/javav2/example_code/connect/src/main/java/com/example/connect/ListUsers.java index 371e173cc8e..de89f64d785 100644 --- a/javav2/example_code/connect/src/main/java/com/example/connect/ListUsers.java +++ b/javav2/example_code/connect/src/main/java/com/example/connect/ListUsers.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[ListUsers.java demonstrates how to list Amazon Connect instance users.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Connect] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.connect; @@ -20,7 +14,8 @@ import java.util.List; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,12 +25,12 @@ public class ListUsers { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - instanceId - The id of the Amazon Connect instance. + Where: + instanceId - The id of the Amazon Connect instance. - """; + """; if (args.length != 1) { System.out.println(usage); @@ -45,8 +40,8 @@ public static void main(String[] args) { String instanceId = args[0]; Region region = Region.US_EAST_1; ConnectClient connectClient = ConnectClient.builder() - .region(region) - .build(); + .region(region) + .build(); getUsers(connectClient, instanceId); } @@ -54,9 +49,9 @@ public static void main(String[] args) { public static void getUsers(ConnectClient connectClient, String instanceId) { try { ListUsersRequest usersRequest = ListUsersRequest.builder() - .instanceId(instanceId) - .maxResults(10) - .build(); + .instanceId(instanceId) + .maxResults(10) + .build(); ListUsersResponse response = connectClient.listUsers(usersRequest); List users = response.userSummaryList(); @@ -72,4 +67,3 @@ public static void getUsers(ConnectClient connectClient, String instanceId) { } } // snippet-end:[connect.java2.list.users.main] - diff --git a/javav2/example_code/connect/src/main/java/com/example/connect/SearchQueues.java b/javav2/example_code/connect/src/main/java/com/example/connect/SearchQueues.java index f41ce9ca994..c6f93e4d49f 100644 --- a/javav2/example_code/connect/src/main/java/com/example/connect/SearchQueues.java +++ b/javav2/example_code/connect/src/main/java/com/example/connect/SearchQueues.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[SearchQueues.java demonstrates how to search queues in an Amazon Connect instance.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Connect] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.connect; @@ -19,7 +13,8 @@ import java.util.List; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,11 +25,11 @@ public class SearchQueues { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - instanceId - The id of the Amazon Connect instance. - """; + Where: + instanceId - The id of the Amazon Connect instance. + """; if (args.length != 1) { System.out.println(usage); @@ -44,8 +39,8 @@ public static void main(String[] args) { String instanceId = args[0]; Region region = Region.US_EAST_1; ConnectClient connectClient = ConnectClient.builder() - .region(region) - .build(); + .region(region) + .build(); searchQueue(connectClient, instanceId); } @@ -53,9 +48,9 @@ public static void main(String[] args) { public static void searchQueue(ConnectClient connectClient, String instanceId) { try { SearchQueuesRequest queuesRequest = SearchQueuesRequest.builder() - .instanceId(instanceId) - .maxResults(10) - .build(); + .instanceId(instanceId) + .maxResults(10) + .build(); SearchQueuesResponse response = connectClient.searchQueues(queuesRequest); List queuesList = response.queues(); diff --git a/javav2/example_code/connect/src/test/java/ConnectTest.java b/javav2/example_code/connect/src/test/java/ConnectTest.java index a88c092a64a..8f3fba8467e 100644 --- a/javav2/example_code/connect/src/test/java/ConnectTest.java +++ b/javav2/example_code/connect/src/test/java/ConnectTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.connect.CreateInstance; import com.example.connect.DeleteInstance; @@ -41,17 +39,17 @@ public class ConnectTest { private static ConnectClient connectClient; private static String instanceAlias = ""; - private static String instanceId = "" ; - private static String contactId = "" ; - private static String existingInstanceId = "" ; - private static String targetArn = "" ; + private static String instanceId = ""; + private static String contactId = ""; + private static String existingInstanceId = ""; + private static String targetArn = ""; @BeforeAll public static void setUp() { connectClient = ConnectClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -62,27 +60,30 @@ public static void setUp() { existingInstanceId = values.getExistingInstanceId(); targetArn = values.getTargetArn(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - - try (InputStream input = ConnectTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - // Load a properties file. - prop.load(input); - instanceAlias = prop.getProperty("instanceAlias"); - contactId = prop.getProperty("contactId"); - existingInstanceId = prop.getProperty("existingInstanceId"); - targetArn = prop.getProperty("targetArn"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * + * try (InputStream input = + * ConnectTest.class.getClassLoader().getResourceAsStream("config.properties")) + * { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * // Load a properties file. + * prop.load(input); + * instanceAlias = prop.getProperty("instanceAlias"); + * contactId = prop.getProperty("contactId"); + * existingInstanceId = prop.getProperty("existingInstanceId"); + * targetArn = prop.getProperty("targetArn"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @@ -98,7 +99,7 @@ public void createInstance() { @Tag("IntegrationTest") @Order(2) public void describeInstance() throws InterruptedException { - assertDoesNotThrow(() ->DescribeInstance.describeSpecificInstance(connectClient, instanceId)); + assertDoesNotThrow(() -> DescribeInstance.describeSpecificInstance(connectClient, instanceId)); System.out.println("Test 2 passed"); } @@ -106,7 +107,7 @@ public void describeInstance() throws InterruptedException { @Tag("IntegrationTest") @Order(3) public void listInstances() { - assertDoesNotThrow(() ->ListInstances.listAllInstances(connectClient)); + assertDoesNotThrow(() -> ListInstances.listAllInstances(connectClient)); System.out.println("Test 3 passed"); } @@ -114,22 +115,22 @@ public void listInstances() { @Tag("IntegrationTest") @Order(4) public void deleteInstance() { - assertDoesNotThrow(() ->DeleteInstance.deleteSpecificInstance(connectClient, instanceId)); + assertDoesNotThrow(() -> DeleteInstance.deleteSpecificInstance(connectClient, instanceId)); System.out.println("Test 4 passed"); } @Test @Order(5) public void describeContact() { - assertDoesNotThrow(() ->DescribeContact.describeSpecificContact(connectClient, existingInstanceId, contactId)); + assertDoesNotThrow(() -> DescribeContact.describeSpecificContact(connectClient, existingInstanceId, contactId)); System.out.println("Test 5 passed"); - } + } @Test @Tag("IntegrationTest") @Order(6) public void describeInstanceAttribute() { - assertDoesNotThrow(() ->DescribeInstanceAttribute.describeAttribute(connectClient, existingInstanceId)); + assertDoesNotThrow(() -> DescribeInstanceAttribute.describeAttribute(connectClient, existingInstanceId)); System.out.println("Test 6 passed"); } @@ -145,7 +146,7 @@ public void getContactAttributes() { @Tag("IntegrationTest") @Order(8) public void listPhoneNumbers() { - assertDoesNotThrow(() ->ListPhoneNumbers.getPhoneNumbers(connectClient, targetArn)); + assertDoesNotThrow(() -> ListPhoneNumbers.getPhoneNumbers(connectClient, targetArn)); System.out.println("Test 8 passed"); } @@ -153,7 +154,7 @@ public void listPhoneNumbers() { @Tag("IntegrationTest") @Order(9) public void listUsers() { - assertDoesNotThrow(() ->ListUsers.getUsers(connectClient, existingInstanceId)); + assertDoesNotThrow(() -> ListUsers.getUsers(connectClient, existingInstanceId)); System.out.println("Test 9 passed"); } @@ -161,20 +162,20 @@ public void listUsers() { @Tag("IntegrationTest") @Order(10) public void searchQueues() { - assertDoesNotThrow(() ->SearchQueues.searchQueue(connectClient, existingInstanceId)); + assertDoesNotThrow(() -> SearchQueues.searchQueue(connectClient, existingInstanceId)); System.out.println("Test 10 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/connect"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -206,4 +207,3 @@ public String getTargetArn() { } } } - diff --git a/javav2/example_code/dynamodb/run_example.sh b/javav2/example_code/dynamodb/run_example.sh index 773ca3b5d3f..c820d0913b1 100755 --- a/javav2/example_code/dynamodb/run_example.sh +++ b/javav2/example_code/dynamodb/run_example.sh @@ -1,12 +1,14 @@ -#!/bin/bash -if [[ -z $* ]] ; then - echo 'Supply the name of one of the example classes as an argument.' - echo 'If there are arguments to the class, put them in quotes after the class name.' - exit 1 -fi -export CLASSPATH=target/sdk-dynamodb-examples-1.0.jar -export className=$1 -echo "## Running $className..." -shift -echo "## arguments $@..." -mvn exec:java -Dexec.mainClass="com.example.dynamodb.$className" -Dexec.args="$@" +#!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +if [[ -z $* ]] ; then + echo 'Supply the name of one of the example classes as an argument.' + echo 'If there are arguments to the class, put them in quotes after the class name.' + exit 1 +fi +export CLASSPATH=target/sdk-dynamodb-examples-1.0.jar +export className=$1 +echo "## Running $className..." +shift +echo "## arguments $@..." +mvn exec:java -Dexec.mainClass="com.example.dynamodb.$className" -Dexec.args="$@" diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Contact.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Contact.java index 149ad3adf5b..4c38cad918b 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Contact.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Contact.java @@ -1,7 +1,6 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.dynamodb; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; @@ -16,21 +15,20 @@ @DynamoDbBean public class Contact { - public static final StaticTableSchema.Builder TABLE_SCHEMA = - StaticTableSchema.builder(Contact.class) - .newItemSupplier(Contact::new) - .addAttribute(String.class, a -> a.name("id") - .getter(Contact::getId) - .setter(Contact::setId) - .tags(primaryPartitionKey())) - .addAttribute(EnhancedType.listOf(String.class), - a -> a.name("pid") - .getter(Contact::getPid) - .setter(Contact::setPid) - .attributeConverter(ListAttributeConverter.builder(EnhancedType.listOf(String.class)) - .collectionConstructor(ArrayList::new) - .elementConverter(StringAttributeConverter.create()) - .build())); + public static final StaticTableSchema.Builder TABLE_SCHEMA = StaticTableSchema.builder(Contact.class) + .newItemSupplier(Contact::new) + .addAttribute(String.class, a -> a.name("id") + .getter(Contact::getId) + .setter(Contact::setId) + .tags(primaryPartitionKey())) + .addAttribute(EnhancedType.listOf(String.class), + a -> a.name("pid") + .getter(Contact::getPid) + .setter(Contact::setPid) + .attributeConverter(ListAttributeConverter.builder(EnhancedType.listOf(String.class)) + .collectionConstructor(ArrayList::new) + .elementConverter(StringAttributeConverter.create()) + .build())); private String id; private List pid; diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/CreateTable.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/CreateTable.java index 1ea42fc06d5..426002ccc28 100755 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/CreateTable.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/CreateTable.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[CreateTable.java demonstrates how to create an Amazon DynamoDB table by using a waiter.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb; @@ -28,7 +22,8 @@ // snippet-end:[dynamodb.java2.create_table.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -38,13 +33,13 @@ public class CreateTable { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - tableName - The Amazon DynamoDB table to create (for example, Music3). - key - The key for the Amazon DynamoDB table (for example, Artist). - """; + Where: + tableName - The Amazon DynamoDB table to create (for example, Music3). + key - The key for the Amazon DynamoDB table (for example, Artist). + """; if (args.length != 2) { System.out.println(usage); @@ -56,8 +51,8 @@ public static void main(String[] args) { System.out.println("Creating an Amazon DynamoDB table " + tableName + " with a simple primary key: " + key); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); String result = createTable(ddb, tableName, key); System.out.println("New table is " + result); @@ -67,27 +62,27 @@ public static void main(String[] args) { public static String createTable(DynamoDbClient ddb, String tableName, String key) { DynamoDbWaiter dbWaiter = ddb.waiter(); CreateTableRequest request = CreateTableRequest.builder() - .attributeDefinitions(AttributeDefinition.builder() - .attributeName(key) - .attributeType(ScalarAttributeType.S) - .build()) - .keySchema(KeySchemaElement.builder() - .attributeName(key) - .keyType(KeyType.HASH) - .build()) - .provisionedThroughput(ProvisionedThroughput.builder() - .readCapacityUnits(10L) - .writeCapacityUnits(10L) - .build()) - .tableName(tableName) - .build(); + .attributeDefinitions(AttributeDefinition.builder() + .attributeName(key) + .attributeType(ScalarAttributeType.S) + .build()) + .keySchema(KeySchemaElement.builder() + .attributeName(key) + .keyType(KeyType.HASH) + .build()) + .provisionedThroughput(ProvisionedThroughput.builder() + .readCapacityUnits(10L) + .writeCapacityUnits(10L) + .build()) + .tableName(tableName) + .build(); String newTable; try { CreateTableResponse response = ddb.createTable(request); DescribeTableRequest tableRequest = DescribeTableRequest.builder() - .tableName(tableName) - .build(); + .tableName(tableName) + .build(); // Wait until the Amazon DynamoDB table is created. WaiterResponse waiterResponse = dbWaiter.waitUntilTableExists(tableRequest); diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/CreateTableCompositeKey.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/CreateTableCompositeKey.java index b6bb6e1e933..6ae7dd9810f 100755 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/CreateTableCompositeKey.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/CreateTableCompositeKey.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[CreateTableCompositeKey.java demonstrates how to create an Amazon DynamoDB table with a composite key.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb; @@ -24,7 +18,8 @@ // snippet-end:[dynamodb.java2.create_table_composite_key.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -35,12 +30,12 @@ public class CreateTableCompositeKey { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - tableName - The Amazon DynamoDB table to create (for example, Music3). - """; + Where: + tableName - The Amazon DynamoDB table to create (for example, Music3). + """; if (args.length != 1) { System.out.println(usage); @@ -50,8 +45,8 @@ public static void main(String[] args) { String tableName = args[0]; Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.format("Creating Amazon DynamoDB table %s\n with a composite primary key:\n", tableName); System.out.format("* Language - partition key\n"); @@ -63,27 +58,27 @@ public static void main(String[] args) { public static String createTableComKey(DynamoDbClient ddb, String tableName) { CreateTableRequest request = CreateTableRequest.builder() - .attributeDefinitions(AttributeDefinition.builder() - .attributeName("Language") - .attributeType(ScalarAttributeType.S) - .build(), - AttributeDefinition.builder() - .attributeName("Greeting") - .attributeType(ScalarAttributeType.S) - .build()) - .keySchema(KeySchemaElement.builder() - .attributeName("Language") - .keyType(KeyType.HASH) - .build(), - KeySchemaElement.builder() - .attributeName("Greeting") - .keyType(KeyType.RANGE) - .build()) - .provisionedThroughput(ProvisionedThroughput.builder() - .readCapacityUnits(10L) - .writeCapacityUnits(10L).build()) - .tableName(tableName) - .build(); + .attributeDefinitions(AttributeDefinition.builder() + .attributeName("Language") + .attributeType(ScalarAttributeType.S) + .build(), + AttributeDefinition.builder() + .attributeName("Greeting") + .attributeType(ScalarAttributeType.S) + .build()) + .keySchema(KeySchemaElement.builder() + .attributeName("Language") + .keyType(KeyType.HASH) + .build(), + KeySchemaElement.builder() + .attributeName("Greeting") + .keyType(KeyType.RANGE) + .build()) + .provisionedThroughput(ProvisionedThroughput.builder() + .readCapacityUnits(10L) + .writeCapacityUnits(10L).build()) + .tableName(tableName) + .build(); String tableId; try { diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Customer.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Customer.java index 583635c9223..2f617134e13 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Customer.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Customer.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb; @@ -15,50 +13,51 @@ * This class is used by the Enhanced Client examples. */ - @DynamoDbBean - public class Customer { - private String id; - private String name; - private String email; - private Instant regDate; +@DynamoDbBean +public class Customer { + private String id; + private String name; + private String email; + private Instant regDate; - @DynamoDbPartitionKey - public String getId() { - return this.id; - } + @DynamoDbPartitionKey + public String getId() { + return this.id; + } - public void setId(String id) { + public void setId(String id) { - this.id = id; - } + this.id = id; + } - public String getCustName() { - return this.name; - } + public String getCustName() { + return this.name; + } - public void setCustName(String name) { - this.name = name; - } + public void setCustName(String name) { + this.name = name; + } - @DynamoDbSortKey - public String getEmail() { - return this.email; - } + @DynamoDbSortKey + public String getEmail() { + return this.email; + } - public void setEmail(String email) { - this.email = email; - } + public void setEmail(String email) { + this.email = email; + } + + public Instant getRegistrationDate() { + return regDate; + } - public Instant getRegistrationDate() { - return regDate; - } - public void setRegistrationDate(Instant registrationDate) { - this.regDate = registrationDate; - } + public void setRegistrationDate(Instant registrationDate) { + this.regDate = registrationDate; + } - @Override - public String toString() { - return "Customer [id=" + id + ", name=" + name + ", email=" + email - + ", regDate=" + regDate + "]"; - } + @Override + public String toString() { + return "Customer [id=" + id + ", name=" + name + ", email=" + email + + ", regDate=" + regDate + "]"; } +} diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DeleteItem.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DeleteItem.java index 26ddfb8e4b1..9c795595fc6 100755 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DeleteItem.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DeleteItem.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DeleteItem.java demonstrates how to delete an item from an Amazon DynamoDB table.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb; @@ -20,7 +14,8 @@ // snippet-end:[dynamodb.java2.delete_item.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,14 +25,14 @@ public class DeleteItem { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - tableName - The Amazon DynamoDB table to delete the item from (for example, Music3). - key - The key used in the Amazon DynamoDB table (for example, Artist).\s - keyval - The key value that represents the item to delete (for example, Famous Band). - """; + Where: + tableName - The Amazon DynamoDB table to delete the item from (for example, Music3). + key - The key used in the Amazon DynamoDB table (for example, Artist).\s + keyval - The key value that represents the item to delete (for example, Famous Band). + """; if (args.length != 3) { System.out.println(usage); @@ -50,8 +45,8 @@ public static void main(String[] args) { System.out.format("Deleting item \"%s\" from %s\n", keyVal, tableName); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteDynamoDBItem(ddb, tableName, key, keyVal); ddb.close(); @@ -60,13 +55,13 @@ public static void main(String[] args) { public static void deleteDynamoDBItem(DynamoDbClient ddb, String tableName, String key, String keyVal) { HashMap keyToGet = new HashMap<>(); keyToGet.put(key, AttributeValue.builder() - .s(keyVal) - .build()); + .s(keyVal) + .build()); DeleteItemRequest deleteReq = DeleteItemRequest.builder() - .tableName(tableName) - .key(keyToGet) - .build(); + .tableName(tableName) + .key(keyToGet) + .build(); try { ddb.deleteItem(deleteReq); @@ -77,4 +72,3 @@ public static void deleteDynamoDBItem(DynamoDbClient ddb, String tableName, Stri } } // snippet-end:[dynamodb.java2.delete_item.main] - diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DeleteTable.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DeleteTable.java index 8e670ff258f..74b704748d1 100755 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DeleteTable.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DeleteTable.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[DeleteTable.java demonstrates how to delete an Amazon DynamoDB table.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.dynamodb; // snippet-start:[dynamodb.java2.delete_table.main] @@ -17,7 +12,8 @@ // snippet-end:[dynamodb.java2.delete_table.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,14 +24,14 @@ public class DeleteTable { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - tableName - The Amazon DynamoDB table to delete (for example, Music3). + Where: + tableName - The Amazon DynamoDB table to delete (for example, Music3). - **Warning** This program will delete the table that you specify! - """; + **Warning** This program will delete the table that you specify! + """; if (args.length != 1) { System.out.println(usage); @@ -46,8 +42,8 @@ public static void main(String[] args) { System.out.format("Deleting the Amazon DynamoDB table %s...\n", tableName); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteDynamoDBTable(ddb, tableName); ddb.close(); @@ -55,8 +51,8 @@ public static void main(String[] args) { public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) { DeleteTableRequest request = DeleteTableRequest.builder() - .tableName(tableName) - .build(); + .tableName(tableName) + .build(); try { ddb.deleteTable(request); @@ -69,4 +65,3 @@ public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) { } } // snippet-end:[dynamodb.java2.delete_table.main] - diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DescribeTable.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DescribeTable.java index c179313f90a..49a001ee9d3 100755 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DescribeTable.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DescribeTable.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeTable.java demonstrates how to retrieve information about an Amazon DynamoDB table.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb; @@ -22,7 +16,8 @@ // snippet-end:[dynamodb.java2.describe_table.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,12 +27,12 @@ public class DescribeTable { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - tableName - The Amazon DynamoDB table to get information about (for example, Music3). - """; + Where: + tableName - The Amazon DynamoDB table to get information about (for example, Music3). + """; if (args.length != 1) { System.out.println(usage); @@ -48,8 +43,8 @@ public static void main(String[] args) { System.out.format("Getting description for %s\n\n", tableName); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeDymamoDBTable(ddb, tableName); ddb.close(); @@ -57,8 +52,8 @@ public static void main(String[] args) { public static void describeDymamoDBTable(DynamoDbClient ddb, String tableName) { DescribeTableRequest request = DescribeTableRequest.builder() - .tableName(tableName) - .build(); + .tableName(tableName) + .build(); try { TableDescription tableInfo = ddb.describeTable(request).table(); @@ -88,6 +83,4 @@ public static void describeDymamoDBTable(DynamoDbClient ddb, String tableName) { System.out.println("\nDone!"); } } - // snippet-end:[dynamodb.java2.describe_table.main] - - +// snippet-end:[dynamodb.java2.describe_table.main] diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DynamoDBPartiQ.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DynamoDBPartiQ.java index 0f8444a5937..fc568f6ee90 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DynamoDBPartiQ.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DynamoDBPartiQ.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DynamoDBPartiQ.java demonstrates how to work with PartiQL for Amazon DynamoDB.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb; @@ -33,70 +27,88 @@ */ public class DynamoDBPartiQ { - public static void main(String[] args) { - Region region = Region.US_EAST_1; - DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); - - AttributeValue att1 = AttributeValue.builder() - .s("Acme Band") - .build(); - - AttributeValue att2 = AttributeValue.builder() - .s("PartiQL Rocks") - .build(); - - List parameters = new ArrayList<>(); - parameters.add(att1); - parameters.add(att2); - queryTable(ddb, parameters); - } - - public static void queryTable(DynamoDbClient ddb, List parameters ) { - - // Retrieve an item from the Music table using the SELECT PartiQL statement. - ExecuteStatementResponse response = executeStatementRequest(ddb, "SELECT COUNT(SongTitle) FROM Music", parameters); - processResults(response); - - //Update an item in the Music table using the UPDATE PartiQL statement. - processResults(executeStatementRequest(ddb, "UPDATE Music SET AwardsWon=1 SET AwardDetail={'Grammys':[2020, 2018]} where Artist=? and SongTitle=?", parameters)); - - //Add a list value for an item in the Music table. - ExecuteStatementResponse resp2 = executeStatementRequest(ddb, "UPDATE Music SET AwardDetail.Grammys =LIST_APPEND(AwardDetail.Grammys,[2016]) where Artist=? and SongTitle=?", parameters); - processResults(resp2); - - // Add a new string set attribute for an item in the Music table. - processResults(executeStatementRequest(ddb, "UPDATE Music SET BandMembers =<<'member1', 'member2'>> where Artist=? and SongTitle=?", parameters)); - - // Add a list value for an item in the Music table. - processResults(executeStatementRequest(ddb, "UPDATE Music SET AwardDetail.Grammys =list_append(AwardDetail.Grammys,[2016]) where Artist=? and SongTitle=?", parameters)); - - // Remove a list value for an item in the Music table. - processResults(executeStatementRequest(ddb, "UPDATE Music REMOVE AwardDetail.Grammys[2] where Artist=? and SongTitle=?", parameters)); - - // Add a new map member for an item in the Music table. - processResults(executeStatementRequest(ddb, "UPDATE Music set AwardDetail.BillBoard=[2020] where Artist=? and SongTitle=?", parameters)); - - // Add a new string set attribute for an item in the Music table. - processResults(executeStatementRequest(ddb, "UPDATE Music SET BandMembers =<<'member1', 'member2'>> where Artist=? and SongTitle=?", parameters)); - - // Update a string set attribute for an item in the Music table. - processResults(executeStatementRequest(ddb, "UPDATE Music SET BandMembers =set_add(BandMembers, <<'newmember'>>) where Artist=? and SongTitle=?", parameters)); - System.out.println("This code example has completed"); - } - - private static ExecuteStatementResponse executeStatementRequest(DynamoDbClient ddb, String statement, List parameters ) { - ExecuteStatementRequest request = ExecuteStatementRequest.builder() - .statement(statement) - .parameters(parameters) - .build(); - - return ddb.executeStatement(request); - } - - private static void processResults(ExecuteStatementResponse executeStatementResult) { - System.out.println("ExecuteStatement successful: "+ executeStatementResult.toString()); - } + public static void main(String[] args) { + Region region = Region.US_EAST_1; + DynamoDbClient ddb = DynamoDbClient.builder() + .region(region) + .build(); + + AttributeValue att1 = AttributeValue.builder() + .s("Acme Band") + .build(); + + AttributeValue att2 = AttributeValue.builder() + .s("PartiQL Rocks") + .build(); + + List parameters = new ArrayList<>(); + parameters.add(att1); + parameters.add(att2); + queryTable(ddb, parameters); + } + + public static void queryTable(DynamoDbClient ddb, List parameters) { + + // Retrieve an item from the Music table using the SELECT PartiQL statement. + ExecuteStatementResponse response = executeStatementRequest(ddb, "SELECT COUNT(SongTitle) FROM Music", + parameters); + processResults(response); + + // Update an item in the Music table using the UPDATE PartiQL statement. + processResults(executeStatementRequest(ddb, + "UPDATE Music SET AwardsWon=1 SET AwardDetail={'Grammys':[2020, 2018]} where Artist=? and SongTitle=?", + parameters)); + + // Add a list value for an item in the Music table. + ExecuteStatementResponse resp2 = executeStatementRequest(ddb, + "UPDATE Music SET AwardDetail.Grammys =LIST_APPEND(AwardDetail.Grammys,[2016]) where Artist=? and SongTitle=?", + parameters); + processResults(resp2); + + // Add a new string set attribute for an item in the Music table. + processResults(executeStatementRequest(ddb, + "UPDATE Music SET BandMembers =<<'member1', 'member2'>> where Artist=? and SongTitle=?", + parameters)); + + // Add a list value for an item in the Music table. + processResults(executeStatementRequest(ddb, + "UPDATE Music SET AwardDetail.Grammys =list_append(AwardDetail.Grammys,[2016]) where Artist=? and SongTitle=?", + parameters)); + + // Remove a list value for an item in the Music table. + processResults(executeStatementRequest(ddb, + "UPDATE Music REMOVE AwardDetail.Grammys[2] where Artist=? and SongTitle=?", + parameters)); + + // Add a new map member for an item in the Music table. + processResults(executeStatementRequest(ddb, + "UPDATE Music set AwardDetail.BillBoard=[2020] where Artist=? and SongTitle=?", + parameters)); + + // Add a new string set attribute for an item in the Music table. + processResults(executeStatementRequest(ddb, + "UPDATE Music SET BandMembers =<<'member1', 'member2'>> where Artist=? and SongTitle=?", + parameters)); + + // Update a string set attribute for an item in the Music table. + processResults(executeStatementRequest(ddb, + "UPDATE Music SET BandMembers =set_add(BandMembers, <<'newmember'>>) where Artist=? and SongTitle=?", + parameters)); + System.out.println("This code example has completed"); + } + + private static ExecuteStatementResponse executeStatementRequest(DynamoDbClient ddb, String statement, + List parameters) { + ExecuteStatementRequest request = ExecuteStatementRequest.builder() + .statement(statement) + .parameters(parameters) + .build(); + + return ddb.executeStatement(request); + } + + private static void processResults(ExecuteStatementResponse executeStatementResult) { + System.out.println("ExecuteStatement successful: " + executeStatementResult.toString()); + } } // snippet-end:[dynamodb.java2.partiql.main] diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DynamoDBScanItems.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DynamoDBScanItems.java index cfdf0b289f0..23d822f5e0f 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DynamoDBScanItems.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/DynamoDBScanItems.java @@ -1,10 +1,5 @@ -// snippet-sourcedescription:[DynamoDBScanItems demonstrates how to return items from an Amazon DynamoDB table.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb; @@ -21,13 +16,15 @@ // snippet-end:[dynamodb.java2.dynamoDB_scan.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * To scan items from an Amazon DynamoDB table using the AWS SDK for Java V2, its better practice to use the + * To scan items from an Amazon DynamoDB table using the AWS SDK for Java V2, + * its better practice to use the * Enhanced Client, See the EnhancedScanRecords example. */ @@ -36,12 +33,12 @@ public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - tableName - The Amazon DynamoDB table to get information from (for example, Music3). - """; + Where: + tableName - The Amazon DynamoDB table to get information from (for example, Music3). + """; if (args.length != 1) { System.out.println(usage); @@ -51,17 +48,18 @@ public static void main(String[] args) { String tableName = args[0]; Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); scanItems(ddb, tableName); ddb.close(); } + public static void scanItems(DynamoDbClient ddb, String tableName) { try { ScanRequest scanRequest = ScanRequest.builder() - .tableName(tableName) - .build(); + .tableName(tableName) + .build(); ScanResponse response = ddb.scan(scanRequest); for (Map item : response.items()) { diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/GetItem.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/GetItem.java index 7185ffe481b..13a5e2aeb3a 100755 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/GetItem.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/GetItem.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[GetItem.java demonstrates how to retrieve an item from an Amazon DynamoDB table.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb; @@ -22,27 +16,29 @@ // snippet-end:[dynamodb.java2.get_item.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * To get an item from an Amazon DynamoDB table using the AWS SDK for Java V2, its better practice to use the + * To get an item from an Amazon DynamoDB table using the AWS SDK for Java V2, + * its better practice to use the * Enhanced Client, see the EnhancedGetItem example. */ public class GetItem { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - tableName - The Amazon DynamoDB table from which an item is retrieved (for example, Music3).\s - key - The key used in the Amazon DynamoDB table (for example, Artist).\s - keyval - The key value that represents the item to get (for example, Famous Band). - """; + Where: + tableName - The Amazon DynamoDB table from which an item is retrieved (for example, Music3).\s + key - The key used in the Amazon DynamoDB table (for example, Artist).\s + keyval - The key value that represents the item to get (for example, Famous Band). + """; if (args.length != 3) { System.out.println(usage); @@ -55,8 +51,8 @@ public static void main(String[] args) { System.out.format("Retrieving item \"%s\" from \"%s\"\n", keyVal, tableName); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); getDynamoDBItem(ddb, tableName, key, keyVal); ddb.close(); @@ -65,13 +61,13 @@ public static void main(String[] args) { public static void getDynamoDBItem(DynamoDbClient ddb, String tableName, String key, String keyVal) { HashMap keyToGet = new HashMap<>(); keyToGet.put(key, AttributeValue.builder() - .s(keyVal) - .build()); + .s(keyVal) + .build()); GetItemRequest request = GetItemRequest.builder() - .key(keyToGet) - .tableName(tableName) - .build(); + .key(keyToGet) + .tableName(tableName) + .build(); try { // If there is no matching item, GetItem does not return any data. diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/ListTables.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/ListTables.java index 833eee4eb2d..65004cf7c7a 100755 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/ListTables.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/ListTables.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[ListTables.java demonstrates how to list all Amazon DynamoDB tables.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb; @@ -20,7 +14,8 @@ // snippet-end:[dynamodb.java2.list_tables.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,8 +26,8 @@ public static void main(String[] args) { System.out.println("Listing your Amazon DynamoDB tables:\n"); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); listAllTables(ddb); ddb.close(); } @@ -49,7 +44,7 @@ public static void listAllTables(DynamoDbClient ddb) { response = ddb.listTables(request); } else { ListTablesRequest request = ListTablesRequest.builder() - .exclusiveStartTableName(lastName).build(); + .exclusiveStartTableName(lastName).build(); response = ddb.listTables(request); } diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Movies.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Movies.java index 253cbeb8b72..1db1fb332b2 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Movies.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Movies.java @@ -1,7 +1,6 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.dynamodb; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; @@ -18,8 +17,9 @@ public class Movies { @DynamoDbSecondaryPartitionKey(indexNames = { "year-index" }) @DynamoDbPartitionKey public int getYear() { - return this.year; + return this.year; } + public void setYear(int year) { this.year = year; } @@ -28,6 +28,7 @@ public void setYear(int year) { public String getTitle() { return this.title; } + public void setTitle(String title) { this.title = title; } @@ -40,5 +41,3 @@ public void setInfo(String info) { this.info = info; } } - - diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Music.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Music.java index f722cbbb5e6..7aa19aec745 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Music.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Music.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/PutItem.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/PutItem.java index d896f564bfe..5c42826ac74 100755 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/PutItem.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/PutItem.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[PutItem.java demonstrates how to place an item into an Amazon DynamoDB table.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb; @@ -21,35 +16,36 @@ // snippet-end:[dynamodb.java2.put_item.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * To place items into an Amazon DynamoDB table using the AWS SDK for Java V2, - * its better practice to use the - * Enhanced Client. See the EnhancedPutItem example. + * To place items into an Amazon DynamoDB table using the AWS SDK for Java V2, + * its better practice to use the + * Enhanced Client. See the EnhancedPutItem example. */ public class PutItem { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - tableName - The Amazon DynamoDB table in which an item is placed (for example, Music3). - key - The key used in the Amazon DynamoDB table (for example, Artist). - keyval - The key value that represents the item to get (for example, Famous Band). - albumTitle - The Album title (for example, AlbumTitle). - AlbumTitleValue - The name of the album (for example, Songs About Life ). - Awards - The awards column (for example, Awards). - AwardVal - The value of the awards (for example, 10). - SongTitle - The song title (for example, SongTitle). - SongTitleVal - The value of the song title (for example, Happy Day). - **Warning** This program will place an item that you specify into a table! - """; + Where: + tableName - The Amazon DynamoDB table in which an item is placed (for example, Music3). + key - The key used in the Amazon DynamoDB table (for example, Artist). + keyval - The key value that represents the item to get (for example, Famous Band). + albumTitle - The Album title (for example, AlbumTitle). + AlbumTitleValue - The name of the album (for example, Songs About Life ). + Awards - The awards column (for example, Awards). + AwardVal - The value of the awards (for example, 10). + SongTitle - The song title (for example, SongTitle). + SongTitleVal - The value of the song title (for example, Happy Day). + **Warning** This program will place an item that you specify into a table! + """; if (args.length != 9) { System.out.println(usage); @@ -68,24 +64,25 @@ public static void main(String[] args) { Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); - putItemInTable(ddb, tableName, key, keyVal, albumTitle, albumTitleValue, awards, awardVal, songTitle, songTitleVal); + putItemInTable(ddb, tableName, key, keyVal, albumTitle, albumTitleValue, awards, awardVal, songTitle, + songTitleVal); System.out.println("Done!"); ddb.close(); } public static void putItemInTable(DynamoDbClient ddb, - String tableName, - String key, - String keyVal, - String albumTitle, - String albumTitleValue, - String awards, - String awardVal, - String songTitle, - String songTitleVal) { + String tableName, + String key, + String keyVal, + String albumTitle, + String albumTitleValue, + String awards, + String awardVal, + String songTitle, + String songTitleVal) { HashMap itemValues = new HashMap<>(); itemValues.put(key, AttributeValue.builder().s(keyVal).build()); @@ -94,13 +91,14 @@ public static void putItemInTable(DynamoDbClient ddb, itemValues.put(awards, AttributeValue.builder().s(awardVal).build()); PutItemRequest request = PutItemRequest.builder() - .tableName(tableName) - .item(itemValues) - .build(); + .tableName(tableName) + .item(itemValues) + .build(); try { PutItemResponse response = ddb.putItem(request); - System.out.println(tableName + " was successfully updated. The request id is " + response.responseMetadata().requestId()); + System.out.println(tableName + " was successfully updated. The request id is " + + response.responseMetadata().requestId()); } catch (ResourceNotFoundException e) { System.err.format("Error: The Amazon DynamoDB table \"%s\" can't be found.\n", tableName); @@ -113,4 +111,3 @@ public static void putItemInTable(DynamoDbClient ddb, } } // snippet-end:[dynamodb.java2.put_item.main] - diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/PutItemEncrypt.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/PutItemEncrypt.java index 4529b5576d8..8c1e348ca13 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/PutItemEncrypt.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/PutItemEncrypt.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[PutItemEncrypt.java demonstrates how to place an encrypted item into an Amazon DynamoDB table.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb; @@ -25,7 +19,8 @@ // snippet-end:[dynamodb.java2.put_item_enc.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -35,21 +30,21 @@ public class PutItemEncrypt { public static void main(String[] args) { final String usage = """ - Usage: - - - Where: - tableName - The Amazon DynamoDB table in which an item is placed (for example, Music3). - key - The key used in the Amazon DynamoDB table (for example, Artist). - keyval - The key value that represents the item to get (for example, Famous Band). - albumTitle - The album title (for example, AlbumTitle). - AlbumTitleValue - The name of the album (for example, Songs About Life ). - Awards - The awards column (for example, Awards). - AwardVal - The value of the awards (for example, 10). - SongTitle - The song title (for example, SongTitle). - SongTitleVal - The value of the song title (for example, Happy Day). - keyId - A KMS key id value to use to encrypt/decrypt the data (for example, xxxxxbcd-12ab-34cd-56ef-1234567890ab). - """; + Usage: + + + Where: + tableName - The Amazon DynamoDB table in which an item is placed (for example, Music3). + key - The key used in the Amazon DynamoDB table (for example, Artist). + keyval - The key value that represents the item to get (for example, Famous Band). + albumTitle - The album title (for example, AlbumTitle). + AlbumTitleValue - The name of the album (for example, Songs About Life ). + Awards - The awards column (for example, Awards). + AwardVal - The value of the awards (for example, 10). + SongTitle - The song title (for example, SongTitle). + SongTitleVal - The value of the song title (for example, Happy Day). + keyId - A KMS key id value to use to encrypt/decrypt the data (for example, xxxxxbcd-12ab-34cd-56ef-1234567890ab). + """; if (args.length != 10) { System.out.println(usage); @@ -69,38 +64,39 @@ public static void main(String[] args) { Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); // Create a KmsClient object to use to encrpt data. KmsClient kmsClient = KmsClient.builder() - .region(region) - .build(); + .region(region) + .build(); - putItemInTable(ddb, kmsClient, tableName, key, keyVal, albumTitle, albumTitleValue, awards, awardVal, songTitle, songTitleVal, keyId); + putItemInTable(ddb, kmsClient, tableName, key, keyVal, albumTitle, albumTitleValue, awards, awardVal, songTitle, + songTitleVal, keyId); System.out.println("Done!"); ddb.close(); } public static void putItemInTable(DynamoDbClient ddb, - KmsClient kmsClient, - String tableName, - String key, - String keyVal, - String albumTitle, - String albumTitleValue, - String awards, - String awardVal, - String songTitle, - String songTitleVal, - String keyId) { + KmsClient kmsClient, + String tableName, + String key, + String keyVal, + String albumTitle, + String albumTitleValue, + String awards, + String awardVal, + String songTitle, + String songTitleVal, + String keyId) { HashMap itemValues = new HashMap<>(); SdkBytes myBytes = SdkBytes.fromUtf8String(albumTitleValue); EncryptRequest encryptRequest = EncryptRequest.builder() - .keyId(keyId) - .plaintext(myBytes) - .build(); + .keyId(keyId) + .plaintext(myBytes) + .build(); EncryptResponse response = kmsClient.encrypt(encryptRequest); SdkBytes encryptedData = response.ciphertextBlob(); @@ -112,9 +108,9 @@ public static void putItemInTable(DynamoDbClient ddb, itemValues.put(awards, AttributeValue.builder().s(awardVal).build()); PutItemRequest request = PutItemRequest.builder() - .tableName(tableName) - .item(itemValues) - .build(); + .tableName(tableName) + .item(itemValues) + .build(); try { ddb.putItem(request); @@ -131,5 +127,3 @@ public static void putItemInTable(DynamoDbClient ddb, } } // snippet-end:[dynamodb.java2.put_item_enc.main] - - diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Query.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Query.java index 3510b7cbfc5..9b8cc4b5161 100755 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Query.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Query.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[Query.java demonstrates how to query an Amazon DynamoDB table.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb; @@ -20,28 +15,29 @@ // snippet-end:[dynamodb.java2.query.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * To query items from an Amazon DynamoDB table using the AWS SDK for Java V2, - * its better practice to use the - * Enhanced Client. See the EnhancedQueryRecords example. + * To query items from an Amazon DynamoDB table using the AWS SDK for Java V2, + * its better practice to use the + * Enhanced Client. See the EnhancedQueryRecords example. */ public class Query { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - tableName - The Amazon DynamoDB table to put the item in (for example, Music3). - partitionKeyName - The partition key name of the Amazon DynamoDB table (for example, Artist). - partitionKeyVal - The value of the partition key that should match (for example, Famous Band). - """; + Where: + tableName - The Amazon DynamoDB table to put the item in (for example, Music3). + partitionKeyName - The partition key name of the Amazon DynamoDB table (for example, Artist). + partitionKeyVal - The value of the partition key that should match (for example, Famous Band). + """; if (args.length != 3) { System.out.println(usage); @@ -60,15 +56,16 @@ public static void main(String[] args) { System.out.println(""); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); int count = queryTable(ddb, tableName, partitionKeyName, partitionKeyVal, partitionAlias); System.out.println("There were " + count + " record(s) returned"); ddb.close(); } - public static int queryTable(DynamoDbClient ddb, String tableName, String partitionKeyName, String partitionKeyVal, String partitionAlias) { + public static int queryTable(DynamoDbClient ddb, String tableName, String partitionKeyName, String partitionKeyVal, + String partitionAlias) { // Set up an alias for the partition key name in case it's a reserved word. HashMap attrNameAlias = new HashMap(); attrNameAlias.put(partitionAlias, partitionKeyName); @@ -76,15 +73,15 @@ public static int queryTable(DynamoDbClient ddb, String tableName, String partit // Set up mapping of the partition name with the value. HashMap attrValues = new HashMap<>(); attrValues.put(":" + partitionKeyName, AttributeValue.builder() - .s(partitionKeyVal) - .build()); + .s(partitionKeyVal) + .build()); QueryRequest queryReq = QueryRequest.builder() - .tableName(tableName) - .keyConditionExpression(partitionAlias + " = :" + partitionKeyName) - .expressionAttributeNames(attrNameAlias) - .expressionAttributeValues(attrValues) - .build(); + .tableName(tableName) + .keyConditionExpression(partitionAlias + " = :" + partitionKeyName) + .expressionAttributeNames(attrNameAlias) + .expressionAttributeValues(attrValues) + .build(); try { QueryResponse response = ddb.query(queryReq); diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/QueryItemsUsingIndex.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/QueryItemsUsingIndex.java index 0795cb4906f..87804b99dd2 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/QueryItemsUsingIndex.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/QueryItemsUsingIndex.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[GetItemIndex.java demonstrates how to retrieve an item from an Amazon DynamoDB table using a secondary index.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb; @@ -22,14 +16,17 @@ // snippet-end:[dynamodb.java2.query_items_sec_index.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * Create the Movies table by running the Scenario example and loading the Movie data from the JSON file. Next create a secondary - * index for the Movies table that uses only the year column. Name the index **year-index**. For more information, see: + * Create the Movies table by running the Scenario example and loading the Movie + * data from the JSON file. Next create a secondary + * index for the Movies table that uses only the year column. Name the index + * **year-index**. For more information, see: * * https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html */ @@ -38,8 +35,8 @@ public static void main(String[] args) { String tableName = "Movies"; Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); queryIndex(ddb, tableName); ddb.close(); @@ -53,17 +50,17 @@ public static void queryIndex(DynamoDbClient ddb, String tableName) { expressionAttributeValues.put(":yearValue", AttributeValue.builder().n("2013").build()); QueryRequest request = QueryRequest.builder() - .tableName(tableName) - .indexName("year-index") - .keyConditionExpression("#year = :yearValue") - .expressionAttributeNames(expressionAttributesNames) - .expressionAttributeValues(expressionAttributeValues) - .build(); + .tableName(tableName) + .indexName("year-index") + .keyConditionExpression("#year = :yearValue") + .expressionAttributeNames(expressionAttributesNames) + .expressionAttributeValues(expressionAttributeValues) + .build(); System.out.println("=== Movie Titles ==="); QueryResponse response = ddb.query(request); response.items() - .forEach(movie -> System.out.println(movie.get("title").s())); + .forEach(movie -> System.out.println(movie.get("title").s())); } catch (DynamoDbException e) { System.err.println(e.getMessage()); @@ -72,4 +69,3 @@ public static void queryIndex(DynamoDbClient ddb, String tableName) { } } // snippet-end:[dynamodb.java2.query_items_sec_index.main] - diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Scenario.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Scenario.java index 3fcb28513e8..5b9ee49bc11 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Scenario.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Scenario.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[Scenario.java demonstrates how to perform various Amazon DynamoDB operations.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb; @@ -50,16 +45,18 @@ // snippet-start:[dynamodb.java2.scenario.main] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * - * For more information, see the following documentation topic: + * For more information, see the following documentation topic: * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * This Java example performs these tasks: + * This Java example performs these tasks: * * 1. Creates the Amazon DynamoDB Movie table with partition and sort key. - * 2. Puts data into the Amazon DynamoDB table from a JSON document using the Enhanced client. + * 2. Puts data into the Amazon DynamoDB table from a JSON document using the + * Enhanced client. * 3. Gets data from the Movie table. * 4. Adds a new item. * 5. Updates an item. @@ -70,15 +67,16 @@ public class Scenario { public static final String DASHES = new String(new char[80]).replace("\0", "-"); + public static void main(String[] args) throws IOException { final String usage = """ - Usage: - + Usage: + - Where: - fileName - The path to the moviedata.json file that you can download from the Amazon DynamoDB Developer Guide. - """; + Where: + fileName - The path to the moviedata.json file that you can download from the Amazon DynamoDB Developer Guide. + """; if (args.length != 1) { System.out.println(usage); @@ -89,15 +87,16 @@ public static void main(String[] args) throws IOException { String fileName = args[0]; Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.println(DASHES); System.out.println("Welcome to the Amazon DynamoDB example scenario."); System.out.println(DASHES); System.out.println(DASHES); - System.out.println("1. Creating an Amazon DynamoDB table named Movies with a key named year and a sort key named title."); + System.out.println( + "1. Creating an Amazon DynamoDB table named Movies with a key named year and a sort key named title."); createTable(ddb, tableName); System.out.println(DASHES); @@ -108,7 +107,7 @@ public static void main(String[] args) throws IOException { System.out.println(DASHES); System.out.println("3. Getting data from the Movie table."); - getItem(ddb) ; + getItem(ddb); System.out.println(DASHES); System.out.println(DASHES); @@ -147,51 +146,51 @@ public static void createTable(DynamoDbClient ddb, String tableName) { // Define attributes. attributeDefinitions.add(AttributeDefinition.builder() - .attributeName("year") - .attributeType("N") - .build()); + .attributeName("year") + .attributeType("N") + .build()); attributeDefinitions.add(AttributeDefinition.builder() - .attributeName("title") - .attributeType("S") - .build()); + .attributeName("title") + .attributeType("S") + .build()); ArrayList tableKey = new ArrayList<>(); KeySchemaElement key = KeySchemaElement.builder() - .attributeName("year") - .keyType(KeyType.HASH) - .build(); + .attributeName("year") + .keyType(KeyType.HASH) + .build(); KeySchemaElement key2 = KeySchemaElement.builder() - .attributeName("title") - .keyType(KeyType.RANGE) - .build(); + .attributeName("title") + .keyType(KeyType.RANGE) + .build(); // Add KeySchemaElement objects to the list. tableKey.add(key); tableKey.add(key2); CreateTableRequest request = CreateTableRequest.builder() - .keySchema(tableKey) - .provisionedThroughput(ProvisionedThroughput.builder() - .readCapacityUnits(10L) - .writeCapacityUnits(10L) - .build()) - .attributeDefinitions(attributeDefinitions) - .tableName(tableName) - .build(); + .keySchema(tableKey) + .provisionedThroughput(ProvisionedThroughput.builder() + .readCapacityUnits(10L) + .writeCapacityUnits(10L) + .build()) + .attributeDefinitions(attributeDefinitions) + .tableName(tableName) + .build(); try { CreateTableResponse response = ddb.createTable(request); DescribeTableRequest tableRequest = DescribeTableRequest.builder() - .tableName(tableName) - .build(); + .tableName(tableName) + .build(); // Wait until the Amazon DynamoDB table is created. WaiterResponse waiterResponse = dbWaiter.waitUntilTableExists(tableRequest); waiterResponse.matched().response().ifPresent(System.out::println); String newTable = response.tableDescription().tableName(); - System.out.println("The " +newTable + " was successfully created."); + System.out.println("The " + newTable + " was successfully created."); } catch (DynamoDbException e) { System.err.println(e.getMessage()); @@ -205,73 +204,73 @@ public static void createTable(DynamoDbClient ddb, String tableName) { public static void queryTable(DynamoDbClient ddb) { try { DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() - .dynamoDbClient(ddb) - .build(); + .dynamoDbClient(ddb) + .build(); DynamoDbTable custTable = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)); QueryConditional queryConditional = QueryConditional - .keyEqualTo(Key.builder() - .partitionValue(2013) - .build()); + .keyEqualTo(Key.builder() + .partitionValue(2013) + .build()); // Get items in the table and write out the ID value. Iterator results = custTable.query(queryConditional).items().iterator(); - String result=""; + String result = ""; while (results.hasNext()) { Movies rec = results.next(); - System.out.println("The title of the movie is "+rec.getTitle()); - System.out.println("The movie information is "+rec.getInfo()); + System.out.println("The title of the movie is " + rec.getTitle()); + System.out.println("The movie information is " + rec.getInfo()); } } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); - } } - // snippet-end:[dynamodb.java2.scenario.query.main] - - // snippet-start:[dynamodb.java2.scenario.scan.main] - // Scan the table. - public static void scanMovies(DynamoDbClient ddb, String tableName) { - System.out.println("******* Scanning all movies.\n"); - try{ - DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() - .dynamoDbClient(ddb) - .build(); - - DynamoDbTable custTable = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)); - Iterator results = custTable.scan().items().iterator(); - while (results.hasNext()) { - Movies rec = results.next(); - System.out.println("The movie title is "+rec.getTitle()); - System.out.println("The movie year is " +rec.getYear()); - } + } + // snippet-end:[dynamodb.java2.scenario.query.main] - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); + // snippet-start:[dynamodb.java2.scenario.scan.main] + // Scan the table. + public static void scanMovies(DynamoDbClient ddb, String tableName) { + System.out.println("******* Scanning all movies.\n"); + try { + DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() + .dynamoDbClient(ddb) + .build(); + + DynamoDbTable custTable = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)); + Iterator results = custTable.scan().items().iterator(); + while (results.hasNext()) { + Movies rec = results.next(); + System.out.println("The movie title is " + rec.getTitle()); + System.out.println("The movie year is " + rec.getYear()); } + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); } + } // snippet-end:[dynamodb.java2.scenario.scan.main] // snippet-start:[dynamodb.java2.scenario.populate_table.main] // Load data into the table. public static void loadData(DynamoDbClient ddb, String tableName, String fileName) throws IOException { DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() - .dynamoDbClient(ddb) - .build(); + .dynamoDbClient(ddb) + .build(); DynamoDbTable mappedTable = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)); JsonParser parser = new JsonFactory().createParser(new File(fileName)); com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); Iterator iter = rootNode.iterator(); ObjectNode currentNode; - int t = 0 ; + int t = 0; while (iter.hasNext()) { // Only add 200 Movies to the table. if (t == 200) - break ; + break; currentNode = (ObjectNode) iter.next(); int year = currentNode.path("year").asInt(); @@ -291,22 +290,23 @@ public static void loadData(DynamoDbClient ddb, String tableName, String fileNam // snippet-end:[dynamodb.java2.scenario.populate_table.main] // Update the record to include show only directors. - public static void updateTableItem(DynamoDbClient ddb, String tableName){ - HashMap itemKey = new HashMap<>(); + public static void updateTableItem(DynamoDbClient ddb, String tableName) { + HashMap itemKey = new HashMap<>(); itemKey.put("year", AttributeValue.builder().n("1933").build()); itemKey.put("title", AttributeValue.builder().s("King Kong").build()); - HashMap updatedValues = new HashMap<>(); + HashMap updatedValues = new HashMap<>(); updatedValues.put("info", AttributeValueUpdate.builder() - .value(AttributeValue.builder().s("{\"directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack\"]").build()) - .action(AttributeAction.PUT) - .build()); + .value(AttributeValue.builder().s("{\"directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack\"]") + .build()) + .action(AttributeAction.PUT) + .build()); UpdateItemRequest request = UpdateItemRequest.builder() - .tableName(tableName) - .key(itemKey) - .attributeUpdates(updatedValues) - .build(); + .tableName(tableName) + .key(itemKey) + .attributeUpdates(updatedValues) + .build(); try { ddb.updateItem(request); @@ -323,8 +323,8 @@ public static void updateTableItem(DynamoDbClient ddb, String tableName){ public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) { DeleteTableRequest request = DeleteTableRequest.builder() - .tableName(tableName) - .build(); + .tableName(tableName) + .build(); try { ddb.deleteTable(request); @@ -333,14 +333,14 @@ public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) { System.err.println(e.getMessage()); System.exit(1); } - System.out.println(tableName +" was successfully deleted!"); + System.out.println(tableName + " was successfully deleted!"); } public static void putRecord(DynamoDbClient ddb) { try { DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() - .dynamoDbClient(ddb) - .build(); + .dynamoDbClient(ddb) + .build(); DynamoDbTable table = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)); @@ -361,22 +361,22 @@ public static void putRecord(DynamoDbClient ddb) { // snippet-start:[dynamodb.java2.scenario.get_item.main] public static void getItem(DynamoDbClient ddb) { - HashMap keyToGet = new HashMap<>(); + HashMap keyToGet = new HashMap<>(); keyToGet.put("year", AttributeValue.builder() - .n("1933") - .build()); + .n("1933") + .build()); keyToGet.put("title", AttributeValue.builder() - .s("King Kong") - .build()); + .s("King Kong") + .build()); GetItemRequest request = GetItemRequest.builder() - .key(keyToGet) - .tableName("Movies") - .build(); + .key(keyToGet) + .tableName("Movies") + .build(); try { - Map returnedItem = ddb.getItem(request).item(); + Map returnedItem = ddb.getItem(request).item(); if (returnedItem != null) { Set keys = returnedItem.keySet(); @@ -390,11 +390,10 @@ public static void getItem(DynamoDbClient ddb) { } } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); + System.err.println(e.getMessage()); + System.exit(1); } } // snippet-end:[dynamodb.java2.scenario.get_item.main] } // snippet-end:[dynamodb.java2.scenario.main] - diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/ScenarioPartiQ.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/ScenarioPartiQ.java index bb4bc60bdf7..a28a9894cee 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/ScenarioPartiQ.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/ScenarioPartiQ.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[ScenarioPartiQ.java demonstrates how to perform various Amazon DynamoDB operations using PartiQL.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb; @@ -40,13 +34,14 @@ // snippet-end:[dynamodb.java2.scenario.partiql.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * This Java example performs the following tasks: + * This Java example performs the following tasks: * * 1. Creates the Amazon DynamoDB movie table with a partition and sort key. * 2. Puts data into the Amazon DynamoDB table from a JSON document. @@ -57,54 +52,56 @@ * 7. Queries all items where the year is 2013 using the Enhanced Client. * 8. Deletes the table. * - * To see another code example with more options using PartiQL and Batch commands, see the ScenarioPartiQBatch code example. + * To see another code example with more options using PartiQL and Batch + * commands, see the ScenarioPartiQBatch code example. */ // snippet-start:[dynamodb.java2.scenario.partiql.main] public class ScenarioPartiQ { - public static void main(String [] args) throws IOException { + public static void main(String[] args) throws IOException { final String usage = """ - Usage: - + Usage: + - Where: - fileName - The path to the moviedata.json file that you can download from the Amazon DynamoDB Developer Guide. - """; + Where: + fileName - The path to the moviedata.json file that you can download from the Amazon DynamoDB Developer Guide. + """; - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } + if (args.length != 1) { + System.out.println(usage); + System.exit(1); + } - String fileName = args[0]; - String tableName = "MoviesPartiQ"; - Region region = Region.US_EAST_1; - DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + String fileName = args[0]; + String tableName = "MoviesPartiQ"; + Region region = Region.US_EAST_1; + DynamoDbClient ddb = DynamoDbClient.builder() + .region(region) + .build(); - System.out.println("******* Creating an Amazon DynamoDB table named MoviesPartiQ with a key named year and a sort key named title."); - createTable(ddb, tableName); + System.out.println( + "******* Creating an Amazon DynamoDB table named MoviesPartiQ with a key named year and a sort key named title."); + createTable(ddb, tableName); - System.out.println("******* Loading data into the MoviesPartiQ table."); - loadData(ddb, fileName); + System.out.println("******* Loading data into the MoviesPartiQ table."); + loadData(ddb, fileName); - System.out.println("******* Getting data from the MoviesPartiQ table."); - getItem(ddb); + System.out.println("******* Getting data from the MoviesPartiQ table."); + getItem(ddb); - System.out.println("******* Putting a record into the MoviesPartiQ table."); - putRecord(ddb); + System.out.println("******* Putting a record into the MoviesPartiQ table."); + putRecord(ddb); - System.out.println("******* Updating a record."); - updateTableItem(ddb); + System.out.println("******* Updating a record."); + updateTableItem(ddb); - System.out.println("******* Querying the movies released in 2013."); - queryTable(ddb); + System.out.println("******* Querying the movies released in 2013."); + queryTable(ddb); - System.out.println("******* Deleting the Amazon DynamoDB table."); - deleteDynamoDBTable(ddb, tableName); - ddb.close(); + System.out.println("******* Deleting the Amazon DynamoDB table."); + deleteDynamoDBTable(ddb, tableName); + ddb.close(); } public static void createTable(DynamoDbClient ddb, String tableName) { @@ -113,51 +110,51 @@ public static void createTable(DynamoDbClient ddb, String tableName) { // Define attributes. attributeDefinitions.add(AttributeDefinition.builder() - .attributeName("year") - .attributeType("N") - .build()); + .attributeName("year") + .attributeType("N") + .build()); attributeDefinitions.add(AttributeDefinition.builder() - .attributeName("title") - .attributeType("S") - .build()); + .attributeName("title") + .attributeType("S") + .build()); ArrayList tableKey = new ArrayList<>(); KeySchemaElement key = KeySchemaElement.builder() - .attributeName("year") - .keyType(KeyType.HASH) - .build(); + .attributeName("year") + .keyType(KeyType.HASH) + .build(); KeySchemaElement key2 = KeySchemaElement.builder() - .attributeName("title") - .keyType(KeyType.RANGE) // Sort - .build(); + .attributeName("title") + .keyType(KeyType.RANGE) // Sort + .build(); // Add KeySchemaElement objects to the list. tableKey.add(key); tableKey.add(key2); CreateTableRequest request = CreateTableRequest.builder() - .keySchema(tableKey) - .provisionedThroughput(ProvisionedThroughput.builder() - .readCapacityUnits(new Long(10)) - .writeCapacityUnits(new Long(10)) - .build()) - .attributeDefinitions(attributeDefinitions) - .tableName(tableName) - .build(); + .keySchema(tableKey) + .provisionedThroughput(ProvisionedThroughput.builder() + .readCapacityUnits(new Long(10)) + .writeCapacityUnits(new Long(10)) + .build()) + .attributeDefinitions(attributeDefinitions) + .tableName(tableName) + .build(); try { CreateTableResponse response = ddb.createTable(request); DescribeTableRequest tableRequest = DescribeTableRequest.builder() - .tableName(tableName) - .build(); + .tableName(tableName) + .build(); // Wait until the Amazon DynamoDB table is created. WaiterResponse waiterResponse = dbWaiter.waitUntilTableExists(tableRequest); waiterResponse.matched().response().ifPresent(System.out::println); String newTable = response.tableDescription().tableName(); - System.out.println("The " +newTable + " was successfully created."); + System.out.println("The " + newTable + " was successfully created."); } catch (DynamoDbException e) { System.err.println(e.getMessage()); @@ -173,13 +170,13 @@ public static void loadData(DynamoDbClient ddb, String fileName) throws IOExcept com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); Iterator iter = rootNode.iterator(); ObjectNode currentNode; - int t = 0 ; + int t = 0; List parameters = new ArrayList<>(); while (iter.hasNext()) { // Add 200 movies to the table. if (t == 200) - break ; + break; currentNode = (ObjectNode) iter.next(); int year = currentNode.path("year").asInt(); @@ -187,16 +184,16 @@ public static void loadData(DynamoDbClient ddb, String fileName) throws IOExcept String info = currentNode.path("info").toString(); AttributeValue att1 = AttributeValue.builder() - .n(String.valueOf(year)) - .build(); + .n(String.valueOf(year)) + .build(); AttributeValue att2 = AttributeValue.builder() - .s(title) - .build(); + .s(title) + .build(); AttributeValue att3 = AttributeValue.builder() - .s(info) - .build(); + .s(info) + .build(); parameters.add(att1); parameters.add(att2); @@ -204,7 +201,7 @@ public static void loadData(DynamoDbClient ddb, String fileName) throws IOExcept // Insert the movie into the Amazon DynamoDB table. executeStatementRequest(ddb, sqlStatement, parameters); - System.out.println("Added Movie " +title); + System.out.println("Added Movie " + title); parameters.remove(att1); parameters.remove(att2); @@ -218,19 +215,19 @@ public static void getItem(DynamoDbClient ddb) { String sqlStatement = "SELECT * FROM MoviesPartiQ where year=? and title=?"; List parameters = new ArrayList<>(); AttributeValue att1 = AttributeValue.builder() - .n("2012") - .build(); + .n("2012") + .build(); AttributeValue att2 = AttributeValue.builder() - .s("The Perks of Being a Wallflower") - .build(); + .s("The Perks of Being a Wallflower") + .build(); parameters.add(att1); parameters.add(att2); try { ExecuteStatementResponse response = executeStatementRequest(ddb, sqlStatement, parameters); - System.out.println("ExecuteStatement successful: "+ response.toString()); + System.out.println("ExecuteStatement successful: " + response.toString()); } catch (DynamoDbException e) { System.err.println(e.getMessage()); @@ -245,16 +242,16 @@ public static void putRecord(DynamoDbClient ddb) { List parameters = new ArrayList<>(); AttributeValue att1 = AttributeValue.builder() - .n(String.valueOf("2020")) - .build(); + .n(String.valueOf("2020")) + .build(); AttributeValue att2 = AttributeValue.builder() - .s("My Movie") - .build(); + .s("My Movie") + .build(); AttributeValue att3 = AttributeValue.builder() - .s("No Information") - .build(); + .s("No Information") + .build(); parameters.add(att1); parameters.add(att2); @@ -269,17 +266,17 @@ public static void putRecord(DynamoDbClient ddb) { } } - public static void updateTableItem(DynamoDbClient ddb){ + public static void updateTableItem(DynamoDbClient ddb) { String sqlStatement = "UPDATE MoviesPartiQ SET info = 'directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack' where year=? and title=?"; List parameters = new ArrayList<>(); AttributeValue att1 = AttributeValue.builder() - .n(String.valueOf("2013")) - .build(); + .n(String.valueOf("2013")) + .build(); AttributeValue att2 = AttributeValue.builder() - .s("The East") - .build(); + .s("The East") + .build(); parameters.add(att1); parameters.add(att2); @@ -301,13 +298,13 @@ public static void queryTable(DynamoDbClient ddb) { List parameters = new ArrayList<>(); AttributeValue att1 = AttributeValue.builder() - .n(String.valueOf("2013")) - .build(); + .n(String.valueOf("2013")) + .build(); parameters.add(att1); // Get items in the table and write out the ID value. ExecuteStatementResponse response = executeStatementRequest(ddb, sqlStatement, parameters); - System.out.println("ExecuteStatement successful: "+ response.toString()); + System.out.println("ExecuteStatement successful: " + response.toString()); } catch (DynamoDbException e) { System.err.println(e.getMessage()); @@ -318,8 +315,8 @@ public static void queryTable(DynamoDbClient ddb) { public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) { DeleteTableRequest request = DeleteTableRequest.builder() - .tableName(tableName) - .build(); + .tableName(tableName) + .build(); try { ddb.deleteTable(request); @@ -328,20 +325,21 @@ public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) { System.err.println(e.getMessage()); System.exit(1); } - System.out.println(tableName +" was successfully deleted!"); + System.out.println(tableName + " was successfully deleted!"); } - private static ExecuteStatementResponse executeStatementRequest(DynamoDbClient ddb, String statement, List parameters ) { + private static ExecuteStatementResponse executeStatementRequest(DynamoDbClient ddb, String statement, + List parameters) { ExecuteStatementRequest request = ExecuteStatementRequest.builder() - .statement(statement) - .parameters(parameters) - .build(); + .statement(statement) + .parameters(parameters) + .build(); return ddb.executeStatement(request); } private static void processResults(ExecuteStatementResponse executeStatementResult) { - System.out.println("ExecuteStatement successful: "+ executeStatementResult.toString()); + System.out.println("ExecuteStatement successful: " + executeStatementResult.toString()); } } // snippet-end:[dynamodb.java2.scenario.partiql.main] \ No newline at end of file diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/ScenarioPartiQLBatch.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/ScenarioPartiQLBatch.java index a2208855a6f..d7377957a5a 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/ScenarioPartiQLBatch.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/ScenarioPartiQLBatch.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[ScenarioPartiQ.java demonstrates how to perform various Amazon DynamoDB batch operations using PartiQL.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb; @@ -36,13 +30,14 @@ // snippet-end:[dynamodb.java2.scenario.partiql.batch.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * This Java example performs the following tasks: + * This Java example performs the following tasks: * * 1. Creates the Amazon DynamoDB movie table with a partition and sort key. * 2. Puts new records into the table using a BatchExecuteStatement @@ -50,362 +45,367 @@ * 4. Deletes items by using a BatchExecuteStatement. * 5. Deletes the table. * - * To see another code example with more options using PartiQL, see the ScenarioPartiQ code example. + * To see another code example with more options using PartiQL, see the + * ScenarioPartiQ code example. */ // snippet-start:[dynamodb.java2.scenario.partiql.batch.main] public class ScenarioPartiQLBatch { - public static void main(String [] args) throws IOException { - String tableName = "MoviesPartiQBatch"; - Region region = Region.US_EAST_1; - DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); - - System.out.println("******* Creating an Amazon DynamoDB table named "+tableName +" with a key named year and a sort key named title."); - createTable(ddb, tableName); - - System.out.println("******* Adding multiple records into the "+ tableName +" table using a batch command."); - putRecordBatch(ddb); - - System.out.println("******* Updating multiple records using a batch command."); - updateTableItemBatch(ddb); - - System.out.println("******* Deleting multiple records using a batch command."); - deleteItemBatch(ddb); - - System.out.println("******* Deleting the Amazon DynamoDB table."); - deleteDynamoDBTable(ddb, tableName); - ddb.close(); - } - - public static void createTable(DynamoDbClient ddb, String tableName) { - DynamoDbWaiter dbWaiter = ddb.waiter(); - ArrayList attributeDefinitions = new ArrayList<>(); - - // Define attributes. - attributeDefinitions.add(AttributeDefinition.builder() - .attributeName("year") - .attributeType("N") - .build()); - - attributeDefinitions.add(AttributeDefinition.builder() - .attributeName("title") - .attributeType("S") - .build()); - - ArrayList tableKey = new ArrayList<>(); - KeySchemaElement key = KeySchemaElement.builder() - .attributeName("year") - .keyType(KeyType.HASH) - .build(); - - KeySchemaElement key2 = KeySchemaElement.builder() - .attributeName("title") - .keyType(KeyType.RANGE) // Sort - .build(); - - // Add KeySchemaElement objects to the list. - tableKey.add(key); - tableKey.add(key2); - - CreateTableRequest request = CreateTableRequest.builder() - .keySchema(tableKey) - .provisionedThroughput(ProvisionedThroughput.builder() - .readCapacityUnits(new Long(10)) - .writeCapacityUnits(new Long(10)) - .build()) - .attributeDefinitions(attributeDefinitions) - .tableName(tableName) - .build(); - - try { - CreateTableResponse response = ddb.createTable(request); - DescribeTableRequest tableRequest = DescribeTableRequest.builder() - .tableName(tableName) - .build(); - - // Wait until the Amazon DynamoDB table is created. - WaiterResponse waiterResponse = dbWaiter.waitUntilTableExists(tableRequest); - waiterResponse.matched().response().ifPresent(System.out::println); - String newTable = response.tableDescription().tableName(); - System.out.println("The " +newTable + " was successfully created."); - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); + public static void main(String[] args) throws IOException { + String tableName = "MoviesPartiQBatch"; + Region region = Region.US_EAST_1; + DynamoDbClient ddb = DynamoDbClient.builder() + .region(region) + .build(); + + System.out.println("******* Creating an Amazon DynamoDB table named " + tableName + + " with a key named year and a sort key named title."); + createTable(ddb, tableName); + + System.out.println("******* Adding multiple records into the " + tableName + + " table using a batch command."); + putRecordBatch(ddb); + + System.out.println("******* Updating multiple records using a batch command."); + updateTableItemBatch(ddb); + + System.out.println("******* Deleting multiple records using a batch command."); + deleteItemBatch(ddb); + + System.out.println("******* Deleting the Amazon DynamoDB table."); + deleteDynamoDBTable(ddb, tableName); + ddb.close(); } - } - - public static void putRecordBatch(DynamoDbClient ddb) { - String sqlStatement = "INSERT INTO MoviesPartiQBatch VALUE {'year':?, 'title' : ?, 'info' : ?}"; - try { - // Create three movies to add to the Amazon DynamoDB table. - // Set data for Movie 1. - List parameters = new ArrayList<>(); - - AttributeValue att1 = AttributeValue.builder() - .n(String.valueOf("2022")) - .build(); - - AttributeValue att2 = AttributeValue.builder() - .s("My Movie 1") - .build(); - - AttributeValue att3 = AttributeValue.builder() - .s("No Information") - .build(); - - parameters.add(att1); - parameters.add(att2); - parameters.add(att3); - - BatchStatementRequest statementRequestMovie1 = BatchStatementRequest.builder() - .statement(sqlStatement) - .parameters(parameters) - .build(); - - // Set data for Movie 2. - List parametersMovie2 = new ArrayList<>(); - AttributeValue attMovie2 = AttributeValue.builder() - .n(String.valueOf("2022")) - .build(); - - AttributeValue attMovie2A = AttributeValue.builder() - .s("My Movie 2") - .build(); - - AttributeValue attMovie2B = AttributeValue.builder() - .s("No Information") - .build(); - - parametersMovie2.add(attMovie2); - parametersMovie2.add(attMovie2A); - parametersMovie2.add(attMovie2B); - - BatchStatementRequest statementRequestMovie2 = BatchStatementRequest.builder() - .statement(sqlStatement) - .parameters(parametersMovie2) - .build(); - - // Set data for Movie 3. - List parametersMovie3 = new ArrayList<>(); - AttributeValue attMovie3 = AttributeValue.builder() - .n(String.valueOf("2022")) - .build(); - - AttributeValue attMovie3A = AttributeValue.builder() - .s("My Movie 3") - .build(); - - AttributeValue attMovie3B = AttributeValue.builder() - .s("No Information") - .build(); - - parametersMovie3.add(attMovie3); - parametersMovie3.add(attMovie3A); - parametersMovie3.add(attMovie3B); - - BatchStatementRequest statementRequestMovie3 = BatchStatementRequest.builder() - .statement(sqlStatement) - .parameters(parametersMovie3) - .build(); - - // Add all three movies to the list. - List myBatchStatementList = new ArrayList<>(); - myBatchStatementList.add(statementRequestMovie1); - myBatchStatementList.add(statementRequestMovie2); - myBatchStatementList.add(statementRequestMovie3); - - BatchExecuteStatementRequest batchRequest = BatchExecuteStatementRequest.builder() - .statements(myBatchStatementList) - .build(); - - BatchExecuteStatementResponse response = ddb.batchExecuteStatement(batchRequest); - System.out.println("ExecuteStatement successful: "+ response.toString()); - System.out.println("Added new movies using a batch command."); - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); + + public static void createTable(DynamoDbClient ddb, String tableName) { + DynamoDbWaiter dbWaiter = ddb.waiter(); + ArrayList attributeDefinitions = new ArrayList<>(); + + // Define attributes. + attributeDefinitions.add(AttributeDefinition.builder() + .attributeName("year") + .attributeType("N") + .build()); + + attributeDefinitions.add(AttributeDefinition.builder() + .attributeName("title") + .attributeType("S") + .build()); + + ArrayList tableKey = new ArrayList<>(); + KeySchemaElement key = KeySchemaElement.builder() + .attributeName("year") + .keyType(KeyType.HASH) + .build(); + + KeySchemaElement key2 = KeySchemaElement.builder() + .attributeName("title") + .keyType(KeyType.RANGE) // Sort + .build(); + + // Add KeySchemaElement objects to the list. + tableKey.add(key); + tableKey.add(key2); + + CreateTableRequest request = CreateTableRequest.builder() + .keySchema(tableKey) + .provisionedThroughput(ProvisionedThroughput.builder() + .readCapacityUnits(new Long(10)) + .writeCapacityUnits(new Long(10)) + .build()) + .attributeDefinitions(attributeDefinitions) + .tableName(tableName) + .build(); + + try { + CreateTableResponse response = ddb.createTable(request); + DescribeTableRequest tableRequest = DescribeTableRequest.builder() + .tableName(tableName) + .build(); + + // Wait until the Amazon DynamoDB table is created. + WaiterResponse waiterResponse = dbWaiter + .waitUntilTableExists(tableRequest); + waiterResponse.matched().response().ifPresent(System.out::println); + String newTable = response.tableDescription().tableName(); + System.out.println("The " + newTable + " was successfully created."); + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } } - } - - public static void updateTableItemBatch(DynamoDbClient ddb){ - String sqlStatement = "UPDATE MoviesPartiQBatch SET info = 'directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack' where year=? and title=?"; - List parametersRec1 = new ArrayList<>(); - - // Update three records. - AttributeValue att1 = AttributeValue.builder() - .n(String.valueOf("2022")) - .build(); - - AttributeValue att2 = AttributeValue.builder() - .s("My Movie 1") - .build(); - - parametersRec1.add(att1); - parametersRec1.add(att2); - - BatchStatementRequest statementRequestRec1 = BatchStatementRequest.builder() - .statement(sqlStatement) - .parameters(parametersRec1) - .build(); - - // Update record 2. - List parametersRec2 = new ArrayList<>(); - AttributeValue attRec2 = AttributeValue.builder() - .n(String.valueOf("2022")) - .build(); - - AttributeValue attRec2a = AttributeValue.builder() - .s("My Movie 2") - .build(); - - parametersRec2.add(attRec2); - parametersRec2.add(attRec2a); - BatchStatementRequest statementRequestRec2 = BatchStatementRequest.builder() - .statement(sqlStatement) - .parameters(parametersRec2) - .build(); - - // Update record 3. - List parametersRec3 = new ArrayList<>(); - AttributeValue attRec3 = AttributeValue.builder() - .n(String.valueOf("2022")) - .build(); - - AttributeValue attRec3a = AttributeValue.builder() - .s("My Movie 3") - .build(); - - parametersRec3.add(attRec3); - parametersRec3.add(attRec3a); - BatchStatementRequest statementRequestRec3 = BatchStatementRequest.builder() - .statement(sqlStatement) - .parameters(parametersRec3) - .build(); - - // Add all three movies to the list. - List myBatchStatementList = new ArrayList<>(); - myBatchStatementList.add(statementRequestRec1); - myBatchStatementList.add(statementRequestRec2); - myBatchStatementList.add(statementRequestRec3); - - BatchExecuteStatementRequest batchRequest = BatchExecuteStatementRequest.builder() - .statements(myBatchStatementList) - .build(); - - try { - BatchExecuteStatementResponse response = ddb.batchExecuteStatement(batchRequest); - System.out.println("ExecuteStatement successful: "+ response.toString()); - System.out.println("Updated three movies using a batch command."); - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); + + public static void putRecordBatch(DynamoDbClient ddb) { + String sqlStatement = "INSERT INTO MoviesPartiQBatch VALUE {'year':?, 'title' : ?, 'info' : ?}"; + try { + // Create three movies to add to the Amazon DynamoDB table. + // Set data for Movie 1. + List parameters = new ArrayList<>(); + + AttributeValue att1 = AttributeValue.builder() + .n(String.valueOf("2022")) + .build(); + + AttributeValue att2 = AttributeValue.builder() + .s("My Movie 1") + .build(); + + AttributeValue att3 = AttributeValue.builder() + .s("No Information") + .build(); + + parameters.add(att1); + parameters.add(att2); + parameters.add(att3); + + BatchStatementRequest statementRequestMovie1 = BatchStatementRequest.builder() + .statement(sqlStatement) + .parameters(parameters) + .build(); + + // Set data for Movie 2. + List parametersMovie2 = new ArrayList<>(); + AttributeValue attMovie2 = AttributeValue.builder() + .n(String.valueOf("2022")) + .build(); + + AttributeValue attMovie2A = AttributeValue.builder() + .s("My Movie 2") + .build(); + + AttributeValue attMovie2B = AttributeValue.builder() + .s("No Information") + .build(); + + parametersMovie2.add(attMovie2); + parametersMovie2.add(attMovie2A); + parametersMovie2.add(attMovie2B); + + BatchStatementRequest statementRequestMovie2 = BatchStatementRequest.builder() + .statement(sqlStatement) + .parameters(parametersMovie2) + .build(); + + // Set data for Movie 3. + List parametersMovie3 = new ArrayList<>(); + AttributeValue attMovie3 = AttributeValue.builder() + .n(String.valueOf("2022")) + .build(); + + AttributeValue attMovie3A = AttributeValue.builder() + .s("My Movie 3") + .build(); + + AttributeValue attMovie3B = AttributeValue.builder() + .s("No Information") + .build(); + + parametersMovie3.add(attMovie3); + parametersMovie3.add(attMovie3A); + parametersMovie3.add(attMovie3B); + + BatchStatementRequest statementRequestMovie3 = BatchStatementRequest.builder() + .statement(sqlStatement) + .parameters(parametersMovie3) + .build(); + + // Add all three movies to the list. + List myBatchStatementList = new ArrayList<>(); + myBatchStatementList.add(statementRequestMovie1); + myBatchStatementList.add(statementRequestMovie2); + myBatchStatementList.add(statementRequestMovie3); + + BatchExecuteStatementRequest batchRequest = BatchExecuteStatementRequest.builder() + .statements(myBatchStatementList) + .build(); + + BatchExecuteStatementResponse response = ddb.batchExecuteStatement(batchRequest); + System.out.println("ExecuteStatement successful: " + response.toString()); + System.out.println("Added new movies using a batch command."); + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } } - System.out.println("Item was updated!"); - } - - public static void deleteItemBatch(DynamoDbClient ddb){ - String sqlStatement = "DELETE FROM MoviesPartiQBatch WHERE year = ? and title=?"; - List parametersRec1 = new ArrayList<>(); - - // Specify three records to delete. - AttributeValue att1 = AttributeValue.builder() - .n(String.valueOf("2022")) - .build(); - - AttributeValue att2 = AttributeValue.builder() - .s("My Movie 1") - .build(); - - parametersRec1.add(att1); - parametersRec1.add(att2); - - BatchStatementRequest statementRequestRec1 = BatchStatementRequest.builder() - .statement(sqlStatement) - .parameters(parametersRec1) - .build(); - - // Specify record 2. - List parametersRec2 = new ArrayList<>(); - AttributeValue attRec2 = AttributeValue.builder() - .n(String.valueOf("2022")) - .build(); - - AttributeValue attRec2a = AttributeValue.builder() - .s("My Movie 2") - .build(); - - parametersRec2.add(attRec2); - parametersRec2.add(attRec2a); - BatchStatementRequest statementRequestRec2 = BatchStatementRequest.builder() - .statement(sqlStatement) - .parameters(parametersRec2) - .build(); - - // Specify record 3. - List parametersRec3 = new ArrayList<>(); - AttributeValue attRec3 = AttributeValue.builder() - .n(String.valueOf("2022")) - .build(); - - AttributeValue attRec3a = AttributeValue.builder() - .s("My Movie 3") - .build(); - - parametersRec3.add(attRec3); - parametersRec3.add(attRec3a); - - BatchStatementRequest statementRequestRec3 = BatchStatementRequest.builder() - .statement(sqlStatement) - .parameters(parametersRec3) - .build(); - - // Add all three movies to the list. - List myBatchStatementList = new ArrayList<>(); - myBatchStatementList.add(statementRequestRec1); - myBatchStatementList.add(statementRequestRec2); - myBatchStatementList.add(statementRequestRec3); - - BatchExecuteStatementRequest batchRequest = BatchExecuteStatementRequest.builder() - .statements(myBatchStatementList) - .build(); - - try { - ddb.batchExecuteStatement(batchRequest); - System.out.println("Deleted three movies using a batch command."); - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); + + public static void updateTableItemBatch(DynamoDbClient ddb) { + String sqlStatement = "UPDATE MoviesPartiQBatch SET info = 'directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack' where year=? and title=?"; + List parametersRec1 = new ArrayList<>(); + + // Update three records. + AttributeValue att1 = AttributeValue.builder() + .n(String.valueOf("2022")) + .build(); + + AttributeValue att2 = AttributeValue.builder() + .s("My Movie 1") + .build(); + + parametersRec1.add(att1); + parametersRec1.add(att2); + + BatchStatementRequest statementRequestRec1 = BatchStatementRequest.builder() + .statement(sqlStatement) + .parameters(parametersRec1) + .build(); + + // Update record 2. + List parametersRec2 = new ArrayList<>(); + AttributeValue attRec2 = AttributeValue.builder() + .n(String.valueOf("2022")) + .build(); + + AttributeValue attRec2a = AttributeValue.builder() + .s("My Movie 2") + .build(); + + parametersRec2.add(attRec2); + parametersRec2.add(attRec2a); + BatchStatementRequest statementRequestRec2 = BatchStatementRequest.builder() + .statement(sqlStatement) + .parameters(parametersRec2) + .build(); + + // Update record 3. + List parametersRec3 = new ArrayList<>(); + AttributeValue attRec3 = AttributeValue.builder() + .n(String.valueOf("2022")) + .build(); + + AttributeValue attRec3a = AttributeValue.builder() + .s("My Movie 3") + .build(); + + parametersRec3.add(attRec3); + parametersRec3.add(attRec3a); + BatchStatementRequest statementRequestRec3 = BatchStatementRequest.builder() + .statement(sqlStatement) + .parameters(parametersRec3) + .build(); + + // Add all three movies to the list. + List myBatchStatementList = new ArrayList<>(); + myBatchStatementList.add(statementRequestRec1); + myBatchStatementList.add(statementRequestRec2); + myBatchStatementList.add(statementRequestRec3); + + BatchExecuteStatementRequest batchRequest = BatchExecuteStatementRequest.builder() + .statements(myBatchStatementList) + .build(); + + try { + BatchExecuteStatementResponse response = ddb.batchExecuteStatement(batchRequest); + System.out.println("ExecuteStatement successful: " + response.toString()); + System.out.println("Updated three movies using a batch command."); + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + System.out.println("Item was updated!"); } - } - public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) { - DeleteTableRequest request = DeleteTableRequest.builder() - .tableName(tableName) - .build(); + public static void deleteItemBatch(DynamoDbClient ddb) { + String sqlStatement = "DELETE FROM MoviesPartiQBatch WHERE year = ? and title=?"; + List parametersRec1 = new ArrayList<>(); + + // Specify three records to delete. + AttributeValue att1 = AttributeValue.builder() + .n(String.valueOf("2022")) + .build(); + + AttributeValue att2 = AttributeValue.builder() + .s("My Movie 1") + .build(); + + parametersRec1.add(att1); + parametersRec1.add(att2); + + BatchStatementRequest statementRequestRec1 = BatchStatementRequest.builder() + .statement(sqlStatement) + .parameters(parametersRec1) + .build(); + + // Specify record 2. + List parametersRec2 = new ArrayList<>(); + AttributeValue attRec2 = AttributeValue.builder() + .n(String.valueOf("2022")) + .build(); + + AttributeValue attRec2a = AttributeValue.builder() + .s("My Movie 2") + .build(); + + parametersRec2.add(attRec2); + parametersRec2.add(attRec2a); + BatchStatementRequest statementRequestRec2 = BatchStatementRequest.builder() + .statement(sqlStatement) + .parameters(parametersRec2) + .build(); + + // Specify record 3. + List parametersRec3 = new ArrayList<>(); + AttributeValue attRec3 = AttributeValue.builder() + .n(String.valueOf("2022")) + .build(); + + AttributeValue attRec3a = AttributeValue.builder() + .s("My Movie 3") + .build(); + + parametersRec3.add(attRec3); + parametersRec3.add(attRec3a); + + BatchStatementRequest statementRequestRec3 = BatchStatementRequest.builder() + .statement(sqlStatement) + .parameters(parametersRec3) + .build(); + + // Add all three movies to the list. + List myBatchStatementList = new ArrayList<>(); + myBatchStatementList.add(statementRequestRec1); + myBatchStatementList.add(statementRequestRec2); + myBatchStatementList.add(statementRequestRec3); + + BatchExecuteStatementRequest batchRequest = BatchExecuteStatementRequest.builder() + .statements(myBatchStatementList) + .build(); + + try { + ddb.batchExecuteStatement(batchRequest); + System.out.println("Deleted three movies using a batch command."); + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + + public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) { + DeleteTableRequest request = DeleteTableRequest.builder() + .tableName(tableName) + .build(); - try { - ddb.deleteTable(request); + try { + ddb.deleteTable(request); - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + System.out.println(tableName + " was successfully deleted!"); } - System.out.println(tableName +" was successfully deleted!"); - } - private static ExecuteStatementResponse executeStatementRequest(DynamoDbClient ddb, String statement, List parameters ) { - ExecuteStatementRequest request = ExecuteStatementRequest.builder() - .statement(statement) - .parameters(parameters) - .build(); + private static ExecuteStatementResponse executeStatementRequest(DynamoDbClient ddb, String statement, + List parameters) { + ExecuteStatementRequest request = ExecuteStatementRequest.builder() + .statement(statement) + .parameters(parameters) + .build(); - return ddb.executeStatement(request); - } + return ddb.executeStatement(request); + } } // snippet-end:[dynamodb.java2.scenario.partiql.batch.main] \ No newline at end of file diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/SyncPagination.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/SyncPagination.java index 1366933c2e3..a6b969bb79f 100755 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/SyncPagination.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/SyncPagination.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[SyncPagination.java demonstrates how to work with paginated functionality.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb; @@ -20,7 +14,8 @@ // snippet-end:[dynamodb.java2.sync_pagination.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,12 +25,12 @@ public class SyncPagination { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - type - The type of pagination. (auto, manual, or default).\s - """; + Where: + type - The type of pagination. (auto, manual, or default).\s + """; if (args.length != 1) { System.out.println(usage); @@ -45,8 +40,8 @@ public static void main(String[] args) { String type = args[0]; Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); switch (type.toLowerCase()) { case "manual" -> manualPagination(ddb); @@ -66,8 +61,8 @@ public static void main(String[] args) { public static void manualPagination(DynamoDbClient client) { System.out.println("running ManualPagination...\n"); ListTablesRequest listTablesRequest = ListTablesRequest.builder() - .limit(3) - .build(); + .limit(3) + .build(); boolean done = false; while (!done) { @@ -79,8 +74,8 @@ public static void manualPagination(DynamoDbClient client) { } listTablesRequest = listTablesRequest.toBuilder() - .exclusiveStartTableName(listTablesResponse.lastEvaluatedTableName()) - .build(); + .exclusiveStartTableName(listTablesResponse.lastEvaluatedTableName()) + .build(); } } @@ -97,12 +92,13 @@ public static void autoPagination(DynamoDbClient client) { System.out.println("AutoPagination: using stream"); responses.stream().forEach(response -> System.out.println(response.tableNames())); - // Convert the stream of responses to stream of table names, then print the table names. + // Convert the stream of responses to stream of table names, then print the + // table names. System.out.println("AutoPagination: using flatmap to get stream of table names"); responses.stream() - .flatMap(response -> response.tableNames().stream()) - .forEach(System.out::println); + .flatMap(response -> response.tableNames().stream()) + .forEach(System.out::println); System.out.println("AutoPagination: iterating directly on the table names"); Iterable tableNames = responses.tableNames(); @@ -127,4 +123,3 @@ public static void autoPaginationWithResume(DynamoDbClient client) { } } // snippet-end:[dynamodb.java2.sync_pagination.main] - diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/UpdateItem.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/UpdateItem.java index f8316b7aa27..42a58ac84dd 100755 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/UpdateItem.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/UpdateItem.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[UpdateItem.java demonstrates how to update a value located in an Amazon DynamoDB table.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb; @@ -22,31 +16,33 @@ // snippet-end:[dynamodb.java2.update_item.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * To update an Amazon DynamoDB table using the AWS SDK for Java V2, its better practice to use the + * To update an Amazon DynamoDB table using the AWS SDK for Java V2, its better + * practice to use the * Enhanced Client, See the EnhancedModifyItem example. */ public class UpdateItem { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - tableName - The Amazon DynamoDB table (for example, Music3). - key - The name of the key in the table (for example, Artist). - keyVal - The value of the key (for example, Famous Band). - name - The name of the column where the value is updated (for example, Awards). - updateVal - The value used to update an item (for example, 14). - Example: - UpdateItem Music3 Artist Famous Band Awards 14 - """; + Where: + tableName - The Amazon DynamoDB table (for example, Music3). + key - The name of the key in the table (for example, Artist). + keyVal - The value of the key (for example, Famous Band). + name - The name of the column where the value is updated (for example, Awards). + updateVal - The value used to update an item (for example, 14). + Example: + UpdateItem Music3 Artist Famous Band Awards 14 + """; if (args.length != 5) { System.out.println(usage); @@ -61,35 +57,35 @@ public static void main(String[] args) { Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); updateTableItem(ddb, tableName, key, keyVal, name, updateVal); ddb.close(); } public static void updateTableItem(DynamoDbClient ddb, - String tableName, - String key, - String keyVal, - String name, - String updateVal) { + String tableName, + String key, + String keyVal, + String name, + String updateVal) { HashMap itemKey = new HashMap<>(); itemKey.put(key, AttributeValue.builder() - .s(keyVal) - .build()); + .s(keyVal) + .build()); HashMap updatedValues = new HashMap<>(); updatedValues.put(name, AttributeValueUpdate.builder() - .value(AttributeValue.builder().s(updateVal).build()) - .action(AttributeAction.PUT) - .build()); + .value(AttributeValue.builder().s(updateVal).build()) + .action(AttributeAction.PUT) + .build()); UpdateItemRequest request = UpdateItemRequest.builder() - .tableName(tableName) - .key(itemKey) - .attributeUpdates(updatedValues) - .build(); + .tableName(tableName) + .key(itemKey) + .attributeUpdates(updatedValues) + .build(); try { ddb.updateItem(request); diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/UpdateTable.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/UpdateTable.java index a17baff435e..4af63125a10 100755 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/UpdateTable.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/UpdateTable.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[UpdateTable.java demonstrates how to update an Amazon DynamoDB table.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb; @@ -16,9 +10,11 @@ import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.UpdateTableRequest; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; + // snippet-end:[dynamodb.java2.update_table.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,17 +23,17 @@ public class UpdateTable { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - tableName - The Amazon DynamoDB table to update (for example, Music3). - readCapacity - The new read capacity of the table (for example, 16). - writeCapacity - The new write capacity of the table (for example, 10). + Where: + tableName - The Amazon DynamoDB table to update (for example, Music3). + readCapacity - The new read capacity of the table (for example, 16). + writeCapacity - The new write capacity of the table (for example, 10). - Example: - UpdateTable Music3 16 10 - """; + Example: + UpdateTable Music3 16 10 + """; if (args.length != 3) { System.out.println(usage); @@ -49,27 +45,28 @@ public static void main(String[] args) { Long writeCapacity = Long.parseLong(args[2]); Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); updateDynamoDBTable(ddb, tableName, readCapacity, writeCapacity); ddb.close(); } - public static void updateDynamoDBTable(DynamoDbClient ddb, String tableName, Long readCapacity, Long writeCapacity) { + public static void updateDynamoDBTable(DynamoDbClient ddb, String tableName, Long readCapacity, + Long writeCapacity) { System.out.format("Updating %s with new provisioned throughput values\n", tableName); System.out.format("Read capacity : %d\n", readCapacity); System.out.format("Write capacity : %d\n", writeCapacity); ProvisionedThroughput tableThroughput = ProvisionedThroughput.builder() - .readCapacityUnits(readCapacity) - .writeCapacityUnits(writeCapacity) - .build(); + .readCapacityUnits(readCapacity) + .writeCapacityUnits(writeCapacity) + .build(); UpdateTableRequest request = UpdateTableRequest.builder() - .provisionedThroughput(tableThroughput) - .tableName(tableName) - .build(); + .provisionedThroughput(tableThroughput) + .tableName(tableName) + .build(); try { ddb.updateTable(request); @@ -81,4 +78,3 @@ public static void updateDynamoDBTable(DynamoDbClient ddb, String tableName, Lon } } // snippet-end:[dynamodb.java2.update_table.main] - diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Work.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Work.java index a4931581d3d..d823da5f022 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Work.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Work.java @@ -1,7 +1,6 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.dynamodb; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedBatchDeleteItems.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedBatchDeleteItems.java index e598012a167..2a88eb9770d 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedBatchDeleteItems.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedBatchDeleteItems.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[EnhancedBatchDeleteItems.java demonstrates how to delete many items from an Amazon DynamoDB table by using the enhanced client.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.dynamodb.enhanced; // snippet-start:[dynamodb.java2.mapping.batchdelete.main] @@ -38,53 +33,55 @@ */ public class EnhancedBatchDeleteItems { - public static void main(String[] args) { - Region region = Region.US_EAST_1; - DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + public static void main(String[] args) { + Region region = Region.US_EAST_1; + DynamoDbClient ddb = DynamoDbClient.builder() + .region(region) + .build(); - DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() - .dynamoDbClient(ddb) - .build(); - deleteBatchRecords(enhancedClient); - ddb.close(); - } + DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() + .dynamoDbClient(ddb) + .build(); + deleteBatchRecords(enhancedClient); + ddb.close(); + } - public static void deleteBatchRecords(DynamoDbEnhancedClient enhancedClient) { - try { - DynamoDbTable mappedTable = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class)); - Key key1 = Key.builder() - .partitionValue("id110") - .build(); + public static void deleteBatchRecords(DynamoDbEnhancedClient enhancedClient) { + try { + DynamoDbTable mappedTable = enhancedClient.table("Customer", + TableSchema.fromBean(Customer.class)); + Key key1 = Key.builder() + .partitionValue("id110") + .build(); - Key key2 = Key.builder() - .partitionValue("id120") - .build(); + Key key2 = Key.builder() + .partitionValue("id120") + .build(); - BatchWriteItemEnhancedRequest request = BatchWriteItemEnhancedRequest.builder() - .writeBatches(WriteBatch.builder(Customer.class) - .mappedTableResource(mappedTable) - .addDeleteItem(DeleteItemEnhancedRequest.builder() - .key(key1) - .build()) - .build(), - WriteBatch.builder(Customer.class) - .mappedTableResource(mappedTable) - .addDeleteItem(DeleteItemEnhancedRequest.builder() - .key(key2) - .build()) - .build()) - .build(); + BatchWriteItemEnhancedRequest request = BatchWriteItemEnhancedRequest.builder() + .writeBatches(WriteBatch.builder(Customer.class) + .mappedTableResource(mappedTable) + .addDeleteItem(DeleteItemEnhancedRequest.builder() + .key(key1) + .build()) + .build(), + WriteBatch.builder(Customer.class) + .mappedTableResource(mappedTable) + .addDeleteItem(DeleteItemEnhancedRequest + .builder() + .key(key2) + .build()) + .build()) + .build(); - // Delete these two items from the table. - enhancedClient.batchWriteItem(request); - System.out.println("Records deleted"); + // Delete these two items from the table. + enhancedClient.batchWriteItem(request); + System.out.println("Records deleted"); - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } } - } } - // snippet-end:[dynamodb.java2.mapping.batchdelete.main] \ No newline at end of file +// snippet-end:[dynamodb.java2.mapping.batchdelete.main] \ No newline at end of file diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedBatchWriteItems.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedBatchWriteItems.java index d1f85b2e898..13e7060792d 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedBatchWriteItems.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedBatchWriteItems.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[EnhancedBatchWriteItems.java demonstrates how to insert many items into an Amazon DynamoDB table by using the enhanced client.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.dynamodb.enhanced; // snippet-start:[dynamodb.java2.mapping.batchitems.main] @@ -41,69 +36,75 @@ * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class EnhancedBatchWriteItems { - public static void main(String[] args) { - Region region = Region.US_EAST_1; - DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); - DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() - .dynamoDbClient(ddb) - .build(); - putBatchRecords(enhancedClient); - ddb.close(); - } - - public static void putBatchRecords(DynamoDbEnhancedClient enhancedClient) { - try { - DynamoDbTable customerMappedTable = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class)); - DynamoDbTable musicMappedTable = enhancedClient.table("Music", TableSchema.fromBean(Music.class)); - LocalDate localDate = LocalDate.parse("2020-04-07"); - LocalDateTime localDateTime = localDate.atStartOfDay(); - Instant instant = localDateTime.toInstant(ZoneOffset.UTC); - - Customer record2 = new Customer(); - record2.setCustName("Fred Pink"); - record2.setId("id110"); - record2.setEmail("fredp@noserver.com"); - record2.setRegistrationDate(instant) ; + public static void main(String[] args) { + Region region = Region.US_EAST_1; + DynamoDbClient ddb = DynamoDbClient.builder() + .region(region) + .build(); + DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() + .dynamoDbClient(ddb) + .build(); + putBatchRecords(enhancedClient); + ddb.close(); + } - Customer record3 = new Customer(); - record3.setCustName("Susan Pink"); - record3.setId("id120"); - record3.setEmail("spink@noserver.com"); - record3.setRegistrationDate(instant) ; + public static void putBatchRecords(DynamoDbEnhancedClient enhancedClient) { + try { + DynamoDbTable customerMappedTable = enhancedClient.table("Customer", + TableSchema.fromBean(Customer.class)); + DynamoDbTable musicMappedTable = enhancedClient.table("Music", + TableSchema.fromBean(Music.class)); + LocalDate localDate = LocalDate.parse("2020-04-07"); + LocalDateTime localDateTime = localDate.atStartOfDay(); + Instant instant = localDateTime.toInstant(ZoneOffset.UTC); - Customer record4 = new Customer(); - record4.setCustName("Jerry orange"); - record4.setId("id101"); - record4.setEmail("jorange@noserver.com"); - record4.setRegistrationDate(instant) ; + Customer record2 = new Customer(); + record2.setCustName("Fred Pink"); + record2.setId("id110"); + record2.setEmail("fredp@noserver.com"); + record2.setRegistrationDate(instant); + Customer record3 = new Customer(); + record3.setCustName("Susan Pink"); + record3.setId("id120"); + record3.setEmail("spink@noserver.com"); + record3.setRegistrationDate(instant); - BatchWriteItemEnhancedRequest batchWriteItemEnhancedRequest = BatchWriteItemEnhancedRequest.builder() - .writeBatches( - WriteBatch.builder(Customer.class) // add items to the Customer table - .mappedTableResource(customerMappedTable) - .addPutItem(builder -> builder.item(record2)) - .addPutItem(builder -> builder.item(record3)) - .addPutItem(builder -> builder.item(record4)) - .build(), - WriteBatch.builder(Music.class) // delete an item from the Music table - .mappedTableResource(musicMappedTable) - .addDeleteItem(builder -> builder.key( - Key.builder().partitionValue("Famous Band").build())) - .build()) - .build(); + Customer record4 = new Customer(); + record4.setCustName("Jerry orange"); + record4.setId("id101"); + record4.setEmail("jorange@noserver.com"); + record4.setRegistrationDate(instant); + BatchWriteItemEnhancedRequest batchWriteItemEnhancedRequest = BatchWriteItemEnhancedRequest + .builder() + .writeBatches( + WriteBatch.builder(Customer.class) // add items to the Customer + // table + .mappedTableResource(customerMappedTable) + .addPutItem(builder -> builder.item(record2)) + .addPutItem(builder -> builder.item(record3)) + .addPutItem(builder -> builder.item(record4)) + .build(), + WriteBatch.builder(Music.class) // delete an item from the Music + // table + .mappedTableResource(musicMappedTable) + .addDeleteItem(builder -> builder.key( + Key.builder().partitionValue( + "Famous Band") + .build())) + .build()) + .build(); - // Add three items to the Customer table and delete one item from the Music table. - enhancedClient.batchWriteItem(batchWriteItemEnhancedRequest); - System.out.println("done"); + // Add three items to the Customer table and delete one item from the Music + // table. + enhancedClient.batchWriteItem(batchWriteItemEnhancedRequest); + System.out.println("done"); - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } } - } } - // snippet-end:[dynamodb.java2.mapping.batchitems.main] \ No newline at end of file +// snippet-end:[dynamodb.java2.mapping.batchitems.main] \ No newline at end of file diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedCreateTable.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedCreateTable.java index 9feb6e3ee71..40e44cb21b7 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedCreateTable.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedCreateTable.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb.enhanced; // snippet-start:[dynamodb.java2.mapping.enhancedcreatetable.import] import com.example.dynamodb.Customer; diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedGetItem.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedGetItem.java index c925ec26e79..7f2c46f96a0 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedGetItem.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedGetItem.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[EnhancedGetItem.java demonstrates how to retrieve an item from an Amazon DynamoDB table by using the enhanced client.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.dynamodb.enhanced; // snippet-start:[dynamodb.java2.mapping.getitem.main] @@ -40,12 +35,12 @@ public class EnhancedGetItem { public static void main(String[] args) { Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() - .dynamoDbClient(ddb) - .build(); + .dynamoDbClient(ddb) + .build(); getItem(enhancedClient); ddb.close(); @@ -56,12 +51,12 @@ public static String getItem(DynamoDbEnhancedClient enhancedClient) { try { DynamoDbTable table = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class)); Key key = Key.builder() - .partitionValue("id101").sortValue("tred@noserver.com") - .build(); + .partitionValue("id101").sortValue("tred@noserver.com") + .build(); // Get the item by using the key. result = table.getItem( - (GetItemEnhancedRequest.Builder requestBuilder) -> requestBuilder.key(key)); + (GetItemEnhancedRequest.Builder requestBuilder) -> requestBuilder.key(key)); System.out.println("******* The description value is " + result.getCustName()); } catch (DynamoDbException e) { diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedGetItemUsingIndex.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedGetItemUsingIndex.java index 59720a97cd5..61363c2ac5b 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedGetItemUsingIndex.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedGetItemUsingIndex.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[GetItemUsingIndex.java demonstrates how to retrieve item from an Amazon DynamoDB table using a secondary index and the Enhanced Client.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb.enhanced; @@ -30,17 +24,21 @@ // snippet-end:[dynamodb.java2.get_item_index.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * To get an item from an Amazon DynamoDB table using the AWS SDK for Java V2, its better practice to use the + * To get an item from an Amazon DynamoDB table using the AWS SDK for Java V2, + * its better practice to use the * Enhanced Client, see the EnhancedGetItem example. * - * Create the Movies table by running the Scenario example and loading the Movie data from the JSON file. Next create a secondary - * index for the Movies table that uses only the year column. Name the index **year-index**. For more information, see: + * Create the Movies table by running the Scenario example and loading the Movie + * data from the JSON file. Next create a secondary + * index for the Movies table that uses only the year column. Name the index + * **year-index**. For more information, see: * * https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html */ @@ -49,8 +47,8 @@ public static void main(String[] args) { String tableName = "Movies"; Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); queryIndex(ddb, tableName); ddb.close(); @@ -60,34 +58,36 @@ public static void queryIndex(DynamoDbClient ddb, String tableName) { try { // Create a DynamoDbEnhancedClient and use the DynamoDbClient object. DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() - .dynamoDbClient(ddb) - .build(); + .dynamoDbClient(ddb) + .build(); - //Create a DynamoDbTable object based on Movies. + // Create a DynamoDbTable object based on Movies. DynamoDbTable table = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)); String dateVal = "2013"; - DynamoDbIndex secIndex = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)).index("year-index"); + DynamoDbIndex secIndex = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)) + .index("year-index"); AttributeValue attVal = AttributeValue.builder() - .n(dateVal) - .build(); + .n(dateVal) + .build(); // Create a QueryConditional object that's used in the query operation. QueryConditional queryConditional = QueryConditional - .keyEqualTo(Key.builder().partitionValue(attVal) - .build()); + .keyEqualTo(Key.builder().partitionValue(attVal) + .build()); // Get items in the table. SdkIterable> results = secIndex.query(QueryEnhancedRequest.builder() - .queryConditional(queryConditional) - .limit(300) - .build()); + .queryConditional(queryConditional) + .limit(300) + .build()); // Display the results. results.forEach(page -> { List allMovies = page.items(); for (Movies myMovies : allMovies) { - System.out.println("The movie title is " + myMovies.getTitle() + ". The year is " + myMovies.getYear()); + System.out.println( + "The movie title is " + myMovies.getTitle() + ". The year is " + myMovies.getYear()); } }); diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedHandleList.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedHandleList.java index 8e3d04c39b7..ddc1d5b3abb 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedHandleList.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedHandleList.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[EnhancedHandleList.java demonstrates how to put an item that includes a list into an Amazon DynamoDB table by using the enhanced client.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb.enhanced; @@ -37,12 +31,12 @@ public class EnhancedHandleList { public static void main(String[] args) { Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() - .dynamoDbClient(ddb) - .build(); + .dynamoDbClient(ddb) + .build(); putRecord(enhancedClient); ddb.close(); @@ -50,7 +44,8 @@ public static void main(String[] args) { public static void putRecord(DynamoDbEnhancedClient enhancedClient) { try { - DynamoDbTable contactTable = (DynamoDbTable) enhancedClient.table("Contact", TableSchema.fromBean(Contact.class)); + DynamoDbTable contactTable = (DynamoDbTable) enhancedClient.table("Contact", + TableSchema.fromBean(Contact.class)); List names = new ArrayList<>(); names.add("Scott"); names.add("LAM"); @@ -69,4 +64,4 @@ public static void putRecord(DynamoDbEnhancedClient enhancedClient) { System.out.println("done"); } } - // snippet-end:[dynamodb.java2.mapping.putitemlist.main] +// snippet-end:[dynamodb.java2.mapping.putitemlist.main] diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedModifyItem.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedModifyItem.java index c8b6599811f..2e8bb72496e 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedModifyItem.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedModifyItem.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[EnhancedModifyItem.java demonstrates how to modify an item located in an Amazon DynamoDB table by using the enhanced client.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.dynamodb.enhanced; // snippet-start:[dynamodb.java2.mapping.moditem.main] @@ -36,13 +31,13 @@ public class EnhancedModifyItem { public static void main(String[] args) { String usage = """ - Usage: - \s + Usage: + \s - Where: - key - the name of the key in the table (id120). - email - the value of the modified email column. - """; + Where: + key - the name of the key in the table (id120). + email - the value of the modified email column. + """; if (args.length != 2) { System.out.println(usage); @@ -53,12 +48,12 @@ public static void main(String[] args) { String email = args[1]; Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() - .dynamoDbClient(ddb) - .build(); + .dynamoDbClient(ddb) + .build(); String updatedValue = modifyItem(enhancedClient, key, email); System.out.println("The updated name value is " + updatedValue); @@ -67,10 +62,11 @@ public static void main(String[] args) { public static String modifyItem(DynamoDbEnhancedClient enhancedClient, String keyVal, String email) { try { - DynamoDbTable mappedTable = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class)); + DynamoDbTable mappedTable = enhancedClient.table("Customer", + TableSchema.fromBean(Customer.class)); Key key = Key.builder() - .partitionValue(keyVal) - .build(); + .partitionValue(keyVal) + .build(); // Get the item by using the key and update the email value. Customer customerRec = mappedTable.getItem(r -> r.key(key)); @@ -86,5 +82,3 @@ public static String modifyItem(DynamoDbEnhancedClient enhancedClient, String ke } } // snippet-end:[dynamodb.java2.mapping.moditem.main] - - diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedPutItem.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedPutItem.java index 11a69e63698..4699a3d1f9a 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedPutItem.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedPutItem.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[EnhancedPutItem.java demonstrates how to put an item into an Amazon DynamoDB table by using the enhanced client.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb.enhanced; @@ -41,12 +35,12 @@ public class EnhancedPutItem { public static void main(String[] args) { Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() - .dynamoDbClient(ddb) - .build(); + .dynamoDbClient(ddb) + .build(); putRecord(enhancedClient); ddb.close(); diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedQueryRecords.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedQueryRecords.java index a3d01b503a7..aaec361fdda 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedQueryRecords.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedQueryRecords.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[EnhancedQueryRecords.java demonstrates how to query an Amazon DynamoDB table by using the enhanced client.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.dynamodb.enhanced; // snippet-start:[dynamodb.java2.mapping.query.main] @@ -40,23 +35,25 @@ public class EnhancedQueryRecords { public static void main(String[] args) { Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() - .dynamoDbClient(ddb) - .build(); + .dynamoDbClient(ddb) + .build(); String result = queryTable(enhancedClient); System.out.println(result); ddb.close(); } + public static String queryTable(DynamoDbEnhancedClient enhancedClient) { try { - DynamoDbTable mappedTable = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class)); + DynamoDbTable mappedTable = enhancedClient.table("Customer", + TableSchema.fromBean(Customer.class)); QueryConditional queryConditional = QueryConditional.keyEqualTo(Key.builder() - .partitionValue("id101") - .build()); + .partitionValue("id101") + .build()); // Get items in the table and write out the ID value. Iterator results = mappedTable.query(queryConditional).items().iterator(); diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedQueryRecordsWithFilter.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedQueryRecordsWithFilter.java index f24743cecf7..553bfb853ac 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedQueryRecordsWithFilter.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedQueryRecordsWithFilter.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[EnhancedPutItem.java demonstrates how to put an item into an Amazon DynamoDB table by using the enhanced client.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.dynamodb.enhanced; // snippet-start:[dynamodb.java2.mapping.queryfilter.main] @@ -27,57 +22,60 @@ // snippet-end:[dynamodb.java2.mapping.queryfilter.import] public class EnhancedQueryRecordsWithFilter { - // Query the Customer table using a filter. - public static void main(String[] args) { - Region region = Region.US_EAST_1; - DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + // Query the Customer table using a filter. + public static void main(String[] args) { + Region region = Region.US_EAST_1; + DynamoDbClient ddb = DynamoDbClient.builder() + .region(region) + .build(); - DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() - .dynamoDbClient(ddb) - .build(); + DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() + .dynamoDbClient(ddb) + .build(); - queryTableFilter(enhancedClient); - ddb.close(); - } + queryTableFilter(enhancedClient); + ddb.close(); + } - public static Integer queryTableFilter(DynamoDbEnhancedClient enhancedClient) { - Integer countOfCustomers = 0; - try { - DynamoDbTable mappedTable = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class)); - AttributeValue att = AttributeValue.builder() - .s("Tom red") - .build(); + public static Integer queryTableFilter(DynamoDbEnhancedClient enhancedClient) { + Integer countOfCustomers = 0; + try { + DynamoDbTable mappedTable = enhancedClient.table("Customer", + TableSchema.fromBean(Customer.class)); + AttributeValue att = AttributeValue.builder() + .s("Tom red") + .build(); - Map expressionValues = new HashMap<>(); - expressionValues.put(":value", att); - Expression expression = Expression.builder() - .expression("custName = :value") - .expressionValues(expressionValues) - .build(); + Map expressionValues = new HashMap<>(); + expressionValues.put(":value", att); + Expression expression = Expression.builder() + .expression("custName = :value") + .expressionValues(expressionValues) + .build(); - // Create a QueryConditional object to query by partitionValue. - // Since the Customer table has a sort key attribute (email), we can use an expression - // to filter the query results if multiple items have the same partition key value. - QueryConditional queryConditional = QueryConditional - .keyEqualTo(Key.builder().partitionValue("id101") - .build()); + // Create a QueryConditional object to query by partitionValue. + // Since the Customer table has a sort key attribute (email), we can use an + // expression + // to filter the query results if multiple items have the same partition key + // value. + QueryConditional queryConditional = QueryConditional + .keyEqualTo(Key.builder().partitionValue("id101") + .build()); - for (Customer customer : mappedTable.query( - r -> r.queryConditional(queryConditional) - .filterExpression(expression) - ).items()) { - countOfCustomers++; - System.out.println(customer); - } + for (Customer customer : mappedTable.query( + r -> r.queryConditional(queryConditional) + .filterExpression(expression)) + .items()) { + countOfCustomers++; + System.out.println(customer); + } - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + System.out.println("Done"); + return countOfCustomers; } - System.out.println("Done"); - return countOfCustomers; - } } - // snippet-end:[dynamodb.java2.mapping.queryfilter.main] \ No newline at end of file +// snippet-end:[dynamodb.java2.mapping.queryfilter.main] \ No newline at end of file diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedQueryRecordsWithSortKey.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedQueryRecordsWithSortKey.java index e539a8b9061..0694062036a 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedQueryRecordsWithSortKey.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedQueryRecordsWithSortKey.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb.enhanced; // snippet-start:[dynamodb.java2.mapping.querykey.import] diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedScanRecords.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedScanRecords.java index 2907861c95b..7cc7798c363 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedScanRecords.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedScanRecords.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[EnhancedScanRecords.java demonstrates how to scan an Amazon DynamoDB table by using the enhanced client.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.dynamodb.enhanced; // snippet-start:[dynamodb.java2.mapping.scan.main] @@ -38,12 +33,12 @@ public class EnhancedScanRecords { public static void main(String[] args) { Region region = Region.US_EAST_1; DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() - .dynamoDbClient(ddb) - .build(); + .dynamoDbClient(ddb) + .build(); scan(enhancedClient); ddb.close(); diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedScanRecordsWithExpression.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedScanRecordsWithExpression.java index 0d54d9d7049..a3902ee536d 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedScanRecordsWithExpression.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedScanRecordsWithExpression.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodb.enhanced; // snippet-start:[dynamodb.java2.mapping.scanEx.import] diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedTableSchema.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedTableSchema.java index d3c9f917543..66e50d18eac 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedTableSchema.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/enhanced/EnhancedTableSchema.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[EnhancedTableSchema.java demonstrates how to use the Amazon DynamoDB enhanced client and a TableSchema to put an item into a table.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon DynamoDB] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.dynamodb.enhanced; // snippet-start:[dynamodb.java2.mapping.tableschema.main] @@ -31,29 +26,28 @@ * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class EnhancedTableSchema { - private static final TableSchema TABLE_SCHEMA = - StaticTableSchema.builder(Record.class) - .newItemSupplier(Record::new) - .addAttribute(String.class, a -> a.name("id") - .getter(Record::getId) - .setter(Record::setId) - .tags(primaryPartitionKey())) - .addAttribute(String.class, a -> a.name("sort") - .getter(Record::getSort) - .setter(Record::setSort) - .tags(primarySortKey())) - .addAttribute(String.class, a -> a.name("attribute") - .getter(Record::getAttribute) - .setter(Record::setAttribute)) - .addAttribute(String.class, a -> a.name("attribute2*") - .getter(Record::getAttribute2) - .setter(Record::setAttribute2) - .tags(secondaryPartitionKey("gsi_1"))) - .addAttribute(String.class, a -> a.name("attribute3") - .getter(Record::getAttribute3) - .setter(Record::setAttribute3) - .tags(secondarySortKey("gsi_1"))) - .build(); + private static final TableSchema TABLE_SCHEMA = StaticTableSchema.builder(Record.class) + .newItemSupplier(Record::new) + .addAttribute(String.class, a -> a.name("id") + .getter(Record::getId) + .setter(Record::setId) + .tags(primaryPartitionKey())) + .addAttribute(String.class, a -> a.name("sort") + .getter(Record::getSort) + .setter(Record::setSort) + .tags(primarySortKey())) + .addAttribute(String.class, a -> a.name("attribute") + .getter(Record::getAttribute) + .setter(Record::setAttribute)) + .addAttribute(String.class, a -> a.name("attribute2*") + .getter(Record::getAttribute2) + .setter(Record::setAttribute2) + .tags(secondaryPartitionKey("gsi_1"))) + .addAttribute(String.class, a -> a.name("attribute3") + .getter(Record::getAttribute3) + .setter(Record::setAttribute3) + .tags(secondarySortKey("gsi_1"))) + .build(); public static void main(String[] args) { Region region = Region.US_EAST_1; @@ -69,13 +63,13 @@ public static void main(String[] args) { ddb.close(); } - public static void putRecord(DynamoDbEnhancedClient enhancedClient){ + public static void putRecord(DynamoDbEnhancedClient enhancedClient) { try { - //Create a DynamoDbTable object + // Create a DynamoDbTable object DynamoDbTable mappedTable = enhancedClient.table("Record", TABLE_SCHEMA); - //Populate the Table + // Populate the Table Record record = new Record() .setId("id-value") .setSort("sort-value") diff --git a/javav2/example_code/dynamodb/src/test/java/DynamoDBTest.java b/javav2/example_code/dynamodb/src/test/java/DynamoDBTest.java index 5573617abc3..0d29afdcc53 100644 --- a/javav2/example_code/dynamodb/src/test/java/DynamoDBTest.java +++ b/javav2/example_code/dynamodb/src/test/java/DynamoDBTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.dynamodb.CreateTable; import com.example.dynamodb.DeleteItem; @@ -68,9 +66,9 @@ public class DynamoDBTest { public static void setUp() throws IOException { Region region = Region.US_EAST_1; ddb = DynamoDbClient.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -88,33 +86,36 @@ public static void setUp() throws IOException { songTitleVal = values.getSongTitleVal(); tableName2 = "Movies"; - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - try (InputStream input = DynamoDBTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - // Populate the data members required for all tests. - prop.load(input); - tableName = prop.getProperty("tableName"); - fileName = prop.getProperty("fileName"); - key = prop.getProperty("key"); - keyVal = prop.getProperty("keyValue"); - albumTitle = prop.getProperty("albumTitle"); - albumTitleValue = prop.getProperty("AlbumTitleValue"); - awards = prop.getProperty("Awards"); - awardVal = prop.getProperty("AwardVal"); - songTitle = prop.getProperty("SongTitle"); - songTitleVal = prop.getProperty("SongTitleVal"); - tableName2 = "Movies"; - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * try (InputStream input = + * DynamoDBTest.class.getClassLoader().getResourceAsStream("config.properties")) + * { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * // Populate the data members required for all tests. + * prop.load(input); + * tableName = prop.getProperty("tableName"); + * fileName = prop.getProperty("fileName"); + * key = prop.getProperty("key"); + * keyVal = prop.getProperty("keyValue"); + * albumTitle = prop.getProperty("albumTitle"); + * albumTitleValue = prop.getProperty("AlbumTitleValue"); + * awards = prop.getProperty("Awards"); + * awardVal = prop.getProperty("AwardVal"); + * songTitle = prop.getProperty("SongTitle"); + * songTitleVal = prop.getProperty("SongTitleVal"); + * tableName2 = "Movies"; + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @@ -130,7 +131,7 @@ public void createTable() { @Tag("IntegrationTest") @Order(2) public void describeTable() { - assertDoesNotThrow(() ->DescribeTable.describeDymamoDBTable(ddb,tableName)); + assertDoesNotThrow(() -> DescribeTable.describeDymamoDBTable(ddb, tableName)); System.out.println("\n Test 2 passed"); } @@ -138,24 +139,24 @@ public void describeTable() { @Tag("IntegrationTest") @Order(3) public void putItem() { - assertDoesNotThrow(() ->PutItem.putItemInTable(ddb, - tableName, - key, - keyVal, - albumTitle, - albumTitleValue, - awards, - awardVal, - songTitle, - songTitleVal)); - System.out.println("\n Test 3 passed"); + assertDoesNotThrow(() -> PutItem.putItemInTable(ddb, + tableName, + key, + keyVal, + albumTitle, + albumTitleValue, + awards, + awardVal, + songTitle, + songTitleVal)); + System.out.println("\n Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) public void listTables() { - assertDoesNotThrow(() ->ListTables.listAllTables(ddb)); + assertDoesNotThrow(() -> ListTables.listAllTables(ddb)); System.out.println("\n Test 4 passed"); } @@ -163,7 +164,7 @@ public void listTables() { @Tag("IntegrationTest") @Order(5) public void queryTable() { - int response = Query.queryTable(ddb,tableName, key,keyVal,"#a" ); + int response = Query.queryTable(ddb, tableName, key, keyVal, "#a"); assertEquals(response, 1); System.out.println("\n Test 5 passed"); } @@ -172,7 +173,7 @@ public void queryTable() { @Tag("IntegrationTest") @Order(6) public void updateItem() { - assertDoesNotThrow(() ->UpdateItem.updateTableItem(ddb,tableName, key, keyVal, awards, "40")); + assertDoesNotThrow(() -> UpdateItem.updateTableItem(ddb, tableName, key, keyVal, awards, "40")); System.out.println("\n Test 6 passed"); } @@ -180,7 +181,7 @@ public void updateItem() { @Tag("IntegrationTest") @Order(7) public void getItem() { - assertDoesNotThrow(() ->GetItem.getDynamoDBItem(ddb, tableName,key,keyVal)); + assertDoesNotThrow(() -> GetItem.getDynamoDBItem(ddb, tableName, key, keyVal)); System.out.println("\n Test 7 passed"); } @@ -188,90 +189,91 @@ public void getItem() { @Tag("IntegrationTest") @Order(8) public void scanItems() { - assertDoesNotThrow(() ->DynamoDBScanItems.scanItems(ddb, tableName)); + assertDoesNotThrow(() -> DynamoDBScanItems.scanItems(ddb, tableName)); System.out.println("\n Test 8 passed"); } - @Test - @Tag("IntegrationTest") - @Order(9) - public void deleteItem() { - assertDoesNotThrow(() ->DeleteItem.deleteDynamoDBItem(ddb,tableName,key,keyVal)); - System.out.println("\n Test 9 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(10) - public void sycnPagination(){ - assertDoesNotThrow(() -> SyncPagination.manualPagination(ddb)); - assertDoesNotThrow(() ->SyncPagination.autoPagination(ddb)); - assertDoesNotThrow(() ->SyncPagination.autoPaginationWithResume(ddb)); - System.out.println("\n Test 10 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(11) - public void updateTable(){ - Long readCapacity = Long.parseLong("16"); - Long writeCapacity = Long.parseLong("10"); - assertDoesNotThrow(() ->UpdateTable.updateDynamoDBTable(ddb, tableName, readCapacity, writeCapacity)); - System.out.println("\n Test 11 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(12) - public void deleteTable() { - try { - //Wait 15 secs for table to update based on test 10 - TimeUnit.SECONDS.sleep(15); - assertDoesNotThrow(() ->DeleteTable.deleteDynamoDBTable(ddb,tableName)); - } catch (InterruptedException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - System.out.println("\n Test 12 passed"); + @Test + @Tag("IntegrationTest") + @Order(9) + public void deleteItem() { + assertDoesNotThrow(() -> DeleteItem.deleteDynamoDBItem(ddb, tableName, key, keyVal)); + System.out.println("\n Test 9 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(10) + public void sycnPagination() { + assertDoesNotThrow(() -> SyncPagination.manualPagination(ddb)); + assertDoesNotThrow(() -> SyncPagination.autoPagination(ddb)); + assertDoesNotThrow(() -> SyncPagination.autoPaginationWithResume(ddb)); + System.out.println("\n Test 10 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(11) + public void updateTable() { + Long readCapacity = Long.parseLong("16"); + Long writeCapacity = Long.parseLong("10"); + assertDoesNotThrow(() -> UpdateTable.updateDynamoDBTable(ddb, tableName, readCapacity, writeCapacity)); + System.out.println("\n Test 11 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(12) + public void deleteTable() { + try { + // Wait 15 secs for table to update based on test 10 + TimeUnit.SECONDS.sleep(15); + assertDoesNotThrow(() -> DeleteTable.deleteDynamoDBTable(ddb, tableName)); + } catch (InterruptedException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + System.out.println("\n Test 12 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(13) + public void testScenario() throws IOException { + assertDoesNotThrow(() -> Scenario.createTable(ddb, tableName2)); + assertDoesNotThrow(() -> Scenario.loadData(ddb, tableName2, fileName)); + assertDoesNotThrow(() -> Scenario.getItem(ddb)); + assertDoesNotThrow(() -> Scenario.putRecord(ddb)); + assertDoesNotThrow(() -> Scenario.updateTableItem(ddb, tableName2)); + assertDoesNotThrow(() -> Scenario.scanMovies(ddb, tableName2)); + assertDoesNotThrow(() -> Scenario.queryTable(ddb)); + assertDoesNotThrow(() -> Scenario.deleteDynamoDBTable(ddb, tableName2)); + System.out.println("\n Test 13 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(14) + public void testScenarioPartiQL() throws IOException { + assertDoesNotThrow(() -> ScenarioPartiQ.createTable(ddb, "MoviesPartiQ")); + assertDoesNotThrow(() -> ScenarioPartiQ.loadData(ddb, fileName)); + assertDoesNotThrow(() -> ScenarioPartiQ.getItem(ddb)); + assertDoesNotThrow(() -> ScenarioPartiQ.putRecord(ddb)); + assertDoesNotThrow(() -> ScenarioPartiQ.updateTableItem(ddb)); + assertDoesNotThrow(() -> ScenarioPartiQ.queryTable(ddb)); + assertDoesNotThrow(() -> ScenarioPartiQ.deleteDynamoDBTable(ddb, "MoviesPartiQ")); } - @Test - @Tag("IntegrationTest") - @Order(13) - public void testScenario() throws IOException { - assertDoesNotThrow(() ->Scenario.createTable(ddb, tableName2)); - assertDoesNotThrow(() ->Scenario.loadData(ddb, tableName2, fileName)); - assertDoesNotThrow(() ->Scenario.getItem(ddb)) ; - assertDoesNotThrow(() ->Scenario.putRecord(ddb)); - assertDoesNotThrow(() ->Scenario.updateTableItem(ddb, tableName2)); - assertDoesNotThrow(() ->Scenario.scanMovies(ddb, tableName2)); - assertDoesNotThrow(() ->Scenario.queryTable(ddb)); - assertDoesNotThrow(() ->Scenario.deleteDynamoDBTable(ddb, tableName2)); - System.out.println("\n Test 13 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(14) - public void testScenarioPartiQL() throws IOException { - assertDoesNotThrow(() ->ScenarioPartiQ.createTable(ddb, "MoviesPartiQ")); - assertDoesNotThrow(() ->ScenarioPartiQ.loadData(ddb, fileName)); - assertDoesNotThrow(() ->ScenarioPartiQ.getItem(ddb)); - assertDoesNotThrow(() ->ScenarioPartiQ.putRecord(ddb)); - assertDoesNotThrow(() ->ScenarioPartiQ.updateTableItem(ddb)); - assertDoesNotThrow(() ->ScenarioPartiQ.queryTable(ddb)); - assertDoesNotThrow(() ->ScenarioPartiQ.deleteDynamoDBTable(ddb, "MoviesPartiQ")); - } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/dynamodb"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -334,5 +336,3 @@ public String getFileName() { } } } - - diff --git a/javav2/example_code/dynamodb/src/test/java/EnhancedClientTest.java b/javav2/example_code/dynamodb/src/test/java/EnhancedClientTest.java index 8d33508d66b..47220e1cfcc 100644 --- a/javav2/example_code/dynamodb/src/test/java/EnhancedClientTest.java +++ b/javav2/example_code/dynamodb/src/test/java/EnhancedClientTest.java @@ -1,140 +1,142 @@ -import static org.junit.jupiter.api.Assertions.assertTrue; - -import com.example.dynamodb.*; -import com.example.dynamodb.enhanced.*; -import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.dynamodb.DynamoDbClient; -import org.junit.jupiter.api.*; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -import static org.junit.jupiter.api.Assertions.assertNotNull; - - - -@TestInstance(TestInstance.Lifecycle.PER_METHOD) -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) -public class EnhancedClientTest { - - private static DynamoDbClient ddb; - private static DynamoDbEnhancedClient enhancedClient; - private static String enhancedTableName = ""; - private static String enhancedTableKey = ""; - private static String enhancedTestRegion = ""; - - @BeforeAll - public static void setUp() { - - try (InputStream input = EnhancedClientTest.class.getClassLoader().getResourceAsStream("config.properties")) { - - Properties prop = new Properties(); - - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - //load a properties file from class path, inside static method - prop.load(input); - enhancedTableName = prop.getProperty("enhancedTableName"); - enhancedTableKey = prop.getProperty("enhancedTableKey"); - enhancedTestRegion = prop.getProperty("enhancedTestRegion"); - } catch (IOException ex) { - ex.printStackTrace(); - } - - //Create a DynamoDbClient object - Region region = Region.of(enhancedTestRegion); - ddb = DynamoDbClient.builder() - .region(region) - .build(); - - // Create a DynamoDbEnhancedClient object - enhancedClient = DynamoDbEnhancedClient.builder() - .dynamoDbClient(ddb) - .build(); - - } - - @Test - @Order(1) - public void whenInitializingEnhancedClient_thenNotNull() { - assertNotNull(enhancedClient); - System.out.println("Test 1 passed"); - } - - @Test - @Order(2) - public void CreateTable() { - EnhancedCreateTable.createTable(enhancedClient); - System.out.println("\n Test 2 passed"); - } - - @Test - @Order(3) - public void PutItem() { - - //Table exists as we used Waiters - EnhancedPutItem.putRecord(enhancedClient); - System.out.println("\n Test 3 passed"); - } - - @Test - @Order(4) - public void PutBatchItems() throws IOException { - - // create and seed the Music table to demonstrate that batching calls - // works with multiple tables - DynamoDBTest.setUp(); // load properties for Music table - DynamoDBTest ddbTest = new DynamoDBTest(); - ddbTest.createTable(); // create Music table - ddbTest.putItem(); // add one item to Music table - - EnhancedBatchWriteItems.putBatchRecords(enhancedClient); - System.out.println("\n Test 4 passed"); - ddbTest.deleteTable(); - } - - @Test - @Order(5) - public void queryWithFilter(){ - Integer customerCount = EnhancedQueryRecordsWithFilter.queryTableFilter(enhancedClient); - Assertions.assertEquals(1, customerCount); - System.out.println("\n Test 5 passed"); - } - - - @Test - @Order(6) - public void GetItem() { - String result = EnhancedGetItem.getItem(enhancedClient); - assertTrue(!result.isEmpty()); - System.out.println("\n Test 6 passed"); - } - - @Test - @Order(7) - public void QueryRecords() { - - String result = EnhancedQueryRecords.queryTable(enhancedClient); - assertTrue(!result.isEmpty()); - System.out.println("\n Test 7passed"); - } - - @Test - @Order(8) - public void ScanRecords() { - - EnhancedScanRecords.scan(enhancedClient); - System.out.println("\n Test 8 passed"); - } - - @Test - @Order(9) - public void DeleteTable() { - - DeleteTable.deleteDynamoDBTable(ddb,enhancedTableName); - System.out.println("\n Test 9 passed"); - } +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.example.dynamodb.*; +import com.example.dynamodb.enhanced.*; +import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import org.junit.jupiter.api.*; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + + + +@TestInstance(TestInstance.Lifecycle.PER_METHOD) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +public class EnhancedClientTest { + + private static DynamoDbClient ddb; + private static DynamoDbEnhancedClient enhancedClient; + private static String enhancedTableName = ""; + private static String enhancedTableKey = ""; + private static String enhancedTestRegion = ""; + + @BeforeAll + public static void setUp() { + + try (InputStream input = EnhancedClientTest.class.getClassLoader().getResourceAsStream("config.properties")) { + + Properties prop = new Properties(); + + if (input == null) { + System.out.println("Sorry, unable to find config.properties"); + return; + } + //load a properties file from class path, inside static method + prop.load(input); + enhancedTableName = prop.getProperty("enhancedTableName"); + enhancedTableKey = prop.getProperty("enhancedTableKey"); + enhancedTestRegion = prop.getProperty("enhancedTestRegion"); + } catch (IOException ex) { + ex.printStackTrace(); + } + + //Create a DynamoDbClient object + Region region = Region.of(enhancedTestRegion); + ddb = DynamoDbClient.builder() + .region(region) + .build(); + + // Create a DynamoDbEnhancedClient object + enhancedClient = DynamoDbEnhancedClient.builder() + .dynamoDbClient(ddb) + .build(); + + } + + @Test + @Order(1) + public void whenInitializingEnhancedClient_thenNotNull() { + assertNotNull(enhancedClient); + System.out.println("Test 1 passed"); + } + + @Test + @Order(2) + public void CreateTable() { + EnhancedCreateTable.createTable(enhancedClient); + System.out.println("\n Test 2 passed"); + } + + @Test + @Order(3) + public void PutItem() { + + //Table exists as we used Waiters + EnhancedPutItem.putRecord(enhancedClient); + System.out.println("\n Test 3 passed"); + } + + @Test + @Order(4) + public void PutBatchItems() throws IOException { + + // create and seed the Music table to demonstrate that batching calls + // works with multiple tables + DynamoDBTest.setUp(); // load properties for Music table + DynamoDBTest ddbTest = new DynamoDBTest(); + ddbTest.createTable(); // create Music table + ddbTest.putItem(); // add one item to Music table + + EnhancedBatchWriteItems.putBatchRecords(enhancedClient); + System.out.println("\n Test 4 passed"); + ddbTest.deleteTable(); + } + + @Test + @Order(5) + public void queryWithFilter(){ + Integer customerCount = EnhancedQueryRecordsWithFilter.queryTableFilter(enhancedClient); + Assertions.assertEquals(1, customerCount); + System.out.println("\n Test 5 passed"); + } + + + @Test + @Order(6) + public void GetItem() { + String result = EnhancedGetItem.getItem(enhancedClient); + assertTrue(!result.isEmpty()); + System.out.println("\n Test 6 passed"); + } + + @Test + @Order(7) + public void QueryRecords() { + + String result = EnhancedQueryRecords.queryTable(enhancedClient); + assertTrue(!result.isEmpty()); + System.out.println("\n Test 7passed"); + } + + @Test + @Order(8) + public void ScanRecords() { + + EnhancedScanRecords.scan(enhancedClient); + System.out.println("\n Test 8 passed"); + } + + @Test + @Order(9) + public void DeleteTable() { + + DeleteTable.deleteDynamoDBTable(ddb,enhancedTableName); + System.out.println("\n Test 9 passed"); + } } \ No newline at end of file diff --git a/javav2/example_code/dynamodbasync/run_example.sh b/javav2/example_code/dynamodbasync/run_example.sh index c0b26fbd7fe..7b618024811 100755 --- a/javav2/example_code/dynamodbasync/run_example.sh +++ b/javav2/example_code/dynamodbasync/run_example.sh @@ -1,12 +1,14 @@ -#!/bin/bash -if [[ -z $* ]] ; then - echo 'Supply the name of one of the example classes as an argument.' - echo 'If there are arguments to the class, put them in quotes after the class name.' - exit 1 -fi -export CLASSPATH=target/sdk-dynamodbasync-examples-1.0.jar -export className=$1 -echo "## Running $className..." -shift -echo "## arguments $@..." -mvn exec:java -Dexec.mainClass="com.example.dynamodbasync.$className" -Dexec.args="$@" +#!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +if [[ -z $* ]] ; then + echo 'Supply the name of one of the example classes as an argument.' + echo 'If there are arguments to the class, put them in quotes after the class name.' + exit 1 +fi +export CLASSPATH=target/sdk-dynamodbasync-examples-1.0.jar +export className=$1 +echo "## Running $className..." +shift +echo "## arguments $@..." +mvn exec:java -Dexec.mainClass="com.example.dynamodbasync.$className" -Dexec.args="$@" diff --git a/javav2/example_code/dynamodbasync/src/main/java/com/example/dynamodbasync/AsyncPagination.java b/javav2/example_code/dynamodbasync/src/main/java/com/example/dynamodbasync/AsyncPagination.java index 4951dc1b2e9..b35d850b8f1 100755 --- a/javav2/example_code/dynamodbasync/src/main/java/com/example/dynamodbasync/AsyncPagination.java +++ b/javav2/example_code/dynamodbasync/src/main/java/com/example/dynamodbasync/AsyncPagination.java @@ -1,24 +1,5 @@ -//snippet-sourcedescription:[AsyncPagination.java demonstrates how to use auto pagination with the asynchronous DynamoDB client for responses with multiple pages of data.] -//snippet-keyword:[SDK for Java 2.0] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[10/15/2020] -//snippet-sourceauthor:[scmacdon] -/* - * Copyright 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. - * You may obtain a copy of the License at: - * - * http://aws.amazon.com/apache2.0 - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES - * OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and - * limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodbasync; // snippet-start:[dynamodb.java2.async_pagination.complete] @@ -79,7 +60,8 @@ public static void main(String[] args) throws InterruptedException, ExecutionExc private static void ManualPagination() throws InterruptedException { System.out.println("running ManualPagination...\n"); - // Creates a default async client with credentials and regions loaded from the environment + // Creates a default async client with credentials and regions loaded from the + // environment DynamoDbAsyncClient client = DynamoDbAsyncClient.create(); CompletableFuture response = client.listTables(ListTablesRequest.builder() .build()); @@ -102,7 +84,8 @@ private static void AutoPagination() throws InterruptedException, ExecutionExcep System.out.println("running AutoPagination...\n"); // snippet-start:[dynamodb.java2.async_pagination.pagesclient] - // Creates a default client with credentials and region loaded from the environment. + // Creates a default client with credentials and region loaded from the + // environment. final DynamoDbAsyncClient asyncClient = DynamoDbAsyncClient.create(); ListTablesRequest listTablesRequest = ListTablesRequest.builder().limit(3).build(); @@ -118,22 +101,26 @@ private static void AutoPagination() throws InterruptedException, ExecutionExcep future.get(); // snippet-start:[dynamodb.java2.async_pagination.pagessubscribe] - // A Subscription represents a one-to-one life-cycle of a Subscriber subscribing to a Publisher. + // A Subscription represents a one-to-one life-cycle of a Subscriber subscribing + // to a Publisher. publisher.subscribe(new Subscriber() { - // Maintain a reference to the subscription object, which is required to request data from the publisher. + // Maintain a reference to the subscription object, which is required to request + // data from the publisher. private Subscription subscription; @Override public void onSubscribe(Subscription s) { subscription = s; - // Request method should be called to demand data. Here we request a single page. + // Request method should be called to demand data. Here we request a single + // page. subscription.request(1); } @Override public void onNext(ListTablesResponse response) { response.tableNames().forEach(System.out::println); - // After you process the current page, call the request method to signal that you are ready for next page. + // After you process the current page, call the request method to signal that + // you are ready for next page. subscription.request(1); } @@ -144,20 +131,24 @@ public void onError(Throwable t) { @Override public void onComplete() { - // This indicates all the results are delivered and there are no more pages left. + // This indicates all the results are delivered and there are no more pages + // left. } }); // snippet-end:[dynamodb.java2.async_pagination.pagessubscribe] - // Since the code above is non-blocking, make sure your application doesn't end immediately. - // For this example, I am using Thread.sleep to wait for all pages to get delivered. + // Since the code above is non-blocking, make sure your application doesn't end + // immediately. + // For this example, I am using Thread.sleep to wait for all pages to get + // delivered. Thread.sleep(3_000); } private static void AutoPaginationOnCollection() throws InterruptedException, ExecutionException { System.out.println("running AutoPagination - iterating on item collection...\n"); // snippet-start:[dynamodb.java2.async_pagination.asyncclient] - // Create a default client with credentials and region loaded from the environment. + // Create a default client with credentials and region loaded from the + // environment. final DynamoDbAsyncClient asyncClient = DynamoDbAsyncClient.create(); ListTablesRequest listTablesRequest = ListTablesRequest.builder().limit(3).build(); @@ -198,7 +189,8 @@ public void onComplete() { }); // snippet-end:[dynamodb.java2.async_pagination.subscriber] - // Since the code above is non-blocking, make sure your application doesn't end immediately. + // Since the code above is non-blocking, make sure your application doesn't end + // immediately. // For this example, I use Thread.sleep to wait for all pages to get delivered. Thread.sleep(3_000); } @@ -227,7 +219,8 @@ private static void useThirdPartySubscriber_Reactor() { ListTablesPublisher publisher = asyncClient.listTablesPaginator(ListTablesRequest.builder() .build()); - // The Flux class has many helper methods that work with any reactive streams compatible publisher implementation + // The Flux class has many helper methods that work with any reactive streams + // compatible publisher implementation List tables = Flux.from(publisher) .flatMapIterable(ListTablesResponse::tableNames) .collectList() diff --git a/javav2/example_code/dynamodbasync/src/main/java/com/example/dynamodbasync/DynamoDBAsyncCreateTable.java b/javav2/example_code/dynamodbasync/src/main/java/com/example/dynamodbasync/DynamoDBAsyncCreateTable.java index 0f4a5dacab9..c0d8c997d91 100644 --- a/javav2/example_code/dynamodbasync/src/main/java/com/example/dynamodbasync/DynamoDBAsyncCreateTable.java +++ b/javav2/example_code/dynamodbasync/src/main/java/com/example/dynamodbasync/DynamoDBAsyncCreateTable.java @@ -1,131 +1,126 @@ -//snippet-sourcedescription:[DynamoDBAsyncCreateTable.java demonstrates how to create an Amazon DynamoDB table using DynamoDbAsyncClient and DynamoDbAsyncWaiter objects.] -//snippet-keyword:[SDK for Java 2.0] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[10/15/2020] -//snippet-sourceauthor:[scmacdon- aws] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - This file is 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/ - This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR - CONDITIONS OF ANY KIND, either express or implied. See the License for the - specific language governing permissions and limitations under the License. -*/ - - -package com.example.dynamodbasync; - -// snippet-start:[dynamodb.java2.dbasync.table.import] -import software.amazon.awssdk.core.waiters.WaiterResponse; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; -import java.util.concurrent.CompletableFuture; -import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; -import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; -import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; -import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; -import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; -import software.amazon.awssdk.services.dynamodb.model.KeyType; -import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse; -import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; -import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse; -import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbAsyncWaiter; -// snippet-end:[dynamodb.java2.dbasync.table.import] - -public class DynamoDBAsyncCreateTable { - - public static void main(String[] args) throws InterruptedException { - - final String USAGE = "\n" + - "Usage:\n" + - " DynamoDBAsyncCreateTable \n\n" + - "Where:\n" + - " table - the table to create (i.e., Music3)\n\n" + - " key - the key for the table (i.e., Artist)\n" + - "Example:\n" + - " Music3 Artist \n"; - - if (args.length < 2) { - System.out.println(USAGE); - System.exit(1); - } - - /* Read the name from command args */ - String tableName = args[0]; - String key = args[1]; - - // Create the DynamoDbAsyncClient object - Region region = Region.US_EAST_1; - DynamoDbAsyncClient client = DynamoDbAsyncClient.builder() - .region(region) - .build(); - - createTable(client, tableName, key); - } - - // snippet-start:[dynamodb.java2.dbasync.table.main] - public static void createTable(DynamoDbAsyncClient client, String tableName, String key) { - - // Create a DynamoDbAsyncWaiter object - DynamoDbAsyncWaiter asyncWaiter = client.waiter(); - - // Create the CreateTableRequest object - CreateTableRequest request = CreateTableRequest.builder() - .attributeDefinitions(AttributeDefinition.builder() - .attributeName(key) - .attributeType(ScalarAttributeType.S) - .build()) - .keySchema(KeySchemaElement.builder() - .attributeName(key) - .keyType(KeyType.HASH) - .build()) - .provisionedThroughput(ProvisionedThroughput.builder() - .readCapacityUnits(new Long(10)) - .writeCapacityUnits(new Long(10)) - .build()) - .tableName(tableName) - .build(); - - // Create the table by using the DynamoDbAsyncClient object - CompletableFuture response = client.createTable(request); - - // When future is complete (either successfully or in error) handle the response - response.whenComplete((table, err) -> { - try { - if (table != null) { - - // Create a DescribeTableRequest object required for waiter functionality - DescribeTableRequest tableRequest = DescribeTableRequest.builder() - .tableName(table.tableDescription().tableName()) - .build(); - - CompletableFuture> waiterResponse = asyncWaiter.waitUntilTableExists(tableRequest); - - // Fires when the table is ready - waiterResponse.whenComplete((r, t) -> { - - // print out the new table's ARN when its ready - String tableARN = r.matched().response().get().table().tableArn(); - System.out.println("The table "+ tableARN +" is ready"); - - }); - waiterResponse.join(); - - } else { - // Handle error - err.printStackTrace(); - } - } finally { - // Lets the application shut down. Only close the client when you are completely done with it. - client.close(); - } - }); - response.join(); - } - // snippet-end:[dynamodb.java2.dbasync.table.main] -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +/* + Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + This file is 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/ + This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. See the License for the + specific language governing permissions and limitations under the License. +*/ + +package com.example.dynamodbasync; + +// snippet-start:[dynamodb.java2.dbasync.table.import] +import software.amazon.awssdk.core.waiters.WaiterResponse; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; +import java.util.concurrent.CompletableFuture; +import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; +import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; +import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; +import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; +import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; +import software.amazon.awssdk.services.dynamodb.model.KeyType; +import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse; +import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; +import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse; +import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbAsyncWaiter; +// snippet-end:[dynamodb.java2.dbasync.table.import] + +public class DynamoDBAsyncCreateTable { + + public static void main(String[] args) throws InterruptedException { + + final String USAGE = "\n" + + "Usage:\n" + + " DynamoDBAsyncCreateTable
    \n\n" + + "Where:\n" + + " table - the table to create (i.e., Music3)\n\n" + + " key - the key for the table (i.e., Artist)\n" + + "Example:\n" + + " Music3 Artist \n"; + + if (args.length < 2) { + System.out.println(USAGE); + System.exit(1); + } + + /* Read the name from command args */ + String tableName = args[0]; + String key = args[1]; + + // Create the DynamoDbAsyncClient object + Region region = Region.US_EAST_1; + DynamoDbAsyncClient client = DynamoDbAsyncClient.builder() + .region(region) + .build(); + + createTable(client, tableName, key); + } + + // snippet-start:[dynamodb.java2.dbasync.table.main] + public static void createTable(DynamoDbAsyncClient client, String tableName, String key) { + + // Create a DynamoDbAsyncWaiter object + DynamoDbAsyncWaiter asyncWaiter = client.waiter(); + + // Create the CreateTableRequest object + CreateTableRequest request = CreateTableRequest.builder() + .attributeDefinitions(AttributeDefinition.builder() + .attributeName(key) + .attributeType(ScalarAttributeType.S) + .build()) + .keySchema(KeySchemaElement.builder() + .attributeName(key) + .keyType(KeyType.HASH) + .build()) + .provisionedThroughput(ProvisionedThroughput.builder() + .readCapacityUnits(new Long(10)) + .writeCapacityUnits(new Long(10)) + .build()) + .tableName(tableName) + .build(); + + // Create the table by using the DynamoDbAsyncClient object + CompletableFuture response = client.createTable(request); + + // When future is complete (either successfully or in error) handle the response + response.whenComplete((table, err) -> { + try { + if (table != null) { + + // Create a DescribeTableRequest object required for waiter functionality + DescribeTableRequest tableRequest = DescribeTableRequest.builder() + .tableName(table.tableDescription().tableName()) + .build(); + + CompletableFuture> waiterResponse = asyncWaiter + .waitUntilTableExists(tableRequest); + + // Fires when the table is ready + waiterResponse.whenComplete((r, t) -> { + + // print out the new table's ARN when its ready + String tableARN = r.matched().response().get().table().tableArn(); + System.out.println("The table " + tableARN + " is ready"); + + }); + waiterResponse.join(); + + } else { + // Handle error + err.printStackTrace(); + } + } finally { + // Lets the application shut down. Only close the client when you are completely + // done with it. + client.close(); + } + }); + response.join(); + } + // snippet-end:[dynamodb.java2.dbasync.table.main] +} diff --git a/javav2/example_code/dynamodbasync/src/main/java/com/example/dynamodbasync/DynamoDBAsyncGetItem.java b/javav2/example_code/dynamodbasync/src/main/java/com/example/dynamodbasync/DynamoDBAsyncGetItem.java index f4ba72200ba..9567bb9c21e 100644 --- a/javav2/example_code/dynamodbasync/src/main/java/com/example/dynamodbasync/DynamoDBAsyncGetItem.java +++ b/javav2/example_code/dynamodbasync/src/main/java/com/example/dynamodbasync/DynamoDBAsyncGetItem.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[DynamoDBAsyncGetItem.java demonstrates how to get an item by using the DynamoDbAsyncClient object] -//snippet-keyword:[SDK for Java 2.0] -//snippet-keyword:[Code Sample] -//snippet-service:[DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[8/7/2020] -//snippet-sourceauthor:[scmacdon-aws] - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * @@ -23,6 +16,7 @@ */ // snippet-start:[dynamodb.Java.DynamoDBAsyncGetItem.complete] package com.example.dynamodbasync; + // snippet-start:[dynamoasyn.java2.get_item.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; @@ -66,15 +60,14 @@ public static void main(String[] args) { .region(region) .build(); - System.out.format("Retrieving item \"%s\" from \"%s\"\n", keyVal, tableName ); + System.out.format("Retrieving item \"%s\" from \"%s\"\n", keyVal, tableName); getItem(client, tableName, key, keyVal); } // snippet-start:[dynamoasyc.java2.get_item.main] - public static void getItem(DynamoDbAsyncClient client, String tableName, String key, String keyVal) { + public static void getItem(DynamoDbAsyncClient client, String tableName, String key, String keyVal) { - HashMap keyToGet = - new HashMap(); + HashMap keyToGet = new HashMap(); keyToGet.put(key, AttributeValue.builder() .s(keyVal).build()); @@ -91,7 +84,8 @@ public static void getItem(DynamoDbAsyncClient client, String tableName, String java.util.Collection returnedItem = client.getItem(request).join().item().values(); // Convert Set to Map - Map map = returnedItem.stream().collect(Collectors.toMap(AttributeValue::s, s->s)); + Map map = returnedItem.stream() + .collect(Collectors.toMap(AttributeValue::s, s -> s)); Set keys = map.keySet(); for (String sinKey : keys) { System.out.format("%s: %s\n", sinKey, map.get(sinKey).toString()); diff --git a/javav2/example_code/dynamodbasync/src/main/java/com/example/dynamodbasync/DynamoDBAsyncListTables.java b/javav2/example_code/dynamodbasync/src/main/java/com/example/dynamodbasync/DynamoDBAsyncListTables.java index 968542b8eec..da0be08b292 100644 --- a/javav2/example_code/dynamodbasync/src/main/java/com/example/dynamodbasync/DynamoDBAsyncListTables.java +++ b/javav2/example_code/dynamodbasync/src/main/java/com/example/dynamodbasync/DynamoDBAsyncListTables.java @@ -1,24 +1,5 @@ -//snippet-sourcedescription:[DynamoDBAsyncListTables.java demonstrates how to use the asynchronous DynamoDB client to list tables.] -//snippet-keyword:[SDK for Java 2.0] -//snippet-keyword:[Code Sample] -//snippet-service:[DynamoDB] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[8/7/2020] -//snippet-sourceauthor:[scmacdon-aws] -/* - * Copyright 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. - * You may obtain a copy of the License at: - * - * http://aws.amazon.com/apache2.0 - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES - * OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and - * limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.dynamodbasync; // snippet-start:[dynamodb.java2.dbasync.complete] @@ -63,7 +44,8 @@ public static void listTables(DynamoDbAsyncClient client) { err.printStackTrace(); } } finally { - // Lets the application shut down. Only close the client when you are completely done with it. + // Lets the application shut down. Only close the client when you are completely + // done with it. client.close(); } }); diff --git a/javav2/example_code/dynamodbasync/src/test/java/DynamoDBAsyncTest.java b/javav2/example_code/dynamodbasync/src/test/java/DynamoDBAsyncTest.java index 3637c324135..805360eeda6 100644 --- a/javav2/example_code/dynamodbasync/src/test/java/DynamoDBAsyncTest.java +++ b/javav2/example_code/dynamodbasync/src/test/java/DynamoDBAsyncTest.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.dynamodbasync.DynamoDBAsyncCreateTable; import com.example.dynamodbasync.DynamoDBAsyncGetItem; import com.example.dynamodbasync.DynamoDBAsyncListTables; diff --git a/javav2/example_code/ec2/run_example.sh b/javav2/example_code/ec2/run_example.sh index c71f86b7d42..74bcaf43a5c 100755 --- a/javav2/example_code/ec2/run_example.sh +++ b/javav2/example_code/ec2/run_example.sh @@ -1,13 +1,15 @@ -#!/bin/bash -if [[ -z $* ]] ; then - echo 'Supply the name of one of the example classes as an argument.' - echo 'If there are arguments to the class, put them in quotes after the class name.' - exit 1 -fi -export CLASSPATH=target/sdk-ec2-examples-1.0.jar -export className=$1 -echo "## Running $className..." -shift -echo "## arguments $@..." -mvn exec:java -Dexec.mainClass="com.example.ec2.$className" -Dexec.args="$@" - +#!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +if [[ -z $* ]] ; then + echo 'Supply the name of one of the example classes as an argument.' + echo 'If there are arguments to the class, put them in quotes after the class name.' + exit 1 +fi +export CLASSPATH=target/sdk-ec2-examples-1.0.jar +export className=$1 +echo "## Running $className..." +shift +echo "## arguments $@..." +mvn exec:java -Dexec.mainClass="com.example.ec2.$className" -Dexec.args="$@" + diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/AllocateAddress.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/AllocateAddress.java index 70c2324b2ab..b6cc9dcd1cc 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/AllocateAddress.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/AllocateAddress.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[AllocateAddress.java demonstrates how to allocate an elastic IP address for an Amazon Elastic Compute Cloud (Amazon EC2) instance.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.ec2; // snippet-start:[ec2.java2.allocate_address.main] @@ -21,7 +16,8 @@ // snippet-end:[ec2.java2.allocate_address.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,12 +28,12 @@ public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - instanceId - An instance id value that you can obtain from the AWS Console.\s - """; + Where: + instanceId - An instance id value that you can obtain from the AWS Console.\s + """; if (args.length != 1) { System.out.println(usage); @@ -47,8 +43,8 @@ public static void main(String[] args) { String instanceId = args[0]; Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.println(getAllocateAddress(ec2, instanceId)); ec2.close(); @@ -57,15 +53,15 @@ public static void main(String[] args) { public static String getAllocateAddress(Ec2Client ec2, String instanceId) { try { AllocateAddressRequest allocateRequest = AllocateAddressRequest.builder() - .domain(DomainType.VPC) - .build(); + .domain(DomainType.VPC) + .build(); AllocateAddressResponse allocateResponse = ec2.allocateAddress(allocateRequest); String allocationId = allocateResponse.allocationId(); AssociateAddressRequest associateRequest = AssociateAddressRequest.builder() - .instanceId(instanceId) - .allocationId(allocationId) - .build(); + .instanceId(instanceId) + .allocationId(allocationId) + .build(); AssociateAddressResponse associateResponse = ec2.associateAddress(associateRequest); return associateResponse.associationId(); diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/CreateInstance.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/CreateInstance.java index 58564c4cd53..d3cf3abdd56 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/CreateInstance.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/CreateInstance.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[CreateInstance.java demonstrates how to create an Amazon Elastic Compute Cloud (Amazon EC2) instance.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.ec2; @@ -22,13 +16,15 @@ // snippet-end:[ec2.java2.create_instance.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * This code example requires an AMI value. You can learn more about this value by reading this documentation topic: + * This code example requires an AMI value. You can learn more about this value + * by reading this documentation topic: * * https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/AMIs.html */ @@ -36,13 +32,13 @@ public class CreateInstance { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - name - An instance name value that you can obtain from the AWS Console (for example, ami-xxxxxx5c8b987b1a0).\s - amiId - An Amazon Machine Image (AMI) value that you can obtain from the AWS Console (for example, i-xxxxxx2734106d0ab).\s - """; + Where: + name - An instance name value that you can obtain from the AWS Console (for example, ami-xxxxxx5c8b987b1a0).\s + amiId - An Amazon Machine Image (AMI) value that you can obtain from the AWS Console (for example, i-xxxxxx2734106d0ab).\s + """; if (args.length != 2) { System.out.println(usage); @@ -53,8 +49,8 @@ public static void main(String[] args) { String amiId = args[1]; Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); String instanceId = createEC2Instance(ec2, name, amiId); System.out.println("The Amazon EC2 Instance ID is " + instanceId); @@ -63,23 +59,23 @@ public static void main(String[] args) { public static String createEC2Instance(Ec2Client ec2, String name, String amiId) { RunInstancesRequest runRequest = RunInstancesRequest.builder() - .imageId(amiId) - .instanceType(InstanceType.T1_MICRO) - .maxCount(1) - .minCount(1) - .build(); + .imageId(amiId) + .instanceType(InstanceType.T1_MICRO) + .maxCount(1) + .minCount(1) + .build(); RunInstancesResponse response = ec2.runInstances(runRequest); String instanceId = response.instances().get(0).instanceId(); Tag tag = Tag.builder() - .key("Name") - .value(name) - .build(); + .key("Name") + .value(name) + .build(); CreateTagsRequest tagRequest = CreateTagsRequest.builder() - .resources(instanceId) - .tags(tag) - .build(); + .resources(instanceId) + .tags(tag) + .build(); try { ec2.createTags(tagRequest); diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/CreateKeyPair.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/CreateKeyPair.java index 16eec73ace0..326e916d62f 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/CreateKeyPair.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/CreateKeyPair.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[CreateKeyPair.java demonstrates how to create an Amazon Elastic Compute Cloud (Amazon EC2) key pair.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.ec2; // snippet-start:[ec2.java2.create_key_pair.main] @@ -17,7 +12,8 @@ // snippet-end:[ec2.java2.create_key_pair.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +24,12 @@ public class CreateKeyPair { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - keyName - A key pair name (for example, TestKeyPair).\s - """; + Where: + keyName - A key pair name (for example, TestKeyPair).\s + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +39,8 @@ public static void main(String[] args) { String keyName = args[0]; Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); createEC2KeyPair(ec2, keyName); ec2.close(); @@ -53,8 +49,8 @@ public static void main(String[] args) { public static void createEC2KeyPair(Ec2Client ec2, String keyName) { try { CreateKeyPairRequest request = CreateKeyPairRequest.builder() - .keyName(keyName) - .build(); + .keyName(keyName) + .build(); ec2.createKeyPair(request); System.out.printf("Successfully created key pair named %s", keyName); diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/CreateSecurityGroup.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/CreateSecurityGroup.java index dead5153091..d4b6d11995a 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/CreateSecurityGroup.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/CreateSecurityGroup.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[CreateSecurityGroup.java demonstrates how to create an Amazon Elastic Compute Cloud (Amazon EC2) Security Group.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.ec2; @@ -22,95 +17,95 @@ // snippet-end:[ec2.java2.create_security_group.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateSecurityGroup { - public static void main(String[] args) { - final String usage = """ - - Usage: - \s - - Where: - groupName - A group name (for example, TestKeyPair).\s - groupDesc - A group description (for example, TestKeyPair).\s - vpcId - A VPC ID that you can obtain from the AWS Management Console (for example, vpc-xxxxxf2f).\s - - """; - - if (args.length != 3) { - System.out.println(usage); - System.exit(1); + public static void main(String[] args) { + final String usage = """ + + Usage: + \s + + Where: + groupName - A group name (for example, TestKeyPair).\s + groupDesc - A group description (for example, TestKeyPair).\s + vpcId - A VPC ID that you can obtain from the AWS Management Console (for example, vpc-xxxxxf2f).\s + + """; + + if (args.length != 3) { + System.out.println(usage); + System.exit(1); + } + + String groupName = args[0]; + String groupDesc = args[1]; + String vpcId = args[2]; + + // snippet-start:[ec2.java2.create_security_group.client] + Region region = Region.US_EAST_1; + Ec2Client ec2 = Ec2Client.builder() + .region(region) + .build(); + // snippet-end:[ec2.java2.create_security_group.client] + + String id = createEC2SecurityGroup(ec2, groupName, groupDesc, vpcId); + System.out.printf("Successfully created Security Group with this ID %s", id); + ec2.close(); } - String groupName = args[0]; - String groupDesc = args[1]; - String vpcId = args[2]; - - // snippet-start:[ec2.java2.create_security_group.client] - Region region = Region.US_EAST_1; - Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); - // snippet-end:[ec2.java2.create_security_group.client] - - String id = createEC2SecurityGroup(ec2, groupName, groupDesc, vpcId); - System.out.printf("Successfully created Security Group with this ID %s", id); - ec2.close(); - } - - public static String createEC2SecurityGroup(Ec2Client ec2, String groupName, String groupDesc, String vpcId) { - try { - // snippet-start:[ec2.java2.create_security_group.create] - CreateSecurityGroupRequest createRequest = CreateSecurityGroupRequest.builder() - .groupName(groupName) - .description(groupDesc) - .vpcId(vpcId) - .build(); - - CreateSecurityGroupResponse resp = ec2.createSecurityGroup(createRequest); - // snippet-end:[ec2.java2.create_security_group.create] - - // snippet-start:[ec2.java2.create_security_group.config] - IpRange ipRange = IpRange.builder() - .cidrIp("0.0.0.0/0").build(); - - IpPermission ipPerm = IpPermission.builder() - .ipProtocol("tcp") - .toPort(80) - .fromPort(80) - .ipRanges(ipRange) - .build(); - - IpPermission ipPerm2 = IpPermission.builder() - .ipProtocol("tcp") - .toPort(22) - .fromPort(22) - .ipRanges(ipRange) - .build(); - - AuthorizeSecurityGroupIngressRequest authRequest = - AuthorizeSecurityGroupIngressRequest.builder() - .groupName(groupName) - .ipPermissions(ipPerm, ipPerm2) - .build(); - - AuthorizeSecurityGroupIngressResponse authResponse = - ec2.authorizeSecurityGroupIngress(authRequest); - System.out.printf("Successfully added ingress policy to Security Group %s", groupName); - return resp.groupId(); - - } catch (Ec2Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + public static String createEC2SecurityGroup(Ec2Client ec2, String groupName, String groupDesc, String vpcId) { + try { + // snippet-start:[ec2.java2.create_security_group.create] + CreateSecurityGroupRequest createRequest = CreateSecurityGroupRequest.builder() + .groupName(groupName) + .description(groupDesc) + .vpcId(vpcId) + .build(); + + CreateSecurityGroupResponse resp = ec2.createSecurityGroup(createRequest); + // snippet-end:[ec2.java2.create_security_group.create] + + // snippet-start:[ec2.java2.create_security_group.config] + IpRange ipRange = IpRange.builder() + .cidrIp("0.0.0.0/0").build(); + + IpPermission ipPerm = IpPermission.builder() + .ipProtocol("tcp") + .toPort(80) + .fromPort(80) + .ipRanges(ipRange) + .build(); + + IpPermission ipPerm2 = IpPermission.builder() + .ipProtocol("tcp") + .toPort(22) + .fromPort(22) + .ipRanges(ipRange) + .build(); + + AuthorizeSecurityGroupIngressRequest authRequest = AuthorizeSecurityGroupIngressRequest + .builder() + .groupName(groupName) + .ipPermissions(ipPerm, ipPerm2) + .build(); + + AuthorizeSecurityGroupIngressResponse authResponse = ec2 + .authorizeSecurityGroupIngress(authRequest); + System.out.printf("Successfully added ingress policy to Security Group %s", groupName); + return resp.groupId(); + + } catch (Ec2Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + return ""; } - return ""; - } } - // snippet-end:[ec2.java2.create_security_group.config] - // snippet-end:[ec2.java2.create_security_group.main] - +// snippet-end:[ec2.java2.create_security_group.config] +// snippet-end:[ec2.java2.create_security_group.main] diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/CreateVolume.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/CreateVolume.java index 356e87782c6..f71f5af06b2 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/CreateVolume.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/CreateVolume.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[CreateVolume.java demonstrates how to create an EBS volume.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.ec2; @@ -18,13 +12,15 @@ import software.amazon.awssdk.services.ec2.model.Ec2Exception; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * This code example requires an AMI value. You can learn more about this value by reading this documentation topic: + * This code example requires an AMI value. You can learn more about this value + * by reading this documentation topic: * * https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/AMIs.html */ @@ -32,18 +28,18 @@ public class CreateVolume { public static void main(String[] args) { Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); try { CreateVolumeRequest request = CreateVolumeRequest.builder() - .availabilityZone("us-east-1e") - .size(384) - .volumeType(VolumeType.GP3) - .build(); + .availabilityZone("us-east-1e") + .size(384) + .volumeType(VolumeType.GP3) + .build(); CreateVolumeResponse response = ec2.createVolume(request); - System.out.println("The ARN is "+response.outpostArn()); + System.out.println("The ARN is " + response.outpostArn()); ec2.close(); } catch (Ec2Exception e) { diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/DeleteKeyPair.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/DeleteKeyPair.java index 8f87c8fd61c..a8f9064c5f3 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/DeleteKeyPair.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/DeleteKeyPair.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DeleteKeyPair.java demonstrates how to delete an Amazon Elastic Compute Cloud (Amazon EC2) key pair.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.ec2; @@ -18,7 +12,8 @@ // snippet-end:[ec2.java2.delete_key_pair.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,11 +24,11 @@ public class DeleteKeyPair { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - keyPair - A key pair name (for example, TestKeyPair)."""; + Where: + keyPair - A key pair name (for example, TestKeyPair)."""; if (args.length != 1) { System.out.println(usage); @@ -43,8 +38,8 @@ public static void main(String[] args) { String keyPair = args[0]; Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); deleteKeys(ec2, keyPair); ec2.close(); @@ -53,8 +48,8 @@ public static void main(String[] args) { public static void deleteKeys(Ec2Client ec2, String keyPair) { try { DeleteKeyPairRequest request = DeleteKeyPairRequest.builder() - .keyName(keyPair) - .build(); + .keyName(keyPair) + .build(); ec2.deleteKeyPair(request); System.out.printf("Successfully deleted key pair named %s", keyPair); @@ -66,4 +61,3 @@ public static void deleteKeys(Ec2Client ec2, String keyPair) { } } // snippet-end:[ec2.java2.delete_key_pair.main] - diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/DeleteSecurityGroup.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/DeleteSecurityGroup.java index 1c3af3be54e..aa978a712f7 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/DeleteSecurityGroup.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/DeleteSecurityGroup.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[DeleteSecurityGroup.java demonstrates how to delete an Amazon Elastic Compute Cloud (Amazon EC2) Security Group.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.ec2; // snippet-start:[ec2.java2.delete_security_group.main] @@ -17,7 +12,8 @@ // snippet-end:[ec2.java2.delete_security_group.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,11 +23,11 @@ public class DeleteSecurityGroup { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - groupId - A security group id that you can obtain from the AWS Console (for example, sg-xxxxxx1c0b65785c3)."""; + Where: + groupId - A security group id that you can obtain from the AWS Console (for example, sg-xxxxxx1c0b65785c3)."""; if (args.length != 1) { System.out.println(usage); @@ -41,8 +37,8 @@ public static void main(String[] args) { String groupId = args[0]; Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); deleteEC2SecGroup(ec2, groupId); ec2.close(); @@ -51,8 +47,8 @@ public static void main(String[] args) { public static void deleteEC2SecGroup(Ec2Client ec2, String groupId) { try { DeleteSecurityGroupRequest request = DeleteSecurityGroupRequest.builder() - .groupId(groupId) - .build(); + .groupId(groupId) + .build(); ec2.deleteSecurityGroup(request); System.out.printf("Successfully deleted Security Group with id %s", groupId); diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeAccount.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeAccount.java index 37cf3dd9cfc..a08d066df33 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeAccount.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeAccount.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeAccount.java demonstrates how to get information about the Amazon Elastic Compute Cloud (Amazon EC2) account.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.ec2; @@ -18,7 +12,8 @@ // snippet-end:[ec2.java2.describe_account.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,8 +23,8 @@ public class DescribeAccount { public static void main(String[] args) { Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); describeEC2Account(ec2); System.out.print("Done"); @@ -40,12 +35,11 @@ public static void describeEC2Account(Ec2Client ec2) { try { DescribeAccountAttributesResponse accountResults = ec2.describeAccountAttributes(); accountResults.accountAttributes().forEach(attribute -> { - System.out.print("\n The name of the attribute is " + attribute.attributeName()); + System.out.print("\n The name of the attribute is " + attribute.attributeName()); - attribute.attributeValues().forEach(myValue -> - System.out.print("\n The value of the attribute is " + myValue.attributeValue())); - } - ); + attribute.attributeValues().forEach( + myValue -> System.out.print("\n The value of the attribute is " + myValue.attributeValue())); + }); } catch (Ec2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -53,4 +47,4 @@ public static void describeEC2Account(Ec2Client ec2) { } } } - // snippet-end:[ec2.java2.describe_account.main] +// snippet-end:[ec2.java2.describe_account.main] diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeAddresses.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeAddresses.java index 428d972b8a4..0faca7a9ce0 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeAddresses.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeAddresses.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[DescribeAddresses.java demonstrates how to get information about elastic IP addresses.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.ec2; // snippet-start:[ec2.java2.describe_addresses.main] @@ -18,7 +13,8 @@ // snippet-end:[ec2.java2.describe_addresses.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,25 +24,26 @@ public class DescribeAddresses { public static void main(String[] args) { Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); describeEC2Address(ec2); ec2.close(); } + public static void describeEC2Address(Ec2Client ec2) { try { DescribeAddressesResponse response = ec2.describeAddresses(); for (Address address : response.addresses()) { System.out.printf( - "Found address with public IP %s, " + - "domain %s, " + - "allocation id %s " + - "and NIC id %s", - address.publicIp(), - address.domain(), - address.allocationId(), - address.networkInterfaceId()); + "Found address with public IP %s, " + + "domain %s, " + + "allocation id %s " + + "and NIC id %s", + address.publicIp(), + address.domain(), + address.allocationId(), + address.networkInterfaceId()); } } catch (Ec2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeInstanceTags.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeInstanceTags.java index 7c089104610..b1980e4a1b8 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeInstanceTags.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeInstanceTags.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeInstanceTags.java demonstrates how to describe the specified tags for your Amazon Elastic Compute Cloud (Amazon EC2) resource.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.ec2; @@ -20,7 +14,8 @@ // snippet-end:[ec2.java2.describe_tags.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,12 +25,12 @@ public class DescribeInstanceTags { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - resourceId - The instance ID value that you can obtain from the AWS Management Console (for example, i-xxxxxx0913e05f482).\s - """; + Where: + resourceId - The instance ID value that you can obtain from the AWS Management Console (for example, i-xxxxxx0913e05f482).\s + """; if (args.length != 1) { System.out.println(usage); @@ -45,8 +40,8 @@ public static void main(String[] args) { String resourceId = args[0]; Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); describeEC2Tags(ec2, resourceId); ec2.close(); @@ -55,9 +50,9 @@ public static void main(String[] args) { public static void describeEC2Tags(Ec2Client ec2, String resourceId) { try { Filter filter = Filter.builder() - .name("resource-id") - .values(resourceId) - .build(); + .name("resource-id") + .values(resourceId) + .build(); DescribeTagsResponse response = ec2.describeTags(DescribeTagsRequest.builder().filters(filter).build()); response.tags().forEach(tag -> { @@ -71,5 +66,4 @@ public static void describeEC2Tags(Ec2Client ec2, String resourceId) { } } } - // snippet-end:[ec2.java2.describe_tags.main] - +// snippet-end:[ec2.java2.describe_tags.main] diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeInstances.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeInstances.java index 7bfde159156..98270a5926a 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeInstances.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeInstances.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[DescribeInstances.java demonstrates how to get information about all the Amazon Elastic Compute Cloud (Amazon EC2) Instances associated with an AWS account.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.ec2; // snippet-start:[ec2.java2.describe_instances.main] @@ -22,7 +17,8 @@ // snippet-end:[ec2.java2.describe_instances.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,20 +27,23 @@ public class DescribeInstances { // private static Global logger. private Logger logger = (Logger) LoggerFactory.getLogger(this.getClass()); + public static void main(String[] args) { Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); describeEC2Instances(ec2); ec2.close(); } + public static void describeEC2Instances(Ec2Client ec2) { String nextToken = null; try { do { - DescribeInstancesRequest request = DescribeInstancesRequest.builder().maxResults(6).nextToken(nextToken).build(); + DescribeInstancesRequest request = DescribeInstancesRequest.builder().maxResults(6).nextToken(nextToken) + .build(); DescribeInstancesResponse response = ec2.describeInstances(request); for (Reservation reservation : response.reservations()) { for (Instance instance : reservation.instances()) { diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeKeyPairs.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeKeyPairs.java index d02b0a64ee7..e1e46eb20c7 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeKeyPairs.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeKeyPairs.java @@ -1,10 +1,6 @@ -//snippet-sourcedescription:[DescribeKeyPairs.java demonstrates how to get information about all instance key pairs.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2]e] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.ec2; // snippet-start:[ec2.java2.describe_key_pairs.main] @@ -16,7 +12,8 @@ // snippet-end:[ec2.java2.describe_key_pairs.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -26,8 +23,8 @@ public class DescribeKeyPairs { public static void main(String[] args) { Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); describeEC2Keys(ec2); ec2.close(); @@ -37,11 +34,10 @@ public static void describeEC2Keys(Ec2Client ec2) { try { DescribeKeyPairsResponse response = ec2.describeKeyPairs(); response.keyPairs().forEach(keyPair -> System.out.printf( - "Found key pair with name %s " + - "and fingerprint %s", - keyPair.keyName(), - keyPair.keyFingerprint()) - ); + "Found key pair with name %s " + + "and fingerprint %s", + keyPair.keyName(), + keyPair.keyFingerprint())); } catch (Ec2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -49,4 +45,4 @@ public static void describeEC2Keys(Ec2Client ec2) { } } } - // snippet-end:[ec2.java2.describe_key_pairs.main] +// snippet-end:[ec2.java2.describe_key_pairs.main] diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeRegionsAndZones.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeRegionsAndZones.java index 0631cec481e..d171057a891 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeRegionsAndZones.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeRegionsAndZones.java @@ -1,10 +1,6 @@ -//snippet-sourcedescription:[DescribeRegionsAndZones.java demonstrates how to get information about all the Amazon Elastic Compute Cloud (Amazon EC2) Regions and Zones.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.ec2; // snippet-start:[ec2.java2.describe_region_and_zones.complete] @@ -19,7 +15,8 @@ // snippet-end:[ec2.java2.describe_region_and_zones.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,18 +27,19 @@ public static void main(String[] args) { // snippet-start:[ec2.java2.describe_region_and_zones.client] software.amazon.awssdk.regions.Region region = software.amazon.awssdk.regions.Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); // snippet-end:[ec2.java2.describe_region_and_zones.client] describeEC2RegionsAndZones(ec2); ec2.close(); } - public static void describeEC2RegionsAndZones( Ec2Client ec2) { + + public static void describeEC2RegionsAndZones(Ec2Client ec2) { // snippet-start:[ec2.java2.describe_region_and_zones.region] try { DescribeRegionsResponse regionsResponse = ec2.describeRegions(); - for(Region region : regionsResponse.regions()) { + for (Region region : regionsResponse.regions()) { System.out.printf( "Found Region %s " + "with endpoint %s", @@ -52,10 +50,9 @@ public static void describeEC2RegionsAndZones( Ec2Client ec2) { } // snippet-start:[ec2.java2.describe_region_and_zones.avail_zone] - DescribeAvailabilityZonesResponse zonesResponse = - ec2.describeAvailabilityZones(); + DescribeAvailabilityZonesResponse zonesResponse = ec2.describeAvailabilityZones(); - for(AvailabilityZone zone : zonesResponse.availabilityZones()) { + for (AvailabilityZone zone : zonesResponse.availabilityZones()) { System.out.printf( "Found Availability Zone %s " + "with status %s " + diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeReservedInstances.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeReservedInstances.java index f54d3fa4163..199e8cf02cd 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeReservedInstances.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeReservedInstances.java @@ -1,10 +1,6 @@ -//snippet-sourcedescription:[DescribeReservedInstances.java demonstrates how to get information about Amazon Elastic Compute Cloud (Amazon EC2) Reserved Instances.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.ec2; // snippet-start:[ec2.java2.describe_reserved_instances.main] @@ -18,7 +14,8 @@ // snippet-end:[ec2.java2.describe_reserved_instances.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,13 +25,13 @@ public class DescribeReservedInstances { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - instanceId - An instance id value that you can obtain from the AWS Console.\s + Where: + instanceId - An instance id value that you can obtain from the AWS Console.\s - """; + """; if (args.length != 1) { System.out.println(usage); @@ -44,8 +41,8 @@ public static void main(String[] args) { String instanceId = args[0]; Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); describeReservedEC2Instances(ec2, instanceId); ec2.close(); @@ -53,7 +50,8 @@ public static void main(String[] args) { public static void describeReservedEC2Instances(Ec2Client ec2, String instanceID) { try { - DescribeReservedInstancesRequest request = DescribeReservedInstancesRequest.builder().reservedInstancesIds(instanceID).build(); + DescribeReservedInstancesRequest request = DescribeReservedInstancesRequest.builder() + .reservedInstancesIds(instanceID).build(); DescribeReservedInstancesResponse response = ec2.describeReservedInstances(request); for (ReservedInstances instance : response.reservedInstances()) { System.out.printf( diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeSecurityGroups.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeSecurityGroups.java index c7e5ad37f8a..24a3eec9479 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeSecurityGroups.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeSecurityGroups.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeSecurityGroups.java demonstrates how to get information about all the Amazon Elastic Compute Cloud (Amazon EC2) Security Groups.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.ec2; @@ -20,7 +14,8 @@ // snippet-end:[ec2.java2.describe_security_groups.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,8 +23,7 @@ */ public class DescribeSecurityGroups { public static void main(String[] args) { - final String usage = - "To run this example, supply a group id\n" + + final String usage = "To run this example, supply a group id\n" + "Ex: DescribeSecurityGroups \n"; if (args.length != 1) { @@ -40,8 +34,8 @@ public static void main(String[] args) { String groupId = args[0]; Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); describeEC2SecurityGroups(ec2, groupId); ec2.close(); @@ -50,18 +44,18 @@ public static void main(String[] args) { public static void describeEC2SecurityGroups(Ec2Client ec2, String groupId) { try { DescribeSecurityGroupsRequest request = DescribeSecurityGroupsRequest.builder() - .groupIds(groupId) - .build(); + .groupIds(groupId) + .build(); DescribeSecurityGroupsResponse response = ec2.describeSecurityGroups(request); for (SecurityGroup group : response.securityGroups()) { System.out.printf( - "Found Security Group with id %s, " + - "vpc id %s " + - "and description %s", - group.groupId(), - group.vpcId(), - group.description()); + "Found Security Group with id %s, " + + "vpc id %s " + + "and description %s", + group.groupId(), + group.vpcId(), + group.description()); } } catch (Ec2Exception e) { @@ -70,5 +64,4 @@ public static void describeEC2SecurityGroups(Ec2Client ec2, String groupId) { } } } - // snippet-end:[ec2.java2.describe_security_groups.main] - +// snippet-end:[ec2.java2.describe_security_groups.main] diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeVPCs.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeVPCs.java index 546d20bc772..5d940060e4f 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeVPCs.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/DescribeVPCs.java @@ -1,10 +1,6 @@ -//snippet-sourcedescription:[DescribeVPCs.java demonstrates how to get information about all the Amazon Elastic Compute Cloud (Amazon EC2) VPCs.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.ec2; // snippet-start:[ec2.java2.describe_vpc.main] @@ -18,7 +14,8 @@ // snippet-end:[ec2.java2.describe_vpc.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +25,12 @@ public class DescribeVPCs { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - vpcId - A VPC ID that you can obtain from the AWS Management Console (for example, vpc-xxxxxf2f).\s - """; + Where: + vpcId - A VPC ID that you can obtain from the AWS Management Console (for example, vpc-xxxxxf2f).\s + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +40,8 @@ public static void main(String[] args) { String vpcId = args[0]; Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); describeEC2Vpcs(ec2, vpcId); ec2.close(); @@ -53,18 +50,18 @@ public static void main(String[] args) { public static void describeEC2Vpcs(Ec2Client ec2, String vpcId) { try { DescribeVpcsRequest request = DescribeVpcsRequest.builder() - .vpcIds(vpcId) - .build(); + .vpcIds(vpcId) + .build(); DescribeVpcsResponse response = ec2.describeVpcs(request); for (Vpc vpc : response.vpcs()) { System.out.printf( - "Found VPC with id %s, " + - "vpc state %s " + - "and tennancy %s", - vpc.vpcId(), - vpc.stateAsString(), - vpc.instanceTenancyAsString()); + "Found VPC with id %s, " + + "vpc state %s " + + "and tennancy %s", + vpc.vpcId(), + vpc.stateAsString(), + vpc.instanceTenancyAsString()); } } catch (Ec2Exception e) { @@ -74,4 +71,3 @@ public static void describeEC2Vpcs(Ec2Client ec2, String vpcId) { } } // snippet-end:[ec2.java2.describe_vpc.main] - diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/EC2Scenario.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/EC2Scenario.java index 0b8ac559a39..0d9cbdee858 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/EC2Scenario.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/EC2Scenario.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[EC2Scenario.java demonstrates how to get information about all the Amazon Elastic Compute Cloud (Amazon EC2) Instances associated with an AWS account.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.ec2; @@ -60,7 +54,8 @@ // snippet-start:[ec2.java2.scenario.main] /** - * Before running this Java (v2) code example, set up your development environment, including your credentials. + * Before running this Java (v2) code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -74,8 +69,10 @@ * 4. Displays security group information. * 5. Gets a list of Amazon Linux 2 AMIs and selects one. * 6. Gets more information about the image. - * 7. Gets a list of instance types that are compatible with the selected AMI’s architecture. - * 8. Creates an instance with the key pair, security group, AMI, and an instance type. + * 7. Gets a list of instance types that are compatible with the selected AMI’s + * architecture. + * 8. Creates an instance with the key pair, security group, AMI, and an + * instance type. * 9. Displays information about the instance. * 10. Stops the instance and waits for it to stop. * 11. Starts the instance and waits for it to start. @@ -88,22 +85,23 @@ */ public class EC2Scenario { public static final String DASHES = new String(new char[80]).replace("\0", "-"); + public static void main(String[] args) throws InterruptedException { final String usage = """ - Usage: - + Usage: + - Where: - keyName - A key pair name (for example, TestKeyPair).\s - fileName - A file name where the key information is written to.\s - groupName - The name of the security group.\s - groupDesc - The description of the security group.\s - vpcId - A VPC Id value. You can get this value from the AWS Management Console.\s - myIpAddress - The IP address of your development machine.\s + Where: + keyName - A key pair name (for example, TestKeyPair).\s + fileName - A file name where the key information is written to.\s + groupName - The name of the security group.\s + groupDesc - The description of the security group.\s + vpcId - A VPC Id value. You can get this value from the AWS Management Console.\s + myIpAddress - The IP address of your development machine.\s - """; + """; if (args.length != 6) { System.out.println(usage); @@ -119,12 +117,12 @@ public static void main(String[] args) throws InterruptedException { Region region = Region.US_WEST_2; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); SsmClient ssmClient = SsmClient.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.println(DASHES); System.out.println("Welcome to the Amazon EC2 example scenario."); @@ -153,7 +151,7 @@ public static void main(String[] args) throws InterruptedException { System.out.println(DASHES); System.out.println("5. Get a list of Amazon Linux 2 AMIs and selects one with amzn2 in the name."); String instanceId = getParaValues(ssmClient); - System.out.println("The instance Id is "+instanceId); + System.out.println("The instance Id is " + instanceId); System.out.println(DASHES); System.out.println(DASHES); @@ -168,15 +166,15 @@ public static void main(String[] args) throws InterruptedException { System.out.println(DASHES); System.out.println("8. Create an instance."); - String newInstanceId = runInstance(ec2, instanceType, keyName, groupName, amiValue ); - System.out.println("The instance Id is "+newInstanceId); + String newInstanceId = runInstance(ec2, instanceType, keyName, groupName, amiValue); + System.out.println("The instance Id is " + newInstanceId); System.out.println(DASHES); System.out.println(DASHES); System.out.println("9. Display information about the running instance. "); String ipAddress = describeEC2Instances(ec2, newInstanceId); System.out.println("You can SSH to the instance using this command:"); - System.out.println("ssh -i "+fileName +"ec2-user@"+ipAddress); + System.out.println("ssh -i " + fileName + "ec2-user@" + ipAddress); System.out.println(DASHES); System.out.println(DASHES); @@ -189,22 +187,22 @@ public static void main(String[] args) throws InterruptedException { startInstance(ec2, newInstanceId); ipAddress = describeEC2Instances(ec2, newInstanceId); System.out.println("You can SSH to the instance using this command:"); - System.out.println("ssh -i "+fileName +"ec2-user@"+ipAddress); + System.out.println("ssh -i " + fileName + "ec2-user@" + ipAddress); System.out.println(DASHES); System.out.println(DASHES); System.out.println("12. Allocate an Elastic IP address and associate it with the instance."); String allocationId = allocateAddress(ec2); - System.out.println("The allocation Id value is "+allocationId); + System.out.println("The allocation Id value is " + allocationId); String associationId = associateAddress(ec2, newInstanceId, allocationId); - System.out.println("The associate Id value is "+associationId); + System.out.println("The associate Id value is " + associationId); System.out.println(DASHES); System.out.println(DASHES); System.out.println("13. Describe the instance again."); ipAddress = describeEC2Instances(ec2, newInstanceId); System.out.println("You can SSH to the instance using this command:"); - System.out.println("ssh -i "+fileName +"ec2-user@"+ipAddress); + System.out.println("ssh -i " + fileName + "ec2-user@" + ipAddress); System.out.println(DASHES); System.out.println(DASHES); @@ -234,14 +232,14 @@ public static void main(String[] args) throws InterruptedException { ec2.close(); } - public static void deleteEC2SecGroup(Ec2Client ec2,String groupId) { + public static void deleteEC2SecGroup(Ec2Client ec2, String groupId) { try { DeleteSecurityGroupRequest request = DeleteSecurityGroupRequest.builder() - .groupId(groupId) - .build(); + .groupId(groupId) + .build(); ec2.deleteSecurityGroup(request); - System.out.println("Successfully deleted security group with Id " +groupId); + System.out.println("Successfully deleted security group with Id " + groupId); } catch (Ec2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -250,26 +248,27 @@ public static void deleteEC2SecGroup(Ec2Client ec2,String groupId) { } public static void terminateEC2(Ec2Client ec2, String instanceId) { - try{ + try { Ec2Waiter ec2Waiter = Ec2Waiter.builder() - .overrideConfiguration(b -> b.maxAttempts(100)) - .client(ec2) - .build(); + .overrideConfiguration(b -> b.maxAttempts(100)) + .client(ec2) + .build(); TerminateInstancesRequest ti = TerminateInstancesRequest.builder() - .instanceIds(instanceId) - .build(); + .instanceIds(instanceId) + .build(); System.out.println("Use an Ec2Waiter to wait for the instance to terminate. This will take a few minutes."); ec2.terminateInstances(ti); DescribeInstancesRequest instanceRequest = DescribeInstancesRequest.builder() - .instanceIds(instanceId) - .build(); + .instanceIds(instanceId) + .build(); - WaiterResponse waiterResponse = ec2Waiter.waitUntilInstanceTerminated(instanceRequest); + WaiterResponse waiterResponse = ec2Waiter + .waitUntilInstanceTerminated(instanceRequest); waiterResponse.matched().response().ifPresent(System.out::println); - System.out.println("Successfully started instance "+instanceId); - System.out.println(instanceId +" is terminated!"); + System.out.println("Successfully started instance " + instanceId); + System.out.println(instanceId + " is terminated!"); } catch (Ec2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -280,11 +279,11 @@ public static void terminateEC2(Ec2Client ec2, String instanceId) { public static void deleteKeys(Ec2Client ec2, String keyPair) { try { DeleteKeyPairRequest request = DeleteKeyPairRequest.builder() - .keyName(keyPair) - .build(); + .keyName(keyPair) + .build(); ec2.deleteKeyPair(request); - System.out.println("Successfully deleted key pair named "+keyPair); + System.out.println("Successfully deleted key pair named " + keyPair); } catch (Ec2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -292,14 +291,14 @@ public static void deleteKeys(Ec2Client ec2, String keyPair) { } } - public static void releaseEC2Address(Ec2Client ec2,String allocId) { + public static void releaseEC2Address(Ec2Client ec2, String allocId) { try { ReleaseAddressRequest request = ReleaseAddressRequest.builder() - .allocationId(allocId) - .build(); + .allocationId(allocId) + .build(); ec2.releaseAddress(request); - System.out.println("Successfully released Elastic IP address "+allocId); + System.out.println("Successfully released Elastic IP address " + allocId); } catch (Ec2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); @@ -310,8 +309,8 @@ public static void releaseEC2Address(Ec2Client ec2,String allocId) { public static void disassociateAddress(Ec2Client ec2, String associationId) { try { DisassociateAddressRequest addressRequest = DisassociateAddressRequest.builder() - .associationId(associationId) - .build(); + .associationId(associationId) + .build(); ec2.disassociateAddress(addressRequest); System.out.println("You successfully disassociated the address!"); @@ -327,9 +326,9 @@ public static void disassociateAddress(Ec2Client ec2, String associationId) { public static String associateAddress(Ec2Client ec2, String instanceId, String allocationId) { try { AssociateAddressRequest associateRequest = AssociateAddressRequest.builder() - .instanceId(instanceId) - .allocationId(allocationId) - .build(); + .instanceId(instanceId) + .allocationId(allocationId) + .build(); AssociateAddressResponse associateResponse = ec2.associateAddress(associateRequest); return associateResponse.associationId(); @@ -340,13 +339,13 @@ public static String associateAddress(Ec2Client ec2, String instanceId, String a } return ""; } - // snippet-end:[ec2.java2.associate_address.main] + // snippet-end:[ec2.java2.associate_address.main] public static String allocateAddress(Ec2Client ec2) { try { AllocateAddressRequest allocateRequest = AllocateAddressRequest.builder() - .domain(DomainType.VPC) - .build(); + .domain(DomainType.VPC) + .build(); AllocateAddressResponse allocateResponse = ec2.allocateAddress(allocateRequest); return allocateResponse.allocationId(); @@ -361,67 +360,69 @@ public static String allocateAddress(Ec2Client ec2) { // snippet-start:[ec2.java2.scenario.start_instance.main] public static void startInstance(Ec2Client ec2, String instanceId) { Ec2Waiter ec2Waiter = Ec2Waiter.builder() - .overrideConfiguration(b -> b.maxAttempts(100)) - .client(ec2) - .build(); + .overrideConfiguration(b -> b.maxAttempts(100)) + .client(ec2) + .build(); StartInstancesRequest request = StartInstancesRequest.builder() - .instanceIds(instanceId) - .build(); + .instanceIds(instanceId) + .build(); System.out.println("Use an Ec2Waiter to wait for the instance to run. This will take a few minutes."); ec2.startInstances(request); DescribeInstancesRequest instanceRequest = DescribeInstancesRequest.builder() - .instanceIds(instanceId) - .build(); + .instanceIds(instanceId) + .build(); WaiterResponse waiterResponse = ec2Waiter.waitUntilInstanceRunning(instanceRequest); waiterResponse.matched().response().ifPresent(System.out::println); - System.out.println("Successfully started instance "+instanceId); + System.out.println("Successfully started instance " + instanceId); } // snippet-end:[ec2.java2.scenario.start_instance.main] // snippet-start:[ec2.java2.scenario.stop_instance.main] public static void stopInstance(Ec2Client ec2, String instanceId) { Ec2Waiter ec2Waiter = Ec2Waiter.builder() - .overrideConfiguration(b -> b.maxAttempts(100)) - .client(ec2) - .build(); + .overrideConfiguration(b -> b.maxAttempts(100)) + .client(ec2) + .build(); StopInstancesRequest request = StopInstancesRequest.builder() - .instanceIds(instanceId) - .build(); + .instanceIds(instanceId) + .build(); System.out.println("Use an Ec2Waiter to wait for the instance to stop. This will take a few minutes."); ec2.stopInstances(request); DescribeInstancesRequest instanceRequest = DescribeInstancesRequest.builder() - .instanceIds(instanceId) - .build(); + .instanceIds(instanceId) + .build(); - WaiterResponse waiterResponse = ec2Waiter.waitUntilInstanceStopped(instanceRequest); - waiterResponse.matched().response().ifPresent(System.out::println); - System.out.println("Successfully stopped instance "+instanceId); + WaiterResponse waiterResponse = ec2Waiter.waitUntilInstanceStopped(instanceRequest); + waiterResponse.matched().response().ifPresent(System.out::println); + System.out.println("Successfully stopped instance " + instanceId); } // snippet-end:[ec2.java2.scenario.stop_instance.main] // snippet-start:[ec2.java2.scenario.describe_instance.main] - public static String describeEC2Instances( Ec2Client ec2, String newInstanceId) { + public static String describeEC2Instances(Ec2Client ec2, String newInstanceId) { try { String pubAddress = ""; boolean isRunning = false; DescribeInstancesRequest request = DescribeInstancesRequest.builder() - .instanceIds(newInstanceId) - .build(); + .instanceIds(newInstanceId) + .build(); while (!isRunning) { DescribeInstancesResponse response = ec2.describeInstances(request); String state = response.reservations().get(0).instances().get(0).state().name().name(); - if (state.compareTo("RUNNING") ==0) { - System.out.println("Image id is " + response.reservations().get(0).instances().get(0).imageId()); - System.out.println("Instance type is " + response.reservations().get(0).instances().get(0).instanceType()); - System.out.println("Instance state is " + response.reservations().get(0).instances().get(0).state().name()); - pubAddress = response.reservations().get(0).instances().get(0).publicIpAddress(); - System.out.println("Instance address is " + pubAddress); - isRunning = true; + if (state.compareTo("RUNNING") == 0) { + System.out.println("Image id is " + response.reservations().get(0).instances().get(0).imageId()); + System.out.println( + "Instance type is " + response.reservations().get(0).instances().get(0).instanceType()); + System.out.println( + "Instance state is " + response.reservations().get(0).instances().get(0).state().name()); + pubAddress = response.reservations().get(0).instances().get(0).publicIpAddress(); + System.out.println("Instance address is " + pubAddress); + isRunning = true; } } return pubAddress; @@ -433,20 +434,21 @@ public static String describeEC2Instances( Ec2Client ec2, String newInstanceId) } // snippet-end:[ec2.java2.scenario.describe_instance.main] - public static String runInstance(Ec2Client ec2, String instanceType, String keyName, String groupName, String amiId ) { + public static String runInstance(Ec2Client ec2, String instanceType, String keyName, String groupName, + String amiId) { try { RunInstancesRequest runRequest = RunInstancesRequest.builder() - .instanceType(instanceType) - .keyName(keyName) - .securityGroups(groupName) - .maxCount(1) - .minCount(1) - .imageId(amiId) - .build(); + .instanceType(instanceType) + .keyName(keyName) + .securityGroups(groupName) + .maxCount(1) + .minCount(1) + .imageId(amiId) + .build(); RunInstancesResponse response = ec2.runInstances(runRequest); String instanceId = response.instances().get(0).instanceId(); - System.out.println("Successfully started EC2 instance "+instanceId +" based on AMI "+amiId); + System.out.println("Successfully started EC2 instance " + instanceId + " based on AMI " + amiId); return instanceId; } catch (SsmException e) { @@ -459,25 +461,25 @@ public static String runInstance(Ec2Client ec2, String instanceType, String keyN // snippet-start:[ec2.java2.scenario.describe_instance.type.main] // Get a list of instance types. public static String getInstanceTypes(Ec2Client ec2) { - String instanceType=""; + String instanceType = ""; try { List filters = new ArrayList<>(); Filter filter = Filter.builder() - .name("processor-info.supported-architecture") - .values("arm64") - .build(); + .name("processor-info.supported-architecture") + .values("arm64") + .build(); filters.add(filter); DescribeInstanceTypesRequest typesRequest = DescribeInstanceTypesRequest.builder() - .filters(filters) - .maxResults(10) - .build(); + .filters(filters) + .maxResults(10) + .build(); DescribeInstanceTypesResponse response = ec2.describeInstanceTypes(typesRequest); List instanceTypes = response.instanceTypes(); - for (InstanceTypeInfo type: instanceTypes) { - System.out.println("The memory information of this type is "+type.memoryInfo().sizeInMiB()); - System.out.println("Network information is "+type.networkInfo().toString()); + for (InstanceTypeInfo type : instanceTypes) { + System.out.println("The memory information of this type is " + type.memoryInfo().sizeInMiB()); + System.out.println("Network information is " + type.networkInfo().toString()); instanceType = type.instanceType().toString(); } @@ -495,12 +497,12 @@ public static String getInstanceTypes(Ec2Client ec2) { public static String describeImage(Ec2Client ec2, String instanceId) { try { DescribeImagesRequest imagesRequest = DescribeImagesRequest.builder() - .imageIds(instanceId) - .build(); + .imageIds(instanceId) + .build(); DescribeImagesResponse response = ec2.describeImages(imagesRequest); - System.out.println("The description of the first image is "+response.images().get(0).description()); - System.out.println("The name of the first image is "+response.images().get(0).name()); + System.out.println("The description of the first image is " + response.images().get(0).description()); + System.out.println("The name of the first image is " + response.images().get(0).name()); // Return the image Id value. return response.images().get(0).imageId(); @@ -516,16 +518,16 @@ public static String describeImage(Ec2Client ec2, String instanceId) { public static String getParaValues(SsmClient ssmClient) { try { GetParametersByPathRequest parameterRequest = GetParametersByPathRequest.builder() - .path("/aws/service/ami-amazon-linux-latest") - .build(); + .path("/aws/service/ami-amazon-linux-latest") + .build(); GetParametersByPathIterable responses = ssmClient.getParametersByPathPaginator(parameterRequest); for (software.amazon.awssdk.services.ssm.model.GetParametersByPathResponse response : responses) { - System.out.println("Test "+response.nextToken()); + System.out.println("Test " + response.nextToken()); List parameterList = response.parameters(); - for (Parameter para: parameterList) { - System.out.println("The name of the para is: "+para.name()); - System.out.println("The type of the para is: "+para.type()); + for (Parameter para : parameterList) { + System.out.println("The name of the para is: " + para.name()); + System.out.println("The type of the para is: " + para.type()); if (filterName(para.name())) { return para.value(); } @@ -536,7 +538,7 @@ public static String getParaValues(SsmClient ssmClient) { System.err.println(e.getMessage()); System.exit(1); } - return "" ; + return ""; } // Return true if the name has amzn2 in it. For example: @@ -551,12 +553,13 @@ private static boolean filterName(String name) { public static void describeSecurityGroups(Ec2Client ec2, String groupId) { try { DescribeSecurityGroupsRequest request = DescribeSecurityGroupsRequest.builder() - .groupIds(groupId) - .build(); + .groupIds(groupId) + .build(); DescribeSecurityGroupsResponse response = ec2.describeSecurityGroups(request); - for(SecurityGroup group : response.securityGroups()) { - System.out.println( "Found Security Group with Id " +group.groupId() +" and group VPC "+ group.vpcId()); + for (SecurityGroup group : response.securityGroups()) { + System.out + .println("Found Security Group with Id " + group.groupId() + " and group VPC " + group.vpcId()); } } catch (Ec2Exception e) { @@ -567,40 +570,41 @@ public static void describeSecurityGroups(Ec2Client ec2, String groupId) { // snippet-end:[ec2.java2.scenario.describe_securitygroup.main] // snippet-start:[ec2.java.scenario_inbound_rule.main] - public static String createSecurityGroup(Ec2Client ec2,String groupName, String groupDesc, String vpcId, String myIpAddress) { + public static String createSecurityGroup(Ec2Client ec2, String groupName, String groupDesc, String vpcId, + String myIpAddress) { try { CreateSecurityGroupRequest createRequest = CreateSecurityGroupRequest.builder() - .groupName(groupName) - .description(groupDesc) - .vpcId(vpcId) - .build(); + .groupName(groupName) + .description(groupDesc) + .vpcId(vpcId) + .build(); - CreateSecurityGroupResponse resp= ec2.createSecurityGroup(createRequest); + CreateSecurityGroupResponse resp = ec2.createSecurityGroup(createRequest); IpRange ipRange = IpRange.builder() - .cidrIp(myIpAddress+"/0") - .build(); + .cidrIp(myIpAddress + "/0") + .build(); IpPermission ipPerm = IpPermission.builder() - .ipProtocol("tcp") - .toPort(80) - .fromPort(80) - .ipRanges(ipRange) - .build(); + .ipProtocol("tcp") + .toPort(80) + .fromPort(80) + .ipRanges(ipRange) + .build(); IpPermission ipPerm2 = IpPermission.builder() - .ipProtocol("tcp") - .toPort(22) - .fromPort(22) - .ipRanges(ipRange) - .build(); + .ipProtocol("tcp") + .toPort(22) + .fromPort(22) + .ipRanges(ipRange) + .build(); AuthorizeSecurityGroupIngressRequest authRequest = AuthorizeSecurityGroupIngressRequest.builder() - .groupName(groupName) - .ipPermissions(ipPerm, ipPerm2) - .build(); + .groupName(groupName) + .ipPermissions(ipPerm, ipPerm2) + .build(); ec2.authorizeSecurityGroupIngress(authRequest); - System.out.println("Successfully added ingress policy to security group "+groupName); + System.out.println("Successfully added ingress policy to security group " + groupName); return resp.groupId(); } catch (Ec2Exception e) { @@ -612,15 +616,14 @@ public static String createSecurityGroup(Ec2Client ec2,String groupName, String // snippet-end:[ec2.java.scenario_inbound_rule.main] // snippet-start:[ec2.java.scenario_describe_keys.main] - public static void describeKeys( Ec2Client ec2){ + public static void describeKeys(Ec2Client ec2) { try { DescribeKeyPairsResponse response = ec2.describeKeyPairs(); response.keyPairs().forEach(keyPair -> System.out.printf( - "Found key pair with name %s " + - "and fingerprint %s", - keyPair.keyName(), - keyPair.keyFingerprint()) - ); + "Found key pair with name %s " + + "and fingerprint %s", + keyPair.keyName(), + keyPair.keyFingerprint())); } catch (Ec2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -632,15 +635,15 @@ public static void describeKeys( Ec2Client ec2){ public static void createKeyPair(Ec2Client ec2, String keyName, String fileName) { try { CreateKeyPairRequest request = CreateKeyPairRequest.builder() - .keyName(keyName) - .build(); + .keyName(keyName) + .build(); CreateKeyPairResponse response = ec2.createKeyPair(request); String content = response.keyMaterial(); BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); writer.write(content); writer.close(); - System.out.println("Successfully created key pair named "+keyName); + System.out.println("Successfully created key pair named " + keyName); } catch (Ec2Exception | IOException e) { System.err.println(e.getMessage()); diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/FindRunningInstances.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/FindRunningInstances.java index e0bbff4ff62..305ef59f2e4 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/FindRunningInstances.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/FindRunningInstances.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -//snippet-sourcedescription:[FindRunningInstances.java demonstrates how to find running Amazon Elastic Compute Cloud (Amazon EC2) instances by using a filter.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.ec2; @@ -23,7 +16,8 @@ // snippet-end:[ec2.java2.running_instances.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -33,8 +27,8 @@ public class FindRunningInstances { public static void main(String[] args) { Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); findRunningEC2Instances(ec2); ec2.close(); @@ -45,13 +39,13 @@ public static void findRunningEC2Instances(Ec2Client ec2) { String nextToken; do { Filter filter = Filter.builder() - .name("instance-state-name") - .values("running") - .build(); + .name("instance-state-name") + .values("running") + .build(); DescribeInstancesRequest request = DescribeInstancesRequest.builder() - .filters(filter) - .build(); + .filters(filter) + .build(); DescribeInstancesResponse response = ec2.describeInstances(request); for (Reservation reservation : response.reservations()) { @@ -61,11 +55,11 @@ public static void findRunningEC2Instances(Ec2Client ec2) { "type %s, " + "state %s " + "and monitoring state %s", - instance.instanceId(), - instance.imageId(), - instance.instanceType(), - instance.state().name(), - instance.monitoring().state()); + instance.instanceId(), + instance.imageId(), + instance.instanceType(), + instance.state().name(), + instance.monitoring().state()); } } nextToken = response.nextToken(); diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/MonitorInstance.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/MonitorInstance.java index a89346f6651..fe3859e0674 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/MonitorInstance.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/MonitorInstance.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[MonitorInstance.java demonstrates how to toggle detailed monitoring for an Amazon Elastic Compute Cloud (Amazon EC2) instance.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.ec2; @@ -18,7 +12,8 @@ // snippet-end:[ec2.java2.monitor_instance.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,12 +24,12 @@ public class MonitorInstance { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - instanceId - An instance id value that you can obtain from the AWS Management Console.\s - monitor - A monitoring status (true|false)"""; + Where: + instanceId - An instance id value that you can obtain from the AWS Management Console.\s + monitor - A monitoring status (true|false)"""; if (args.length != 2) { System.out.println(usage); @@ -45,8 +40,8 @@ public static void main(String[] args) { boolean monitor = Boolean.parseBoolean(args[1]); Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); if (monitor) { monitorInstance(ec2, instanceId); @@ -58,8 +53,8 @@ public static void main(String[] args) { public static void monitorInstance(Ec2Client ec2, String instanceId) { MonitorInstancesRequest request = MonitorInstancesRequest.builder() - .instanceIds(instanceId) - .build(); + .instanceIds(instanceId) + .build(); ec2.monitorInstances(request); System.out.printf("Successfully enabled monitoring for instance %s", instanceId); @@ -69,8 +64,8 @@ public static void monitorInstance(Ec2Client ec2, String instanceId) { // snippet-start:[ec2.java2.monitor_instance.stop] public static void unmonitorInstance(Ec2Client ec2, String instanceId) { UnmonitorInstancesRequest request = UnmonitorInstancesRequest.builder() - .instanceIds(instanceId) - .build(); + .instanceIds(instanceId) + .build(); ec2.unmonitorInstances(request); System.out.printf("Successfully disabled monitoring for instance %s", instanceId); diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/RebootInstance.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/RebootInstance.java index d14856d7a19..dda36f7d2c4 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/RebootInstance.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/RebootInstance.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[RebootInstance.java demonstrates how to reboot an Amazon Elastic Compute Cloud (Amazon EC2) instance.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.ec2; // snippet-start:[ec2.java2.reboot_instance.main] @@ -17,7 +12,8 @@ // snippet-end:[ec2.java2.reboot_instance.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,12 +23,12 @@ public class RebootInstance { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - instanceId - An instance id value that you can obtain from the AWS Console.\s - """; + Where: + instanceId - An instance id value that you can obtain from the AWS Console.\s + """; if (args.length != 1) { System.out.println(usage); @@ -42,8 +38,8 @@ public static void main(String[] args) { String instanceId = args[0]; Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); rebootEC2Instance(ec2, instanceId); ec2.close(); @@ -52,8 +48,8 @@ public static void main(String[] args) { public static void rebootEC2Instance(Ec2Client ec2, String instanceId) { try { RebootInstancesRequest request = RebootInstancesRequest.builder() - .instanceIds(instanceId) - .build(); + .instanceIds(instanceId) + .build(); ec2.rebootInstances(request); System.out.printf("Successfully rebooted instance %s", instanceId); @@ -65,5 +61,3 @@ public static void rebootEC2Instance(Ec2Client ec2, String instanceId) { } } // snippet-end:[ec2.java2.reboot_instance.main] - - diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/ReleaseAddress.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/ReleaseAddress.java index 625aa86ca07..9735eb65a72 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/ReleaseAddress.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/ReleaseAddress.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[ReleaseAddress.java demonstrates how to release an elastic IP address.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.ec2; // snippet-start:[ec2.java2.release_instance.main] @@ -17,7 +12,8 @@ // snippet-end:[ec2.java2.release_instance.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,13 +23,13 @@ public class ReleaseAddress { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - allocId - An allocation ID value that you can obtain from the AWS Console.\s + Where: + allocId - An allocation ID value that you can obtain from the AWS Console.\s - """; + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +39,8 @@ public static void main(String[] args) { String allocId = args[0]; Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); releaseEC2Address(ec2, allocId); ec2.close(); @@ -53,8 +49,8 @@ public static void main(String[] args) { public static void releaseEC2Address(Ec2Client ec2, String allocId) { try { ReleaseAddressRequest request = ReleaseAddressRequest.builder() - .allocationId(allocId) - .build(); + .allocationId(allocId) + .build(); ec2.releaseAddress(request); System.out.printf("Successfully released elastic IP address %s", allocId); diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/StartStopInstance.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/StartStopInstance.java index 8a4b37e3fd3..2fa06f09bd1 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/StartStopInstance.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/StartStopInstance.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[StartStopInstance.java demonstrates how to start and stop an Amazon Elastic Compute Cloud (Amazon EC2) instance.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.ec2; // snippet-start:[ec2.java2.start_stop_instance.import] @@ -16,7 +11,8 @@ // snippet-end:[ec2.java2.start_stop_instance.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -26,13 +22,13 @@ public class StartStopInstance { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - instanceId - an instance id value that you can obtain from the AWS Console.\s + Where: + instanceId - an instance id value that you can obtain from the AWS Console.\s - """; + """; if (args.length != 1) { System.out.println(usage); @@ -44,8 +40,8 @@ public static void main(String[] args) { Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); if (args[1].equals("start")) { start = true; @@ -64,8 +60,8 @@ public static void main(String[] args) { // snippet-start:[ec2.java2.start_stop_instance.start] public static void startInstance(Ec2Client ec2, String instanceId) { StartInstancesRequest request = StartInstancesRequest.builder() - .instanceIds(instanceId) - .build(); + .instanceIds(instanceId) + .build(); ec2.startInstances(request); System.out.printf("Successfully started instance %s", instanceId); @@ -75,8 +71,8 @@ public static void startInstance(Ec2Client ec2, String instanceId) { // snippet-start:[ec2.java2.start_stop_instance.stop] public static void stopInstance(Ec2Client ec2, String instanceId) { StopInstancesRequest request = StopInstancesRequest.builder() - .instanceIds(instanceId) - .build(); + .instanceIds(instanceId) + .build(); ec2.stopInstances(request); System.out.printf("Successfully stopped instance %s", instanceId); diff --git a/javav2/example_code/ec2/src/main/java/com/example/ec2/TerminateInstance.java b/javav2/example_code/ec2/src/main/java/com/example/ec2/TerminateInstance.java index e9e8bf6b96c..35bc6658034 100644 --- a/javav2/example_code/ec2/src/main/java/com/example/ec2/TerminateInstance.java +++ b/javav2/example_code/ec2/src/main/java/com/example/ec2/TerminateInstance.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[TerminateInstance.java demonstrates how to terminate an Amazon Elastic Compute Cloud (Amazon EC2) instance.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EC2] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.ec2; // snippet-start:[ec2.java2.terminate_instance] @@ -20,7 +15,8 @@ // snippet-end:[ec2.java2.terminate_instance.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,12 +26,12 @@ public class TerminateInstance { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - instanceId - An instance id value that you can obtain from the AWS Console.\s - """; + Where: + instanceId - An instance id value that you can obtain from the AWS Console.\s + """; if (args.length != 1) { System.out.println(usage); @@ -45,8 +41,8 @@ public static void main(String[] args) { String instanceId = args[0]; Region region = Region.US_EAST_1; Ec2Client ec2 = Ec2Client.builder() - .region(region) - .build(); + .region(region) + .build(); terminateEC2(ec2, instanceId); ec2.close(); @@ -55,8 +51,8 @@ public static void main(String[] args) { public static void terminateEC2(Ec2Client ec2, String instanceID) { try { TerminateInstancesRequest ti = TerminateInstancesRequest.builder() - .instanceIds(instanceID) - .build(); + .instanceIds(instanceID) + .build(); TerminateInstancesResponse response = ec2.terminateInstances(ti); List list = response.terminatingInstances(); diff --git a/javav2/example_code/ec2/src/test/java/EC2Test.java b/javav2/example_code/ec2/src/test/java/EC2Test.java index e575885acd1..fa5056d2ddf 100644 --- a/javav2/example_code/ec2/src/test/java/EC2Test.java +++ b/javav2/example_code/ec2/src/test/java/EC2Test.java @@ -1,7 +1,6 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + import com.example.ec2.*; import com.google.gson.Gson; import org.junit.jupiter.api.*; @@ -12,7 +11,7 @@ import java.io.*; import java.util.concurrent.TimeUnit; -import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; @@ -26,37 +25,37 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class EC2Test { - private static Ec2Client ec2; + private static Ec2Client ec2; private static SsmClient ssmClient; // Define the data members required for the tests. private static String instanceId = ""; // gets set in test 2. - private static String ami=""; - private static String instanceName=""; - private static String keyName=""; - private static String groupName=""; - private static String groupDesc=""; - private static String groupId=""; - private static String vpcId=""; - private static String keyNameSc=""; - private static String fileNameSc=""; - private static String groupDescSc=""; - private static String groupNameSc=""; - private static String vpcIdSc=""; - private static String myIpAddressSc=""; + private static String ami = ""; + private static String instanceName = ""; + private static String keyName = ""; + private static String groupName = ""; + private static String groupDesc = ""; + private static String groupId = ""; + private static String vpcId = ""; + private static String keyNameSc = ""; + private static String fileNameSc = ""; + private static String groupDescSc = ""; + private static String groupNameSc = ""; + private static String vpcIdSc = ""; + private static String myIpAddressSc = ""; @BeforeAll public static void setUp() throws IOException { Region region = Region.US_WEST_2; ec2 = Ec2Client.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); ssmClient = SsmClient.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -65,49 +64,51 @@ public static void setUp() throws IOException { ami = values.getAmi(); instanceName = values.getInstanceName(); keyName = values.getKeyNameSc(); - groupName= values.getGroupName(); - groupDesc= values.getGroupDesc(); - vpcId= values.getVpcId(); - keyNameSc= values.getKeyNameSc() + java.util.UUID.randomUUID(); - fileNameSc= values.getFileNameSc(); - groupDescSc= values.getGroupDescSc(); - groupNameSc= values.getGroupDescSc()+ java.util.UUID.randomUUID(); - vpcIdSc= values.getVpcIdSc(); - myIpAddressSc= values.getMyIpAddressSc(); - - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - try (InputStream input = EC2Test.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - prop.load(input); - ami = prop.getProperty("ami"); - instanceName = prop.getProperty("instanceName"); - keyName = prop.getProperty("keyPair")+ java.util.UUID.randomUUID(); - groupName= prop.getProperty("groupName")+ java.util.UUID.randomUUID();; - groupDesc= prop.getProperty("groupDesc"); - vpcId= prop.getProperty("vpcId"); - keyNameSc= prop.getProperty("keyNameSc")+ java.util.UUID.randomUUID(); - fileNameSc= prop.getProperty("fileNameSc"); - groupDescSc= prop.getProperty("groupDescSc"); - groupNameSc= prop.getProperty("groupNameSc")+ java.util.UUID.randomUUID();; - vpcIdSc= prop.getProperty("vpcIdSc"); - myIpAddressSc= prop.getProperty("myIpAddressSc"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + groupName = values.getGroupName(); + groupDesc = values.getGroupDesc(); + vpcId = values.getVpcId(); + keyNameSc = values.getKeyNameSc() + java.util.UUID.randomUUID(); + fileNameSc = values.getFileNameSc(); + groupDescSc = values.getGroupDescSc(); + groupNameSc = values.getGroupDescSc() + java.util.UUID.randomUUID(); + vpcIdSc = values.getVpcIdSc(); + myIpAddressSc = values.getMyIpAddressSc(); + + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * try (InputStream input = + * EC2Test.class.getClassLoader().getResourceAsStream("config.properties")) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * prop.load(input); + * ami = prop.getProperty("ami"); + * instanceName = prop.getProperty("instanceName"); + * keyName = prop.getProperty("keyPair")+ java.util.UUID.randomUUID(); + * groupName= prop.getProperty("groupName")+ java.util.UUID.randomUUID();; + * groupDesc= prop.getProperty("groupDesc"); + * vpcId= prop.getProperty("vpcId"); + * keyNameSc= prop.getProperty("keyNameSc")+ java.util.UUID.randomUUID(); + * fileNameSc= prop.getProperty("fileNameSc"); + * groupDescSc= prop.getProperty("groupDescSc"); + * groupNameSc= prop.getProperty("groupNameSc")+ java.util.UUID.randomUUID();; + * vpcIdSc= prop.getProperty("vpcIdSc"); + * myIpAddressSc= prop.getProperty("myIpAddressSc"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @Tag("IntegrationTest") @Order(1) public void CreateInstance() { - instanceId = CreateInstance.createEC2Instance(ec2,instanceName,ami); + instanceId = CreateInstance.createEC2Instance(ec2, instanceName, ami); assertFalse(instanceId.isEmpty()); System.out.println("\n Test 1 passed"); } @@ -116,7 +117,7 @@ public void CreateInstance() { @Tag("IntegrationTest") @Order(2) public void CreateKeyPair() { - assertDoesNotThrow(() ->CreateKeyPair.createEC2KeyPair(ec2, keyName)); + assertDoesNotThrow(() -> CreateKeyPair.createEC2KeyPair(ec2, keyName)); System.out.println("\n Test 2 passed"); } @@ -124,7 +125,7 @@ public void CreateKeyPair() { @Tag("IntegrationTest") @Order(3) public void DescribeKeyPair() { - assertDoesNotThrow(() ->DescribeKeyPairs.describeEC2Keys(ec2)); + assertDoesNotThrow(() -> DescribeKeyPairs.describeEC2Keys(ec2)); System.out.println("Test 3 passed"); } @@ -132,7 +133,7 @@ public void DescribeKeyPair() { @Tag("IntegrationTest") @Order(4) public void DeleteKeyPair() { - assertDoesNotThrow(() -> DeleteKeyPair.deleteKeys(ec2,keyName)); + assertDoesNotThrow(() -> DeleteKeyPair.deleteKeys(ec2, keyName)); System.out.println("\n Test 4 passed"); } @@ -140,28 +141,27 @@ public void DeleteKeyPair() { @Tag("IntegrationTest") @Order(5) public void CreateSecurityGroup() { - groupId = CreateSecurityGroup.createEC2SecurityGroup(ec2,groupName,groupDesc,vpcId); + groupId = CreateSecurityGroup.createEC2SecurityGroup(ec2, groupName, groupDesc, vpcId); assertFalse(groupId.isEmpty()); System.out.println("\n Test 5 passed"); - } + } @Test @Tag("IntegrationTest") @Order(6) public void DescribeSecurityGroup() { - assertDoesNotThrow(() -> DescribeSecurityGroups.describeEC2SecurityGroups(ec2,groupId)); + assertDoesNotThrow(() -> DescribeSecurityGroups.describeEC2SecurityGroups(ec2, groupId)); System.out.println("\n Test 6 passed"); } @Test @Tag("IntegrationTest") @Order(7) - public void DeleteSecurityGroup(){ + public void DeleteSecurityGroup() { assertDoesNotThrow(() -> DeleteSecurityGroup.deleteEC2SecGroup(ec2, groupId)); System.out.println("\n Test 7 passed"); } - @Test @Tag("IntegrationTest") @Order(8) @@ -181,7 +181,7 @@ public void DescribeInstances() { @Test @Tag("IntegrationTest") @Order(10) - public void DescribeRegionsAndZones () { + public void DescribeRegionsAndZones() { assertDoesNotThrow(() -> DescribeRegionsAndZones.describeEC2RegionsAndZones(ec2)); System.out.println("\n Test 10 passed"); } @@ -189,18 +189,18 @@ public void DescribeRegionsAndZones () { @Test @Tag("IntegrationTest") @Order(11) - public void DescribeVPCs () { - assertDoesNotThrow(() -> DescribeVPCs.describeEC2Vpcs(ec2,vpcId)); + public void DescribeVPCs() { + assertDoesNotThrow(() -> DescribeVPCs.describeEC2Vpcs(ec2, vpcId)); System.out.println("\n Test 11 passed"); } @Test @Tag("IntegrationTest") @Order(12) - public void FindRunningInstances() { + public void FindRunningInstances() { assertDoesNotThrow(() -> FindRunningInstances.findRunningEC2Instances(ec2)); System.out.println("\n Test 12 passed"); - } + } @Test @Tag("IntegrationTest") @@ -213,15 +213,15 @@ public void DescribeAddressed() { @Test @Tag("IntegrationTest") @Order(14) - public void TerminateInstance() { - assertDoesNotThrow(() -> TerminateInstance.terminateEC2(ec2, instanceId)); - System.out.println("\n Test 14 passed"); - } + public void TerminateInstance() { + assertDoesNotThrow(() -> TerminateInstance.terminateEC2(ec2, instanceId)); + System.out.println("\n Test 14 passed"); + } @Test @Tag("IntegrationTest") @Order(15) - public void TestEC2Scenario() throws InterruptedException { + public void TestEC2Scenario() throws InterruptedException { System.out.println(EC2Scenario.DASHES); System.out.println("1. Create an RSA key pair and save the private key material as a .pem file."); EC2Scenario.createKeyPair(ec2, keyNameSc, fileNameSc); @@ -234,7 +234,7 @@ public void TestEC2Scenario() throws InterruptedException { System.out.println(EC2Scenario.DASHES); System.out.println("3. Create a security group."); - String groupId = EC2Scenario.createSecurityGroup(ec2, groupNameSc, groupDescSc, vpcIdSc,myIpAddressSc); + String groupId = EC2Scenario.createSecurityGroup(ec2, groupNameSc, groupDescSc, vpcIdSc, myIpAddressSc); assertFalse(groupId.isEmpty()); System.out.println(EC2Scenario.DASHES); @@ -247,7 +247,7 @@ public void TestEC2Scenario() throws InterruptedException { System.out.println("5. Get a list of Amazon Linux 2 AMIs and select one with amzn2 in the name."); String instanceId = EC2Scenario.getParaValues(ssmClient); assertFalse(instanceId.isEmpty()); - System.out.println("The instance Id is "+instanceId); + System.out.println("The instance Id is " + instanceId); System.out.println(EC2Scenario.DASHES); System.out.println(EC2Scenario.DASHES); @@ -262,15 +262,15 @@ public void TestEC2Scenario() throws InterruptedException { assertFalse(instanceType.isEmpty()); if (instanceType.compareTo("x2gd.metal") != 0) instanceType = "x2gd.metal"; - System.out.println("*** The instance type is "+instanceType); + System.out.println("*** The instance type is " + instanceType); System.out.println(EC2Scenario.DASHES); System.out.println(EC2Scenario.DASHES); - System.out.println("Wait 1 min before creating the instance using "+ instanceType); + System.out.println("Wait 1 min before creating the instance using " + instanceType); TimeUnit.MINUTES.sleep(1); System.out.println("8. Create an instance."); - String newInstanceId = EC2Scenario.runInstance(ec2, instanceType, keyNameSc, groupNameSc, amiValue ); - System.out.println("The instance Id is "+newInstanceId); + String newInstanceId = EC2Scenario.runInstance(ec2, instanceType, keyNameSc, groupNameSc, amiValue); + System.out.println("The instance Id is " + newInstanceId); System.out.println(EC2Scenario.DASHES); System.out.println(EC2Scenario.DASHES); @@ -278,7 +278,7 @@ public void TestEC2Scenario() throws InterruptedException { String ipAddress = EC2Scenario.describeEC2Instances(ec2, newInstanceId); assertFalse(ipAddress.isEmpty()); System.out.println("You can SSH to the instance using this command:"); - System.out.println("ssh -i "+fileNameSc +"ec2-user@"+ipAddress); + System.out.println("ssh -i " + fileNameSc + "ec2-user@" + ipAddress); System.out.println(EC2Scenario.DASHES); System.out.println(EC2Scenario.DASHES); @@ -292,16 +292,16 @@ public void TestEC2Scenario() throws InterruptedException { ipAddress = EC2Scenario.describeEC2Instances(ec2, newInstanceId); assertFalse(ipAddress.isEmpty()); System.out.println("You can SSH to the instance using this command:"); - System.out.println("ssh -i "+fileNameSc +"ec2-user@"+ipAddress); + System.out.println("ssh -i " + fileNameSc + "ec2-user@" + ipAddress); System.out.println(EC2Scenario.DASHES); System.out.println(EC2Scenario.DASHES); System.out.println("12. Allocate an Elastic IP address and associate it with the instance."); String allocationId = EC2Scenario.allocateAddress(ec2); assertFalse(allocationId.isEmpty()); - System.out.println("The allocation Id value is "+allocationId); + System.out.println("The allocation Id value is " + allocationId); String associationId = EC2Scenario.associateAddress(ec2, newInstanceId, allocationId); - System.out.println("The association Id value is "+associationId); + System.out.println("The association Id value is " + associationId); System.out.println(EC2Scenario.DASHES); System.out.println(EC2Scenario.DASHES); @@ -309,7 +309,7 @@ public void TestEC2Scenario() throws InterruptedException { ipAddress = EC2Scenario.describeEC2Instances(ec2, newInstanceId); assertFalse(ipAddress.isEmpty()); System.out.println("You can SSH to the instance using this command:"); - System.out.println("ssh -i "+fileNameSc +"ec2-user@"+ipAddress); + System.out.println("ssh -i " + fileNameSc + "ec2-user@" + ipAddress); System.out.println(EC2Scenario.DASHES); System.out.println(EC2Scenario.DASHES); @@ -334,16 +334,17 @@ public void TestEC2Scenario() throws InterruptedException { System.out.println(EC2Scenario.DASHES); System.out.println("\n Test 16 passed"); } + private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/ec2"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -422,4 +423,3 @@ public String getMyIpAddressSc() { } } } - diff --git a/javav2/example_code/ecs/src/main/java/com/example/ecs/CreateCluster.java b/javav2/example_code/ecs/src/main/java/com/example/ecs/CreateCluster.java index 0dbcb4509b0..2905a940f24 100644 --- a/javav2/example_code/ecs/src/main/java/com/example/ecs/CreateCluster.java +++ b/javav2/example_code/ecs/src/main/java/com/example/ecs/CreateCluster.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[CreateCluster.java demonstrates how to create a cluster for the Amazon Elastic Container Service (Amazon ECS) service.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Elastic Container Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.ecs; @@ -22,7 +16,8 @@ // snippet-end:[ecs.java2.create_cluster.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,12 +27,12 @@ public class CreateCluster { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - clusterName - The name of the ECS cluster to create. - """; + Where: + clusterName - The name of the ECS cluster to create. + """; if (args.length != 1) { System.out.println(usage); @@ -47,8 +42,8 @@ public static void main(String[] args) { String clusterName = args[0]; Region region = Region.US_EAST_1; EcsClient ecsClient = EcsClient.builder() - .region(region) - .build(); + .region(region) + .build(); String clusterArn = createGivenCluster(ecsClient, clusterName); System.out.println("The cluster ARN is " + clusterArn); @@ -58,17 +53,17 @@ public static void main(String[] args) { public static String createGivenCluster(EcsClient ecsClient, String clusterName) { try { ExecuteCommandConfiguration commandConfiguration = ExecuteCommandConfiguration.builder() - .logging(ExecuteCommandLogging.DEFAULT) - .build(); + .logging(ExecuteCommandLogging.DEFAULT) + .build(); ClusterConfiguration clusterConfiguration = ClusterConfiguration.builder() - .executeCommandConfiguration(commandConfiguration) - .build(); + .executeCommandConfiguration(commandConfiguration) + .build(); CreateClusterRequest clusterRequest = CreateClusterRequest.builder() - .clusterName(clusterName) - .configuration(clusterConfiguration) - .build(); + .clusterName(clusterName) + .configuration(clusterConfiguration) + .build(); CreateClusterResponse response = ecsClient.createCluster(clusterRequest); return response.cluster().clusterArn(); diff --git a/javav2/example_code/ecs/src/main/java/com/example/ecs/CreateService.java b/javav2/example_code/ecs/src/main/java/com/example/ecs/CreateService.java index 1b4d5a075c1..81cfdb92cc5 100644 --- a/javav2/example_code/ecs/src/main/java/com/example/ecs/CreateService.java +++ b/javav2/example_code/ecs/src/main/java/com/example/ecs/CreateService.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[CreateService.java demonstrates how to create a service for the Amazon Elastic Container Service (Amazon ECS) service.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Elastic Container Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.ecs; @@ -22,81 +16,83 @@ // snippet-end:[ecs.java2.create_service.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateService { - public static void main(String[] args) { - final String usage = """ + public static void main(String[] args) { + final String usage = """ - Usage: - + Usage: + - Where: - clusterName - The name of the ECS cluster. - serviceName - The name of the ECS service to create. - securityGroups - The name of the security group. - subnets - The name of the subnet. - taskDefinition - The name of the task definition. - """; + Where: + clusterName - The name of the ECS cluster. + serviceName - The name of the ECS service to create. + securityGroups - The name of the security group. + subnets - The name of the subnet. + taskDefinition - The name of the task definition. + """; - if (args.length != 5) { - System.out.println(usage); - System.exit(1); - } + if (args.length != 5) { + System.out.println(usage); + System.exit(1); + } - String clusterName = args[0]; - String serviceName = args[1]; - String securityGroups = args[2]; - String subnets = args[3]; - String taskDefinition = args[4]; - Region region = Region.US_EAST_1; - EcsClient ecsClient = EcsClient.builder() - .region(region) - .build(); + String clusterName = args[0]; + String serviceName = args[1]; + String securityGroups = args[2]; + String subnets = args[3]; + String taskDefinition = args[4]; + Region region = Region.US_EAST_1; + EcsClient ecsClient = EcsClient.builder() + .region(region) + .build(); - String serviceArn = createNewService(ecsClient, clusterName, serviceName, securityGroups, subnets, taskDefinition); - System.out.println("The ARN of the service is " + serviceArn); - ecsClient.close(); - } + String serviceArn = createNewService(ecsClient, clusterName, serviceName, securityGroups, subnets, + taskDefinition); + System.out.println("The ARN of the service is " + serviceArn); + ecsClient.close(); + } - public static String createNewService(EcsClient ecsClient, - String clusterName, - String serviceName, - String securityGroups, - String subnets, - String taskDefinition) { + public static String createNewService(EcsClient ecsClient, + String clusterName, + String serviceName, + String securityGroups, + String subnets, + String taskDefinition) { - try { - AwsVpcConfiguration vpcConfiguration = AwsVpcConfiguration.builder() - .securityGroups(securityGroups) - .subnets(subnets) - .build(); + try { + AwsVpcConfiguration vpcConfiguration = AwsVpcConfiguration.builder() + .securityGroups(securityGroups) + .subnets(subnets) + .build(); - NetworkConfiguration configuration = NetworkConfiguration.builder() - .awsvpcConfiguration(vpcConfiguration) - .build(); + NetworkConfiguration configuration = NetworkConfiguration.builder() + .awsvpcConfiguration(vpcConfiguration) + .build(); - CreateServiceRequest serviceRequest = CreateServiceRequest.builder() - .cluster(clusterName) - .networkConfiguration(configuration) - .desiredCount(1) - .launchType(LaunchType.FARGATE) - .serviceName(serviceName) - .taskDefinition(taskDefinition) - .build(); + CreateServiceRequest serviceRequest = CreateServiceRequest.builder() + .cluster(clusterName) + .networkConfiguration(configuration) + .desiredCount(1) + .launchType(LaunchType.FARGATE) + .serviceName(serviceName) + .taskDefinition(taskDefinition) + .build(); - CreateServiceResponse response = ecsClient.createService(serviceRequest); - return response.service().serviceArn(); + CreateServiceResponse response = ecsClient.createService(serviceRequest); + return response.service().serviceArn(); - } catch (EcsException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + } catch (EcsException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + return ""; } - return ""; - } } // snippet-end:[ecs.java2.create_service.main] diff --git a/javav2/example_code/ecs/src/main/java/com/example/ecs/DeleteService.java b/javav2/example_code/ecs/src/main/java/com/example/ecs/DeleteService.java index b548158cd6e..d82ecdee6b6 100644 --- a/javav2/example_code/ecs/src/main/java/com/example/ecs/DeleteService.java +++ b/javav2/example_code/ecs/src/main/java/com/example/ecs/DeleteService.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DeleteService.java demonstrates how to delete a service for the Amazon Elastic Container Service (Amazon ECS) service.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Elastic Container Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.ecs; @@ -18,7 +12,8 @@ // snippet-end:[ecs.java2.delete_service.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,13 +24,13 @@ public class DeleteService { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - clusterName - The name of the ECS cluster. - serviceArn - The ARN of the ECS service. - """; + Where: + clusterName - The name of the ECS cluster. + serviceArn - The ARN of the ECS service. + """; if (args.length != 2) { System.out.println(usage); @@ -46,8 +41,8 @@ public static void main(String[] args) { String serviceArn = args[1]; Region region = Region.US_EAST_1; EcsClient ecsClient = EcsClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteSpecificService(ecsClient, clusterName, serviceArn); ecsClient.close(); @@ -56,9 +51,9 @@ public static void main(String[] args) { public static void deleteSpecificService(EcsClient ecsClient, String clusterName, String serviceArn) { try { DeleteServiceRequest serviceRequest = DeleteServiceRequest.builder() - .cluster(clusterName) - .service(serviceArn) - .build(); + .cluster(clusterName) + .service(serviceArn) + .build(); ecsClient.deleteService(serviceRequest); System.out.println("The Service was successfully deleted"); diff --git a/javav2/example_code/ecs/src/main/java/com/example/ecs/DescribeClusters.java b/javav2/example_code/ecs/src/main/java/com/example/ecs/DescribeClusters.java index ca78b32392d..bb63a93675e 100644 --- a/javav2/example_code/ecs/src/main/java/com/example/ecs/DescribeClusters.java +++ b/javav2/example_code/ecs/src/main/java/com/example/ecs/DescribeClusters.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeClusters.java demonstrates how to describe a cluster for the Amazon Elastic Container Service (Amazon ECS) service.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Elastic Container Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.ecs; @@ -21,7 +15,8 @@ // snippet-end:[ecs.java2.des_cluster.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,12 +26,12 @@ public class DescribeClusters { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - clusterArn - The ARN of the ECS cluster to describe. - """; + Where: + clusterArn - The ARN of the ECS cluster to describe. + """; if (args.length != 1) { System.out.println(usage); @@ -46,8 +41,8 @@ public static void main(String[] args) { String clusterArn = args[0]; Region region = Region.US_EAST_1; EcsClient ecsClient = EcsClient.builder() - .region(region) - .build(); + .region(region) + .build(); descCluster(ecsClient, clusterArn); } @@ -55,8 +50,8 @@ public static void main(String[] args) { public static void descCluster(EcsClient ecsClient, String clusterArn) { try { DescribeClustersRequest clustersRequest = DescribeClustersRequest.builder() - .clusters(clusterArn) - .build(); + .clusters(clusterArn) + .build(); DescribeClustersResponse response = ecsClient.describeClusters(clustersRequest); List clusters = response.clusters(); diff --git a/javav2/example_code/ecs/src/main/java/com/example/ecs/ListClusters.java b/javav2/example_code/ecs/src/main/java/com/example/ecs/ListClusters.java index 7b4b8a86963..86b85fbb262 100644 --- a/javav2/example_code/ecs/src/main/java/com/example/ecs/ListClusters.java +++ b/javav2/example_code/ecs/src/main/java/com/example/ecs/ListClusters.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[ListClusters.java demonstrates how to list clusters for the Amazon Elastic Container Service (Amazon ECS) service.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Elastic Container Service] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.ecs; // snippet-start:[ecs.java2.list_clusters.main] @@ -18,7 +13,8 @@ // snippet-end:[ecs.java2.list_clusters.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,12 +25,13 @@ public class ListClusters { public static void main(String[] args) { Region region = Region.US_EAST_1; EcsClient ecsClient = EcsClient.builder() - .region(region) - .build(); + .region(region) + .build(); listAllClusters(ecsClient); ecsClient.close(); } + public static void listAllClusters(EcsClient ecsClient) { try { ListClustersResponse response = ecsClient.listClusters(); diff --git a/javav2/example_code/ecs/src/main/java/com/example/ecs/ListTaskDefinitions.java b/javav2/example_code/ecs/src/main/java/com/example/ecs/ListTaskDefinitions.java index 3ee5cf4059d..14f69e46822 100644 --- a/javav2/example_code/ecs/src/main/java/com/example/ecs/ListTaskDefinitions.java +++ b/javav2/example_code/ecs/src/main/java/com/example/ecs/ListTaskDefinitions.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[ListTaskDefinitions.java demonstrates how to list task definitions.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Elastic Container Service] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.ecs; // snippet-start:[ecs.java2.list_tasks.main] @@ -20,7 +15,8 @@ // snippet-end:[ecs.java2.list_tasks.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,13 +26,13 @@ public class ListTaskDefinitions { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - clusterArn - The ARN of an ECS cluster. - taskId - The task Id value. - """; + Where: + clusterArn - The ARN of an ECS cluster. + taskId - The task Id value. + """; if (args.length != 2) { System.out.println(usage); @@ -47,8 +43,8 @@ public static void main(String[] args) { String taskId = args[1]; Region region = Region.US_EAST_1; EcsClient ecsClient = EcsClient.builder() - .region(region) - .build(); + .region(region) + .build(); getAllTasks(ecsClient, clusterArn, taskId); ecsClient.close(); @@ -57,9 +53,9 @@ public static void main(String[] args) { public static void getAllTasks(EcsClient ecsClient, String clusterArn, String taskId) { try { DescribeTasksRequest tasksRequest = DescribeTasksRequest.builder() - .cluster(clusterArn) - .tasks(taskId) - .build(); + .cluster(clusterArn) + .tasks(taskId) + .build(); DescribeTasksResponse response = ecsClient.describeTasks(tasksRequest); List tasks = response.tasks(); diff --git a/javav2/example_code/ecs/src/main/java/com/example/ecs/UpdateService.java b/javav2/example_code/ecs/src/main/java/com/example/ecs/UpdateService.java index 85f8a76d4e1..225f50df0ef 100644 --- a/javav2/example_code/ecs/src/main/java/com/example/ecs/UpdateService.java +++ b/javav2/example_code/ecs/src/main/java/com/example/ecs/UpdateService.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[UpdateService.java demonstrates how to update the task placement strategies and constraints on an Amazon Elastic Container Service (Amazon ECS) service.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Elastic Container Service] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.ecs; @@ -17,7 +12,8 @@ // snippet-end:[ecs.java2.update_service.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,13 +26,13 @@ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - clusterName - The cluster name. - serviceArn - The service ARN value. - """; + Where: + clusterName - The cluster name. + serviceArn - The service ARN value. + """; if (args.length != 2) { System.out.println(usage); @@ -47,8 +43,8 @@ public static void main(String[] args) { String serviceArn = args[1]; Region region = Region.US_EAST_1; EcsClient ecsClient = EcsClient.builder() - .region(region) - .build(); + .region(region) + .build(); updateSpecificService(ecsClient, clusterName, serviceArn); ecsClient.close(); @@ -57,10 +53,10 @@ public static void main(String[] args) { public static void updateSpecificService(EcsClient ecsClient, String clusterName, String serviceArn) { try { UpdateServiceRequest serviceRequest = UpdateServiceRequest.builder() - .cluster(clusterName) - .service(serviceArn) - .desiredCount(0) - .build(); + .cluster(clusterName) + .service(serviceArn) + .desiredCount(0) + .build(); ecsClient.updateService(serviceRequest); System.out.println("The service was modified"); diff --git a/javav2/example_code/ecs/src/test/java/EcsTest.java b/javav2/example_code/ecs/src/test/java/EcsTest.java index 2c967ccaa41..6013e5e4eb7 100644 --- a/javav2/example_code/ecs/src/test/java/EcsTest.java +++ b/javav2/example_code/ecs/src/test/java/EcsTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.ecs.*; import com.google.gson.Gson; @@ -23,7 +21,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class EcsTest { - private static EcsClient ecsClient; + private static EcsClient ecsClient; private static String clusterName = ""; private static String clusterARN = ""; private static String taskId = ""; @@ -38,44 +36,46 @@ public static void setUp() throws IOException { // Run tests on Real AWS Resources ecsClient = EcsClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); String json = getSecretValues(); SecretValues values = gson.fromJson(json, SecretValues.class); - clusterName = values.getClusterName()+java.util.UUID.randomUUID(); + clusterName = values.getClusterName() + java.util.UUID.randomUUID(); taskId = values.getTaskId(); subnet = values.getSubnet(); securityGroups = values.getSecurityGroups(); - serviceName = values.getServiceName() +java.util.UUID.randomUUID(); + serviceName = values.getServiceName() + java.util.UUID.randomUUID(); taskDefinition = values.getTaskDefinition(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - - try (InputStream input = EcsTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - // Populate the data members required for all tests. - prop.load(input); - clusterName = prop.getProperty("clusterName")+java.util.UUID.randomUUID(); - taskId = prop.getProperty("taskId"); - subnet = prop.getProperty("subnet"); - securityGroups = prop.getProperty("securityGroups"); - serviceName = prop.getProperty("serviceName")+java.util.UUID.randomUUID(); - taskDefinition = prop.getProperty("taskDefinition"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * + * try (InputStream input = + * EcsTest.class.getClassLoader().getResourceAsStream("config.properties")) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * // Populate the data members required for all tests. + * prop.load(input); + * clusterName = prop.getProperty("clusterName")+java.util.UUID.randomUUID(); + * taskId = prop.getProperty("taskId"); + * subnet = prop.getProperty("subnet"); + * securityGroups = prop.getProperty("securityGroups"); + * serviceName = prop.getProperty("serviceName")+java.util.UUID.randomUUID(); + * taskDefinition = prop.getProperty("taskDefinition"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @@ -91,7 +91,7 @@ public void CreateCluster() { @Tag("IntegrationTest") @Order(2) public void ListClusters() { - assertDoesNotThrow(() ->ListClusters.listAllClusters(ecsClient)); + assertDoesNotThrow(() -> ListClusters.listAllClusters(ecsClient)); System.out.println("Test 3 passed"); } @@ -99,7 +99,7 @@ public void ListClusters() { @Tag("IntegrationTest") @Order(3) public void DescribeClusters() { - assertDoesNotThrow(() ->DescribeClusters.descCluster(ecsClient, clusterARN)); + assertDoesNotThrow(() -> DescribeClusters.descCluster(ecsClient, clusterARN)); System.out.println("Test 4 passed"); } @@ -107,7 +107,7 @@ public void DescribeClusters() { @Tag("IntegrationTest") @Order(4) public void ListTaskDefinitions() { - assertDoesNotThrow(() ->ListTaskDefinitions.getAllTasks(ecsClient, clusterARN, taskId)); + assertDoesNotThrow(() -> ListTaskDefinitions.getAllTasks(ecsClient, clusterARN, taskId)); System.out.println("Test 5 passed"); } @@ -115,7 +115,8 @@ public void ListTaskDefinitions() { @Tag("IntegrationTest") @Order(5) public void CreateService() { - serviceArn = CreateService.createNewService(ecsClient, clusterName, serviceName, securityGroups, subnet, taskDefinition); + serviceArn = CreateService.createNewService(ecsClient, clusterName, serviceName, securityGroups, subnet, + taskDefinition); assertFalse(serviceArn.isEmpty()); System.out.println("Test 6 passed"); } @@ -125,7 +126,7 @@ public void CreateService() { @Order(6) public void UpdateService() throws InterruptedException { Thread.sleep(20000); - assertDoesNotThrow(() ->UpdateService.updateSpecificService(ecsClient, clusterName, serviceArn)); + assertDoesNotThrow(() -> UpdateService.updateSpecificService(ecsClient, clusterName, serviceArn)); System.out.println("Test 7 passed"); } @@ -133,20 +134,20 @@ public void UpdateService() throws InterruptedException { @Tag("IntegrationTest") @Order(7) public void DeleteService() { - assertDoesNotThrow(() ->DeleteService.deleteSpecificService(ecsClient, clusterName, serviceArn)); + assertDoesNotThrow(() -> DeleteService.deleteSpecificService(ecsClient, clusterName, serviceArn)); System.out.println("Test 8 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/ecs"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -190,4 +191,3 @@ public String getTaskDefinition() { } } } - diff --git a/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/CreateApplication.java b/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/CreateApplication.java index e6698934385..4525f6016cb 100644 --- a/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/CreateApplication.java +++ b/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/CreateApplication.java @@ -1,25 +1,20 @@ -//snippet-sourcedescription:[CreateApplication.java demonstrates how to create an AWS Elastic Beanstalk application.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[AWS Elastic Beanstalk ] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.aws.example; -//snippet-start:[eb.java2.create_app.main] -//snippet-start:[eb.java2.create_app.import] +// snippet-start:[eb.java2.create_app.main] +// snippet-start:[eb.java2.create_app.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.elasticbeanstalk.ElasticBeanstalkClient; import software.amazon.awssdk.services.elasticbeanstalk.model.CreateApplicationResponse; import software.amazon.awssdk.services.elasticbeanstalk.model.CreateApplicationRequest; import software.amazon.awssdk.services.elasticbeanstalk.model.ElasticBeanstalkException; -//snippet-end:[eb.java2.create_app.import] +// snippet-end:[eb.java2.create_app.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,12 +24,12 @@ public class CreateApplication { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - appName - The name of the AWS Elastic Beanstalk application.\s - """; + Where: + appName - The name of the AWS Elastic Beanstalk application.\s + """; if (args.length != 1) { System.out.println(usage); @@ -44,8 +39,8 @@ public static void main(String[] args) { String appName = args[0]; Region region = Region.US_EAST_1; ElasticBeanstalkClient beanstalkClient = ElasticBeanstalkClient.builder() - .region(region) - .build(); + .region(region) + .build(); String appArn = createApp(beanstalkClient, appName); System.out.println("The ARN of the application is " + appArn); @@ -54,9 +49,9 @@ public static void main(String[] args) { public static String createApp(ElasticBeanstalkClient beanstalkClient, String appName) { try { CreateApplicationRequest applicationRequest = CreateApplicationRequest.builder() - .description("An AWS Elastic Beanstalk app created using the AWS Java API") - .applicationName(appName) - .build(); + .description("An AWS Elastic Beanstalk app created using the AWS Java API") + .applicationName(appName) + .build(); CreateApplicationResponse applicationResponse = beanstalkClient.createApplication(applicationRequest); return applicationResponse.application().applicationArn(); @@ -68,6 +63,4 @@ public static String createApp(ElasticBeanstalkClient beanstalkClient, String ap return ""; } } -//snippet-end:[eb.java2.create_app.main] - - +// snippet-end:[eb.java2.create_app.main] diff --git a/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/CreateEnvironment.java b/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/CreateEnvironment.java index 2176161b625..19b18518239 100644 --- a/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/CreateEnvironment.java +++ b/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/CreateEnvironment.java @@ -1,26 +1,21 @@ -//snippet-sourcedescription:[CreateEnvironment.java demonstrates how to create an AWS Elastic Beanstalk environment.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[AWS Elastic Beanstalk ] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.aws.example; -//snippet-start:[eb.java2.create_env.main] -//snippet-start:[eb.java2.create_env.import] +// snippet-start:[eb.java2.create_env.main] +// snippet-start:[eb.java2.create_env.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.elasticbeanstalk.ElasticBeanstalkClient; import software.amazon.awssdk.services.elasticbeanstalk.model.ConfigurationOptionSetting; import software.amazon.awssdk.services.elasticbeanstalk.model.CreateEnvironmentRequest; import software.amazon.awssdk.services.elasticbeanstalk.model.CreateEnvironmentResponse; import software.amazon.awssdk.services.elasticbeanstalk.model.ElasticBeanstalkException; -//snippet-end:[eb.java2.create_env.import] +// snippet-end:[eb.java2.create_env.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,12 +27,12 @@ public class CreateEnvironment { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - envName - The name of the AWS Elastic Beanstalk environment.\s - appName - The name of the AWS Elastic Beanstalk application."""; + Where: + envName - The name of the AWS Elastic Beanstalk environment.\s + appName - The name of the AWS Elastic Beanstalk application."""; if (args.length != 1) { System.out.println(usage); @@ -48,8 +43,8 @@ public static void main(String[] args) { String appName = args[1]; Region region = Region.US_WEST_2; ElasticBeanstalkClient beanstalkClient = ElasticBeanstalkClient.builder() - .region(region) - .build(); + .region(region) + .build(); String environmentArn = createEBEnvironment(beanstalkClient, envName, appName); System.out.println("The ARN of the environment is " + environmentArn); @@ -58,18 +53,18 @@ public static void main(String[] args) { public static String createEBEnvironment(ElasticBeanstalkClient beanstalkClient, String envName, String appName) { try { ConfigurationOptionSetting setting1 = ConfigurationOptionSetting.builder() - .namespace("aws:autoscaling:launchconfiguration") - .optionName("IamInstanceProfile") - .value("aws-elasticbeanstalk-ec2-role") - .build(); + .namespace("aws:autoscaling:launchconfiguration") + .optionName("IamInstanceProfile") + .value("aws-elasticbeanstalk-ec2-role") + .build(); CreateEnvironmentRequest applicationRequest = CreateEnvironmentRequest.builder() - .description("An AWS Elastic Beanstalk environment created using the AWS Java API") - .environmentName(envName) - .solutionStackName("64bit Amazon Linux 2 v3.2.12 running Corretto 11") - .applicationName(appName) - .optionSettings(setting1) - .build(); + .description("An AWS Elastic Beanstalk environment created using the AWS Java API") + .environmentName(envName) + .solutionStackName("64bit Amazon Linux 2 v3.2.12 running Corretto 11") + .applicationName(appName) + .optionSettings(setting1) + .build(); CreateEnvironmentResponse response = beanstalkClient.createEnvironment(applicationRequest); return response.environmentArn(); @@ -82,4 +77,4 @@ public static String createEBEnvironment(ElasticBeanstalkClient beanstalkClient, return ""; } } -//snippet-end:[eb.java2.create_env.main] +// snippet-end:[eb.java2.create_env.main] diff --git a/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/DeleteApplication.java b/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/DeleteApplication.java index be42bfe3e83..77f08886ee1 100644 --- a/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/DeleteApplication.java +++ b/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/DeleteApplication.java @@ -1,24 +1,19 @@ -//snippet-sourcedescription:[DeleteApplication.java demonstrates how to delete an AWS Elastic Beanstalk application.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[AWS Elastic Beanstalk ] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.aws.example; -//snippet-start:[eb.java2.delete_app.main] -//snippet-start:[eb.java2.delete_app.import] +// snippet-start:[eb.java2.delete_app.main] +// snippet-start:[eb.java2.delete_app.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.elasticbeanstalk.ElasticBeanstalkClient; import software.amazon.awssdk.services.elasticbeanstalk.model.ElasticBeanstalkException; import software.amazon.awssdk.services.elasticbeanstalk.model.DeleteApplicationRequest; -//snippet-end:[eb.java2.delete_app.import] +// snippet-end:[eb.java2.delete_app.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +23,12 @@ public class DeleteApplication { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - appName - The name of the AWS Elastic Beanstalk application.\s - """; + Where: + appName - The name of the AWS Elastic Beanstalk application.\s + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +38,8 @@ public static void main(String[] args) { String appName = args[0]; Region region = Region.US_EAST_1; ElasticBeanstalkClient beanstalkClient = ElasticBeanstalkClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteApp(beanstalkClient, appName); } @@ -52,9 +47,9 @@ public static void main(String[] args) { public static void deleteApp(ElasticBeanstalkClient beanstalkClient, String appName) { try { DeleteApplicationRequest applicationRequest = DeleteApplicationRequest.builder() - .applicationName(appName) - .terminateEnvByForce(true) - .build(); + .applicationName(appName) + .terminateEnvByForce(true) + .build(); beanstalkClient.deleteApplication(applicationRequest); System.out.println("The Elastic Beanstalk application was successfully deleted!"); @@ -64,5 +59,5 @@ public static void deleteApp(ElasticBeanstalkClient beanstalkClient, String appN System.exit(1); } } - //snippet-end:[eb.java2.delete_app.main] + // snippet-end:[eb.java2.delete_app.main] } diff --git a/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/DescribeApplications.java b/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/DescribeApplications.java index a3d575ae890..de355f75797 100644 --- a/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/DescribeApplications.java +++ b/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/DescribeApplications.java @@ -1,17 +1,10 @@ -//snippet-sourcedescription:[DescribeApplication.java demonstrates how to describe an AWS Elastic Beanstalk application.] -//snippet-keyword:[SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[AWS Elastic Beanstalk ] -//snippet-sourcetype:[full-example] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.aws.example; -//snippet-start:[eb.java2.describe_app.main] -//snippet-start:[eb.java2.describe_app.import] +// snippet-start:[eb.java2.describe_app.main] +// snippet-start:[eb.java2.describe_app.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.elasticbeanstalk.ElasticBeanstalkClient; import software.amazon.awssdk.services.elasticbeanstalk.model.DescribeApplicationsResponse; @@ -21,10 +14,11 @@ import software.amazon.awssdk.services.elasticbeanstalk.model.EnvironmentDescription; import software.amazon.awssdk.services.elasticbeanstalk.model.ElasticBeanstalkException; import java.util.List; -//snippet-end:[eb.java2.describe_app.import] +// snippet-end:[eb.java2.describe_app.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -35,8 +29,8 @@ public class DescribeApplications { public static void main(String[] args) { Region region = Region.US_EAST_1; ElasticBeanstalkClient beanstalkClient = ElasticBeanstalkClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeApps(beanstalkClient); } @@ -48,8 +42,8 @@ public static void describeApps(ElasticBeanstalkClient beanstalkClient) { for (ApplicationDescription app : apps) { System.out.println("The application name is " + app.applicationName()); DescribeEnvironmentsRequest desRequest = DescribeEnvironmentsRequest.builder() - .applicationName(app.applicationName()) - .build(); + .applicationName(app.applicationName()) + .build(); DescribeEnvironmentsResponse res = beanstalkClient.describeEnvironments(desRequest); List envDesc = res.environments(); @@ -66,4 +60,4 @@ public static void describeApps(ElasticBeanstalkClient beanstalkClient) { } } } -//snippet-end:[eb.java2.describe_app.main] +// snippet-end:[eb.java2.describe_app.main] diff --git a/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/DescribeConfigurationOptions.java b/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/DescribeConfigurationOptions.java index 7c668611e19..393f9b31ab9 100644 --- a/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/DescribeConfigurationOptions.java +++ b/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/DescribeConfigurationOptions.java @@ -1,16 +1,10 @@ -//snippet-sourcedescription:[DescribeApplication.java demonstrates how to describe configuration options.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[AWS Elastic Beanstalk ] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.aws.example; -//snippet-start:[eb.java2.config.main] -//snippet-start:[eb.java2.config.import] +// snippet-start:[eb.java2.config.main] +// snippet-start:[eb.java2.config.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.elasticbeanstalk.ElasticBeanstalkClient; import software.amazon.awssdk.services.elasticbeanstalk.model.OptionSpecification; @@ -19,10 +13,11 @@ import software.amazon.awssdk.services.elasticbeanstalk.model.ConfigurationOptionDescription; import software.amazon.awssdk.services.elasticbeanstalk.model.ElasticBeanstalkException; import java.util.List; -//snippet-end:[eb.java2.config.import] +// snippet-end:[eb.java2.config.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -33,8 +28,8 @@ public class DescribeConfigurationOptions { public static void main(String[] args) { Region region = Region.US_EAST_1; ElasticBeanstalkClient beanstalkClient = ElasticBeanstalkClient.builder() - .region(region) - .build(); + .region(region) + .build(); getOptions(beanstalkClient); } @@ -42,13 +37,13 @@ public static void main(String[] args) { public static void getOptions(ElasticBeanstalkClient beanstalkClient) { try { OptionSpecification spec = OptionSpecification.builder() - .namespace("aws:ec2:instances") - .build(); + .namespace("aws:ec2:instances") + .build(); DescribeConfigurationOptionsRequest request = DescribeConfigurationOptionsRequest.builder() - .environmentName("Joblisting-env") - .options(spec) - .build(); + .environmentName("Joblisting-env") + .options(spec) + .build(); DescribeConfigurationOptionsResponse response = beanstalkClient.describeConfigurationOptions(request); List options = response.options(); @@ -70,4 +65,4 @@ public static void getOptions(ElasticBeanstalkClient beanstalkClient) { } } } -//snippet-end:[eb.java2.config.main] +// snippet-end:[eb.java2.config.main] diff --git a/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/DescribeEnvironment.java b/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/DescribeEnvironment.java index 32db4f1c81a..704f79f69fd 100644 --- a/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/DescribeEnvironment.java +++ b/javav2/example_code/elasticbeanstalk/src/main/java/com/aws/example/DescribeEnvironment.java @@ -1,15 +1,10 @@ -//snippet-sourcedescription:[DescribeEnvironment.java demonstrates how to describe an AWS Elastic Beanstalk environment.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[AWS Elastic Beanstalk ] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.aws.example; -//snippet-start:[eb.java2.describe_env.main] -//snippet-start:[eb.java2.describe_env.import] +// snippet-start:[eb.java2.describe_env.main] +// snippet-start:[eb.java2.describe_env.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.elasticbeanstalk.ElasticBeanstalkClient; import software.amazon.awssdk.services.elasticbeanstalk.model.DescribeEnvironmentsRequest; @@ -17,10 +12,11 @@ import software.amazon.awssdk.services.elasticbeanstalk.model.EnvironmentDescription; import software.amazon.awssdk.services.elasticbeanstalk.model.ElasticBeanstalkException; import java.util.List; -//snippet-end:[eb.java2.describe_env.import] +// snippet-end:[eb.java2.describe_env.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,12 +27,12 @@ public class DescribeEnvironment { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - appName - The name of the AWS Elastic Beanstalk application.\s - """; + Where: + appName - The name of the AWS Elastic Beanstalk application.\s + """; if (args.length != 1) { System.out.println(usage); @@ -46,8 +42,8 @@ public static void main(String[] args) { String appName = args[0]; Region region = Region.US_EAST_1; ElasticBeanstalkClient beanstalkClient = ElasticBeanstalkClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeEnv(beanstalkClient, appName); } @@ -55,8 +51,8 @@ public static void main(String[] args) { public static void describeEnv(ElasticBeanstalkClient beanstalkClient, String appName) { try { DescribeEnvironmentsRequest request = DescribeEnvironmentsRequest.builder() - .environmentNames("Joblisting-env") - .build(); + .environmentNames("Joblisting-env") + .build(); DescribeEnvironmentsResponse response = beanstalkClient.describeEnvironments(request); List envs = response.environments(); @@ -71,4 +67,4 @@ public static void describeEnv(ElasticBeanstalkClient beanstalkClient, String ap } } } -//snippet-end:[eb.java2.describe_env.main] +// snippet-end:[eb.java2.describe_env.main] diff --git a/javav2/example_code/elasticbeanstalk/src/test/java/ElasticBeanstalkTest.java b/javav2/example_code/elasticbeanstalk/src/test/java/ElasticBeanstalkTest.java index 2a11145ea18..ed39873d199 100644 --- a/javav2/example_code/elasticbeanstalk/src/test/java/ElasticBeanstalkTest.java +++ b/javav2/example_code/elasticbeanstalk/src/test/java/ElasticBeanstalkTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.aws.example.*; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; @@ -15,15 +13,15 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class ElasticBeanstalkTest { private static ElasticBeanstalkClient beanstalkClient; - private static final String appName="apptest"; + private static final String appName = "apptest"; @BeforeAll public static void setUp() { Region region = Region.US_EAST_1; beanstalkClient = ElasticBeanstalkClient.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); } @Test @@ -58,7 +56,7 @@ public void DescribeApplications() { @Tag("IntegrationTest") @Order(4) public void DescribeEnvironment() { - assertDoesNotThrow(() ->DescribeEnvironment.describeEnv(beanstalkClient, appName)); + assertDoesNotThrow(() -> DescribeEnvironment.describeEnv(beanstalkClient, appName)); System.out.println("Test 4 passed"); } @@ -66,9 +64,9 @@ public void DescribeEnvironment() { @Tag("IntegrationTest") @Order(5) public void DeleteApplication() throws InterruptedException { - System.out.println("*** Wait for 5 MIN so the app can be deleted"); - TimeUnit.MINUTES.sleep(5); - assertDoesNotThrow(() ->DeleteApplication.deleteApp(beanstalkClient, appName)); - System.out.println("Test 5 passed"); - } + System.out.println("*** Wait for 5 MIN so the app can be deleted"); + TimeUnit.MINUTES.sleep(5); + assertDoesNotThrow(() -> DeleteApplication.deleteApp(beanstalkClient, appName)); + System.out.println("Test 5 passed"); + } } diff --git a/javav2/example_code/emr/run_example.sh b/javav2/example_code/emr/run_example.sh index c654ab9fe09..3a74b261b3f 100755 --- a/javav2/example_code/emr/run_example.sh +++ b/javav2/example_code/emr/run_example.sh @@ -1,3 +1,5 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 mvn exec:java -Dexec.mainClass="aws.example.emr.CreateEmrFleet" -Dexec.cleanupDaemonThreads=false \ No newline at end of file diff --git a/javav2/example_code/emr/src/main/java/aws/example/emr/AddSteps.java b/javav2/example_code/emr/src/main/java/aws/example/emr/AddSteps.java index 0143e629a37..50e31ac1d89 100644 --- a/javav2/example_code/emr/src/main/java/aws/example/emr/AddSteps.java +++ b/javav2/example_code/emr/src/main/java/aws/example/emr/AddSteps.java @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[AddSteps.java demonstrates how to add new steps to a running cluster.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EMR] -//snippet-sourcetype:[full-example] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.emr; @@ -22,7 +14,8 @@ // snippet-end:[emr.java2._add_steps.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -33,14 +26,14 @@ public class AddSteps { public static void main(String[] args) { final String usage = """ - Usage: \s + Usage: \s - Where: - jar - A path to a JAR file run during the step.\s - myClass - The name of the main class in the specified Java file.\s - jobFlowId - The id of the job flow.\s + Where: + jar - A path to a JAR file run during the step.\s + myClass - The name of the main class in the specified Java file.\s + jobFlowId - The id of the job flow.\s - """; + """; if (args.length != 3) { System.out.println(usage); @@ -52,8 +45,8 @@ public static void main(String[] args) { String jobFlowId = args[2]; Region region = Region.US_WEST_2; EmrClient emrClient = EmrClient.builder() - .region(region) - .build(); + .region(region) + .build(); addNewStep(emrClient, jobFlowId, jar, myClass); emrClient.close(); @@ -62,19 +55,19 @@ public static void main(String[] args) { public static void addNewStep(EmrClient emrClient, String jobFlowId, String jar, String myClass) { try { HadoopJarStepConfig jarStepConfig = HadoopJarStepConfig.builder() - .jar(jar) - .mainClass(myClass) - .build(); + .jar(jar) + .mainClass(myClass) + .build(); StepConfig stepConfig = StepConfig.builder() - .hadoopJarStep(jarStepConfig) - .name("Run a bash script") - .build(); + .hadoopJarStep(jarStepConfig) + .name("Run a bash script") + .build(); AddJobFlowStepsRequest jobFlowStepsRequest = AddJobFlowStepsRequest.builder() - .jobFlowId(jobFlowId) - .steps(stepConfig) - .build(); + .jobFlowId(jobFlowId) + .steps(stepConfig) + .build(); emrClient.addJobFlowSteps(jobFlowStepsRequest); System.out.println("You have successfully added a step!"); diff --git a/javav2/example_code/emr/src/main/java/aws/example/emr/CreateCluster.java b/javav2/example_code/emr/src/main/java/aws/example/emr/CreateCluster.java index a749bbe8eef..e3724b48892 100644 --- a/javav2/example_code/emr/src/main/java/aws/example/emr/CreateCluster.java +++ b/javav2/example_code/emr/src/main/java/aws/example/emr/CreateCluster.java @@ -1,12 +1,6 @@ -//snippet-sourcedescription:[CreateCluster.java demonstrates how to create and start running a new cluster (job flow).] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EMR] -//snippet-sourcetype:[full-example] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package aws.example.emr; // snippet-start:[emr.java2._create_cluster.main] @@ -25,7 +19,8 @@ // snippet-end:[emr.java2._create_cluster.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -33,104 +28,104 @@ */ public class CreateCluster { - public static void main(String[] args) { - final String usage = """ - - Usage: - - Where: - jar - A path to a JAR file run during the step.\s - myClass - The name of the main class in the specified Java file.\s - keys - The name of the Amazon EC2 key pair.\s - logUri - The Amazon S3 bucket where the logs are located (for example, s3:///logs/).\s - name - The name of the job flow.\s - """; - - if (args.length != 5) { - System.out.println(usage); - System.exit(1); + public static void main(String[] args) { + final String usage = """ + + Usage: + + Where: + jar - A path to a JAR file run during the step.\s + myClass - The name of the main class in the specified Java file.\s + keys - The name of the Amazon EC2 key pair.\s + logUri - The Amazon S3 bucket where the logs are located (for example, s3:///logs/).\s + name - The name of the job flow.\s + """; + + if (args.length != 5) { + System.out.println(usage); + System.exit(1); + } + + String jar = args[0]; + String myClass = args[1]; + String keys = args[2]; + String logUri = args[3]; + String name = args[4]; + Region region = Region.US_WEST_2; + EmrClient emrClient = EmrClient.builder() + .region(region) + .build(); + + String jobFlowId = createAppCluster(emrClient, jar, myClass, keys, logUri, name); + System.out.println("The job flow id is " + jobFlowId); + emrClient.close(); } - String jar = args[0]; - String myClass = args[1]; - String keys = args[2]; - String logUri = args[3]; - String name = args[4]; - Region region = Region.US_WEST_2; - EmrClient emrClient = EmrClient.builder() - .region(region) - .build(); - - String jobFlowId = createAppCluster(emrClient, jar, myClass, keys, logUri, name); - System.out.println("The job flow id is " + jobFlowId); - emrClient.close(); - } - - public static String createAppCluster(EmrClient emrClient, - String jar, - String myClass, - String keys, - String logUri, - String name) { - - try { - HadoopJarStepConfig jarStepConfig = HadoopJarStepConfig.builder() - .jar(jar) - .mainClass(myClass) - .build(); - - Application spark = Application.builder() - .name("Spark") - .build(); - - Application hive = Application.builder() - .name("Hive") - .build(); - - Application zeppelin = Application.builder() - .name("Zeppelin") - .build(); - - List apps = new ArrayList<>(); - apps.add(spark); - apps.add(hive); - apps.add(zeppelin); - - StepConfig enabledebugging = StepConfig.builder() - .name("Enable debugging") - .actionOnFailure("TERMINATE_JOB_FLOW") - .hadoopJarStep(jarStepConfig) - .build(); - - JobFlowInstancesConfig instancesConfig = JobFlowInstancesConfig.builder() - .ec2SubnetId("subnet-206a9c58") - .ec2KeyName(keys) - .instanceCount(3) - .keepJobFlowAliveWhenNoSteps(true) - .masterInstanceType("m4.large") - .slaveInstanceType("m4.large") - .build(); - - RunJobFlowRequest jobFlowRequest = RunJobFlowRequest.builder() - .name(name) - .releaseLabel("emr-5.20.0") - .steps(enabledebugging) - .applications(apps) - .logUri(logUri) - .serviceRole("EMR_DefaultRole") - .jobFlowRole("EMR_EC2_DefaultRole") - .instances(instancesConfig) - .build(); - - RunJobFlowResponse response = emrClient.runJobFlow(jobFlowRequest); - return response.jobFlowId(); - - } catch (EmrException e) { - System.err.println(e.getMessage()); - System.exit(1); + public static String createAppCluster(EmrClient emrClient, + String jar, + String myClass, + String keys, + String logUri, + String name) { + + try { + HadoopJarStepConfig jarStepConfig = HadoopJarStepConfig.builder() + .jar(jar) + .mainClass(myClass) + .build(); + + Application spark = Application.builder() + .name("Spark") + .build(); + + Application hive = Application.builder() + .name("Hive") + .build(); + + Application zeppelin = Application.builder() + .name("Zeppelin") + .build(); + + List apps = new ArrayList<>(); + apps.add(spark); + apps.add(hive); + apps.add(zeppelin); + + StepConfig enabledebugging = StepConfig.builder() + .name("Enable debugging") + .actionOnFailure("TERMINATE_JOB_FLOW") + .hadoopJarStep(jarStepConfig) + .build(); + + JobFlowInstancesConfig instancesConfig = JobFlowInstancesConfig.builder() + .ec2SubnetId("subnet-206a9c58") + .ec2KeyName(keys) + .instanceCount(3) + .keepJobFlowAliveWhenNoSteps(true) + .masterInstanceType("m4.large") + .slaveInstanceType("m4.large") + .build(); + + RunJobFlowRequest jobFlowRequest = RunJobFlowRequest.builder() + .name(name) + .releaseLabel("emr-5.20.0") + .steps(enabledebugging) + .applications(apps) + .logUri(logUri) + .serviceRole("EMR_DefaultRole") + .jobFlowRole("EMR_EC2_DefaultRole") + .instances(instancesConfig) + .build(); + + RunJobFlowResponse response = emrClient.runJobFlow(jobFlowRequest); + return response.jobFlowId(); + + } catch (EmrException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + + return ""; } - - return ""; - } } // snippet-end:[emr.java2._create_cluster.main] diff --git a/javav2/example_code/emr/src/main/java/aws/example/emr/CreateEmrFleet.java b/javav2/example_code/emr/src/main/java/aws/example/emr/CreateEmrFleet.java index 42f3e4e1358..dac1314d7be 100644 --- a/javav2/example_code/emr/src/main/java/aws/example/emr/CreateEmrFleet.java +++ b/javav2/example_code/emr/src/main/java/aws/example/emr/CreateEmrFleet.java @@ -1,13 +1,6 @@ -//snippet-sourcedescription:[CreateEmrFleet.java demonstrates how to create a cluster using instance fleet with spot instances.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EMR] -//snippet-sourcetype:[full-example] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package aws.example.emr; // snippet-start:[emr.java2._create_fleet.main] @@ -26,146 +19,143 @@ // snippet-end:[emr.java2._create_fleet.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * Also. to run the CreateEmrFleet example, it is recommended that you go through the following document: + * Also. to run the CreateEmrFleet example, it is recommended that you go + * through the following document: * * https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-gs.html * ------------------------------------- */ public class CreateEmrFleet { - public static void main(String[] args) throws Exception { - Region region = Region.US_EAST_1; - EmrClient emrClient = EmrClient.builder() - .region(region) - .build(); - createFleet(emrClient); - } - - public static void createFleet(EmrClient emr) { - try { - InstanceTypeConfig m3xLarge = InstanceTypeConfig.builder() - .bidPriceAsPercentageOfOnDemandPrice(100.0) - .instanceType("m3.xlarge") - .weightedCapacity(1) - .build(); - - InstanceTypeConfig m4xLarge = InstanceTypeConfig.builder() - .bidPriceAsPercentageOfOnDemandPrice(100.0) - .instanceType("m4.xlarge") - .weightedCapacity(1) - .build(); - - InstanceTypeConfig m5xLarge = InstanceTypeConfig.builder() - .bidPriceAsPercentageOfOnDemandPrice(100.0) - .instanceType("m5.xlarge") - .weightedCapacity(1) - .build(); - - InstanceTypeConfig r5xlarge = InstanceTypeConfig.builder() - .bidPriceAsPercentageOfOnDemandPrice(100.0) - .instanceType("r5.xlarge") - .weightedCapacity(2) - .build(); - - InstanceTypeConfig r4xlarge = InstanceTypeConfig.builder() - .bidPriceAsPercentageOfOnDemandPrice(100.0) - .instanceType("r4.xlarge") - .weightedCapacity(2) - .build(); - - InstanceTypeConfig r3xlarge = InstanceTypeConfig.builder() - .bidPriceAsPercentageOfOnDemandPrice(100.0) - .instanceType("r3.xlarge") - .weightedCapacity(2) - .build(); - - InstanceTypeConfig c32xlarge = InstanceTypeConfig.builder() - .bidPriceAsPercentageOfOnDemandPrice(100.0) - .instanceType("c3.2xlarge") - .weightedCapacity(4) - .build(); - - InstanceTypeConfig c42xlarge = InstanceTypeConfig.builder() - .bidPriceAsPercentageOfOnDemandPrice(100.0) - .instanceType("c4.2xlarge") - .weightedCapacity(4) - .build(); - - InstanceFleetConfig masterFleet = InstanceFleetConfig.builder() - .name("master-fleet") - .instanceFleetType(InstanceFleetType.MASTER) - .instanceTypeConfigs(Arrays.asList( - m3xLarge, - m4xLarge, - m5xLarge - )) - .targetOnDemandCapacity(1) - .build(); - - InstanceFleetConfig coreFleet = InstanceFleetConfig.builder() - .name("core-fleet") - .instanceFleetType(InstanceFleetType.CORE) - .instanceTypeConfigs(Arrays.asList( - m3xLarge, - m4xLarge, - r4xlarge, - r3xlarge, - c32xlarge - )) - .targetOnDemandCapacity(20) - .targetSpotCapacity(10) - .build(); - - InstanceFleetConfig taskFleet = InstanceFleetConfig.builder() - .name("task-fleet") - .instanceFleetType(InstanceFleetType.TASK) - .instanceTypeConfigs(Arrays.asList( - m4xLarge, - r5xlarge, - r4xlarge, - c32xlarge, - c42xlarge - )) - .targetOnDemandCapacity(8) - .targetSpotCapacity(40) - .build(); - - JobFlowInstancesConfig flowInstancesConfig = JobFlowInstancesConfig.builder() - .ec2KeyName(System.getenv("keypair1")) - .keepJobFlowAliveWhenNoSteps(true) - .instanceFleets(Arrays.asList( - masterFleet, - coreFleet, - taskFleet - )) - .ec2SubnetId("subnet-cca64baa") - .build(); - - RunJobFlowRequest flowRequest = RunJobFlowRequest.builder() - .name("emr-spot-example") - .instances(flowInstancesConfig) - .serviceRole("EMR_DefaultRole") - .jobFlowRole("EMR_EC2_DefaultRole") - .visibleToAllUsers(true) - .applications(java.util.Arrays.asList( - Application.builder().name("Spark").build() - )) - .releaseLabel("emr-5.29.0") - .build(); - - RunJobFlowResponse response = emr.runJobFlow(flowRequest); - System.out.println(response.toString()); - - } catch (EmrException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + public static void main(String[] args) throws Exception { + Region region = Region.US_EAST_1; + EmrClient emrClient = EmrClient.builder() + .region(region) + .build(); + createFleet(emrClient); + } + + public static void createFleet(EmrClient emr) { + try { + InstanceTypeConfig m3xLarge = InstanceTypeConfig.builder() + .bidPriceAsPercentageOfOnDemandPrice(100.0) + .instanceType("m3.xlarge") + .weightedCapacity(1) + .build(); + + InstanceTypeConfig m4xLarge = InstanceTypeConfig.builder() + .bidPriceAsPercentageOfOnDemandPrice(100.0) + .instanceType("m4.xlarge") + .weightedCapacity(1) + .build(); + + InstanceTypeConfig m5xLarge = InstanceTypeConfig.builder() + .bidPriceAsPercentageOfOnDemandPrice(100.0) + .instanceType("m5.xlarge") + .weightedCapacity(1) + .build(); + + InstanceTypeConfig r5xlarge = InstanceTypeConfig.builder() + .bidPriceAsPercentageOfOnDemandPrice(100.0) + .instanceType("r5.xlarge") + .weightedCapacity(2) + .build(); + + InstanceTypeConfig r4xlarge = InstanceTypeConfig.builder() + .bidPriceAsPercentageOfOnDemandPrice(100.0) + .instanceType("r4.xlarge") + .weightedCapacity(2) + .build(); + + InstanceTypeConfig r3xlarge = InstanceTypeConfig.builder() + .bidPriceAsPercentageOfOnDemandPrice(100.0) + .instanceType("r3.xlarge") + .weightedCapacity(2) + .build(); + + InstanceTypeConfig c32xlarge = InstanceTypeConfig.builder() + .bidPriceAsPercentageOfOnDemandPrice(100.0) + .instanceType("c3.2xlarge") + .weightedCapacity(4) + .build(); + + InstanceTypeConfig c42xlarge = InstanceTypeConfig.builder() + .bidPriceAsPercentageOfOnDemandPrice(100.0) + .instanceType("c4.2xlarge") + .weightedCapacity(4) + .build(); + + InstanceFleetConfig masterFleet = InstanceFleetConfig.builder() + .name("master-fleet") + .instanceFleetType(InstanceFleetType.MASTER) + .instanceTypeConfigs(Arrays.asList( + m3xLarge, + m4xLarge, + m5xLarge)) + .targetOnDemandCapacity(1) + .build(); + + InstanceFleetConfig coreFleet = InstanceFleetConfig.builder() + .name("core-fleet") + .instanceFleetType(InstanceFleetType.CORE) + .instanceTypeConfigs(Arrays.asList( + m3xLarge, + m4xLarge, + r4xlarge, + r3xlarge, + c32xlarge)) + .targetOnDemandCapacity(20) + .targetSpotCapacity(10) + .build(); + + InstanceFleetConfig taskFleet = InstanceFleetConfig.builder() + .name("task-fleet") + .instanceFleetType(InstanceFleetType.TASK) + .instanceTypeConfigs(Arrays.asList( + m4xLarge, + r5xlarge, + r4xlarge, + c32xlarge, + c42xlarge)) + .targetOnDemandCapacity(8) + .targetSpotCapacity(40) + .build(); + + JobFlowInstancesConfig flowInstancesConfig = JobFlowInstancesConfig.builder() + .ec2KeyName(System.getenv("keypair1")) + .keepJobFlowAliveWhenNoSteps(true) + .instanceFleets(Arrays.asList( + masterFleet, + coreFleet, + taskFleet)) + .ec2SubnetId("subnet-cca64baa") + .build(); + + RunJobFlowRequest flowRequest = RunJobFlowRequest.builder() + .name("emr-spot-example") + .instances(flowInstancesConfig) + .serviceRole("EMR_DefaultRole") + .jobFlowRole("EMR_EC2_DefaultRole") + .visibleToAllUsers(true) + .applications(java.util.Arrays.asList( + Application.builder().name("Spark").build())) + .releaseLabel("emr-5.29.0") + .build(); + + RunJobFlowResponse response = emr.runJobFlow(flowRequest); + System.out.println(response.toString()); + + } catch (EmrException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } } - } } // snippet-end:[emr.java2._create_fleet.main] \ No newline at end of file diff --git a/javav2/example_code/emr/src/main/java/aws/example/emr/CreateHiveCluster.java b/javav2/example_code/emr/src/main/java/aws/example/emr/CreateHiveCluster.java index 4b189dafe1c..3a8a37705ba 100644 --- a/javav2/example_code/emr/src/main/java/aws/example/emr/CreateHiveCluster.java +++ b/javav2/example_code/emr/src/main/java/aws/example/emr/CreateHiveCluster.java @@ -1,13 +1,5 @@ -//snippet-sourcedescription:[CreateHiveCluster.java demonstrates how to create a cluster.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EMR] -//snippet-sourcetype:[full-example] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.emr; @@ -28,111 +20,109 @@ // snippet-end:[emr.java2._create_hive.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateHiveCluster { - public static void main(String[] args) { - final String usage = """ - - Usage: - - Where: - jar - A path to a JAR file run during the step.\s - myClass - The name of the main class in the specified Java file.\s - keys - The name of the Amazon EC2 key pair.\s - logUri - The Amazon S3 bucket where the logs are located (for example, s3:///logs/).\s - name - The name of the job flow.\s - - """; - - if (args.length != 5) { - System.out.println(usage); - System.exit(1); + public static void main(String[] args) { + final String usage = """ + + Usage: + + Where: + jar - A path to a JAR file run during the step.\s + myClass - The name of the main class in the specified Java file.\s + keys - The name of the Amazon EC2 key pair.\s + logUri - The Amazon S3 bucket where the logs are located (for example, s3:///logs/).\s + name - The name of the job flow.\s + + """; + + if (args.length != 5) { + System.out.println(usage); + System.exit(1); + } + + String jar = args[0]; + String myClass = args[1]; + String keys = args[2]; + String logUri = args[3]; + String name = args[4]; + Region region = Region.US_WEST_2; + EmrClient emrClient = EmrClient.builder() + .region(region) + .build(); + + String jobFlowId = createCluster(emrClient, jar, myClass, keys, logUri, name); + System.out.println("The job flow id is " + jobFlowId); + emrClient.close(); } - String jar = args[0]; - String myClass = args[1]; - String keys = args[2]; - String logUri = args[3]; - String name = args[4]; - Region region = Region.US_WEST_2; - EmrClient emrClient = EmrClient.builder() - .region(region) - .build(); - - String jobFlowId = createCluster(emrClient, jar, myClass, keys, logUri, name); - System.out.println("The job flow id is " + jobFlowId); - emrClient.close(); - } - - public static String createCluster(EmrClient emrClient, String jar, - String myClass, - String keys, - String logUri, - String name) { - - try { - HadoopJarStepConfig jarStepConfig = HadoopJarStepConfig.builder() - .jar(jar) - .mainClass(myClass) - .build(); - - Application hiveApp = Application.builder() - .name("Hive") - .build(); - - Map hiveProperties = new HashMap<>(); - hiveProperties.put("hive.join.emit.interval", "1000"); - hiveProperties.put("hive.merge.mapfiles", "true"); - - Configuration configuration = Configuration.builder() - .classification("hive-site") - .properties(hiveProperties) - .build(); - - StepConfig enabledebugging = StepConfig.builder() - .name("Enable debugging") - .actionOnFailure("TERMINATE_JOB_FLOW") - .hadoopJarStep(jarStepConfig) - .build(); - - JobFlowInstancesConfig instancesConfig = JobFlowInstancesConfig.builder() - .ec2SubnetId("subnet-206a9c58") - .ec2KeyName(keys) - .instanceCount(3) - .keepJobFlowAliveWhenNoSteps(true) - .masterInstanceType("m4.large") - .slaveInstanceType("m4.large") - .build(); - - RunJobFlowRequest jobFlowRequest = RunJobFlowRequest.builder() - .name(name) - .configurations(configuration) - .releaseLabel("emr-5.20.0") - .steps(enabledebugging) - .applications(hiveApp) - .logUri(logUri) - .serviceRole("EMR_DefaultRole") - .jobFlowRole("EMR_EC2_DefaultRole") - .instances(instancesConfig) - .build(); - - RunJobFlowResponse response = emrClient.runJobFlow(jobFlowRequest); - return response.jobFlowId(); - - } catch (EmrException e) { - System.err.println(e.getMessage()); - System.exit(1); + public static String createCluster(EmrClient emrClient, String jar, + String myClass, + String keys, + String logUri, + String name) { + + try { + HadoopJarStepConfig jarStepConfig = HadoopJarStepConfig.builder() + .jar(jar) + .mainClass(myClass) + .build(); + + Application hiveApp = Application.builder() + .name("Hive") + .build(); + + Map hiveProperties = new HashMap<>(); + hiveProperties.put("hive.join.emit.interval", "1000"); + hiveProperties.put("hive.merge.mapfiles", "true"); + + Configuration configuration = Configuration.builder() + .classification("hive-site") + .properties(hiveProperties) + .build(); + + StepConfig enabledebugging = StepConfig.builder() + .name("Enable debugging") + .actionOnFailure("TERMINATE_JOB_FLOW") + .hadoopJarStep(jarStepConfig) + .build(); + + JobFlowInstancesConfig instancesConfig = JobFlowInstancesConfig.builder() + .ec2SubnetId("subnet-206a9c58") + .ec2KeyName(keys) + .instanceCount(3) + .keepJobFlowAliveWhenNoSteps(true) + .masterInstanceType("m4.large") + .slaveInstanceType("m4.large") + .build(); + + RunJobFlowRequest jobFlowRequest = RunJobFlowRequest.builder() + .name(name) + .configurations(configuration) + .releaseLabel("emr-5.20.0") + .steps(enabledebugging) + .applications(hiveApp) + .logUri(logUri) + .serviceRole("EMR_DefaultRole") + .jobFlowRole("EMR_EC2_DefaultRole") + .instances(instancesConfig) + .build(); + + RunJobFlowResponse response = emrClient.runJobFlow(jobFlowRequest); + return response.jobFlowId(); + + } catch (EmrException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + + return ""; } - - return ""; - } } // snippet-end:[emr.java2._create_hive.main] - - - diff --git a/javav2/example_code/emr/src/main/java/aws/example/emr/CreateSparkCluster.java b/javav2/example_code/emr/src/main/java/aws/example/emr/CreateSparkCluster.java index edc4e18785a..b089fa802b3 100644 --- a/javav2/example_code/emr/src/main/java/aws/example/emr/CreateSparkCluster.java +++ b/javav2/example_code/emr/src/main/java/aws/example/emr/CreateSparkCluster.java @@ -1,12 +1,6 @@ -//snippet-sourcedescription:[CreateSparkCluster.java demonstrates how to create and start running a new cluster (job flow).] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EMR] -//snippet-sourcetype:[full-example] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package aws.example.emr; // snippet-start:[emr.java2._create_spark.main] @@ -23,98 +17,99 @@ // snippet-end:[emr.java2._create_spark.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateSparkCluster { - public static void main(String[] args) { - final String usage = """ - - Usage: - - Where: - jar - A path to a JAR file run during the step.\s - myClass - The name of the main class in the specified Java file.\s - keys - The name of the Amazon EC2 key pair.\s - logUri - The Amazon S3 bucket where the logs are located (for example, s3:///logs/).\s - name - The name of the job flow.\s - - """; - - if (args.length != 5) { - System.out.println(usage); - System.exit(1); + public static void main(String[] args) { + final String usage = """ + + Usage: + + Where: + jar - A path to a JAR file run during the step.\s + myClass - The name of the main class in the specified Java file.\s + keys - The name of the Amazon EC2 key pair.\s + logUri - The Amazon S3 bucket where the logs are located (for example, s3:///logs/).\s + name - The name of the job flow.\s + + """; + + if (args.length != 5) { + System.out.println(usage); + System.exit(1); + } + + String jar = args[0]; + String myClass = args[1]; + String keys = args[2]; + String logUri = args[3]; + String name = args[4]; + Region region = Region.US_WEST_2; + EmrClient emrClient = EmrClient.builder() + .region(region) + .build(); + + String jobFlowId = createCluster(emrClient, jar, myClass, keys, logUri, name); + System.out.println("The job flow id is " + jobFlowId); + emrClient.close(); } - String jar = args[0]; - String myClass = args[1]; - String keys = args[2]; - String logUri = args[3]; - String name = args[4]; - Region region = Region.US_WEST_2; - EmrClient emrClient = EmrClient.builder() - .region(region) - .build(); - - String jobFlowId = createCluster(emrClient, jar, myClass, keys, logUri, name); - System.out.println("The job flow id is " + jobFlowId); - emrClient.close(); - } - - public static String createCluster(EmrClient emrClient, - String jar, - String myClass, - String keys, - String logUri, - String name) { - - try { - HadoopJarStepConfig jarStepConfig = HadoopJarStepConfig.builder() - .jar(jar) - .mainClass(myClass) - .build(); - - Application app = Application.builder() - .name("Spark") - .build(); - - StepConfig enabledebugging = StepConfig.builder() - .name("Enable debugging") - .actionOnFailure("TERMINATE_JOB_FLOW") - .hadoopJarStep(jarStepConfig) - .build(); - - JobFlowInstancesConfig instancesConfig = JobFlowInstancesConfig.builder() - .ec2SubnetId("subnet-206a9c58") - .ec2KeyName(keys) - .instanceCount(3) - .keepJobFlowAliveWhenNoSteps(true) - .masterInstanceType("m4.large") - .slaveInstanceType("m4.large") - .build(); - - RunJobFlowRequest jobFlowRequest = RunJobFlowRequest.builder() - .name(name) - .releaseLabel("emr-5.20.0") - .steps(enabledebugging) - .applications(app) - .logUri(logUri) - .serviceRole("EMR_DefaultRole") - .jobFlowRole("EMR_EC2_DefaultRole") - .instances(instancesConfig) - .build(); - - RunJobFlowResponse response = emrClient.runJobFlow(jobFlowRequest); - return response.jobFlowId(); - - } catch (EmrException e) { - System.err.println(e.getMessage()); - System.exit(1); + public static String createCluster(EmrClient emrClient, + String jar, + String myClass, + String keys, + String logUri, + String name) { + + try { + HadoopJarStepConfig jarStepConfig = HadoopJarStepConfig.builder() + .jar(jar) + .mainClass(myClass) + .build(); + + Application app = Application.builder() + .name("Spark") + .build(); + + StepConfig enabledebugging = StepConfig.builder() + .name("Enable debugging") + .actionOnFailure("TERMINATE_JOB_FLOW") + .hadoopJarStep(jarStepConfig) + .build(); + + JobFlowInstancesConfig instancesConfig = JobFlowInstancesConfig.builder() + .ec2SubnetId("subnet-206a9c58") + .ec2KeyName(keys) + .instanceCount(3) + .keepJobFlowAliveWhenNoSteps(true) + .masterInstanceType("m4.large") + .slaveInstanceType("m4.large") + .build(); + + RunJobFlowRequest jobFlowRequest = RunJobFlowRequest.builder() + .name(name) + .releaseLabel("emr-5.20.0") + .steps(enabledebugging) + .applications(app) + .logUri(logUri) + .serviceRole("EMR_DefaultRole") + .jobFlowRole("EMR_EC2_DefaultRole") + .instances(instancesConfig) + .build(); + + RunJobFlowResponse response = emrClient.runJobFlow(jobFlowRequest); + return response.jobFlowId(); + + } catch (EmrException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + return ""; } - return ""; - } } // snippet-end:[emr.java2._create_spark.main] diff --git a/javav2/example_code/emr/src/main/java/aws/example/emr/CustomEmrfsMaterials.java b/javav2/example_code/emr/src/main/java/aws/example/emr/CustomEmrfsMaterials.java index 6105f3818f8..8bd949de35b 100644 --- a/javav2/example_code/emr/src/main/java/aws/example/emr/CustomEmrfsMaterials.java +++ b/javav2/example_code/emr/src/main/java/aws/example/emr/CustomEmrfsMaterials.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[CustomEmrfsMaterials.java demonstrates how to create a cluster, specifying values in the emrfs-site configuration classification for a custom encryption materials provider.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EMR] -//snippet-sourcetype:[full-example] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.emr; @@ -27,111 +20,112 @@ // snippet-end:[emr.java2.emrfs.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CustomEmrfsMaterials { - public static void main(String[] args) { - final String usage = """ - - Usage: - - Where: - jar - A path to a JAR file run during the step.\s - myClass - The name of the main class in the specified Java file.\s - keys - The name of the Amazon EC2 key pair.\s - logUri - The Amazon S3 bucket where the logs are located (for example, s3:///logs/).\s - name - The name of the job flow.\s - """; - - if (args.length != 5) { - System.out.println(usage); - System.exit(1); + public static void main(String[] args) { + final String usage = """ + + Usage: + + Where: + jar - A path to a JAR file run during the step.\s + myClass - The name of the main class in the specified Java file.\s + keys - The name of the Amazon EC2 key pair.\s + logUri - The Amazon S3 bucket where the logs are located (for example, s3:///logs/).\s + name - The name of the job flow.\s + """; + + if (args.length != 5) { + System.out.println(usage); + System.exit(1); + } + + String jar = args[0]; + String myClass = args[1]; + String keys = args[2]; + String logUri = args[3]; + String name = args[4]; + Region region = Region.US_WEST_2; + EmrClient emrClient = EmrClient.builder() + .region(region) + .build(); + + String jobFlowId = createEmrfsCluster(emrClient, jar, myClass, keys, logUri, name); + System.out.println("The job flow id is " + jobFlowId); } - String jar = args[0]; - String myClass = args[1]; - String keys = args[2]; - String logUri = args[3]; - String name = args[4]; - Region region = Region.US_WEST_2; - EmrClient emrClient = EmrClient.builder() - .region(region) - .build(); - - String jobFlowId = createEmrfsCluster(emrClient, jar, myClass, keys, logUri, name); - System.out.println("The job flow id is " + jobFlowId); - } - - public static String createEmrfsCluster(EmrClient emrClient, - String jar, - String myClass, - String keys, - String logUri, - String name) { - - try { - Map emrfsProperties = new HashMap<>(); - emrfsProperties.put("fs.s3.cse.encryptionMaterialsProvider.uri", "s3://emrscott/MyCustomEncryptionMaterialsProvider.jar"); - emrfsProperties.put("fs.s3.cse.enabled", "true"); - emrfsProperties.put("fs.s3.consistent", "true"); - emrfsProperties.put("fs.s3.cse.encryptionMaterialsProvider", "full.class.name.of.EncryptionMaterialsProvider"); - - - Configuration configuration = Configuration.builder() - .classification("emrfs-site") - .properties(emrfsProperties) - .build(); - - HadoopJarStepConfig jarStepConfig = HadoopJarStepConfig.builder() - .jar(jar) - .mainClass(myClass) - .build(); - - Application app = Application.builder() - .name("Spark") - .build(); - - StepConfig enabledebugging = StepConfig.builder() - .name("Enable debugging") - .actionOnFailure("TERMINATE_JOB_FLOW") - .hadoopJarStep(jarStepConfig) - .build(); - - JobFlowInstancesConfig instancesConfig = JobFlowInstancesConfig.builder() - .ec2SubnetId("subnet-206a9c58") - .ec2KeyName(keys) - .instanceCount(3) - .keepJobFlowAliveWhenNoSteps(true) - .masterInstanceType("m4.large") - .slaveInstanceType("m4.large") - .build(); - - RunJobFlowRequest jobFlowRequest = RunJobFlowRequest.builder() - .name(name) - .configurations(configuration) - .releaseLabel("emr-5.20.0") - .steps(enabledebugging) - .applications(app) - .logUri(logUri) - .serviceRole("EMR_DefaultRole") - .jobFlowRole("EMR_EC2_DefaultRole") - .instances(instancesConfig) - .build(); - - RunJobFlowResponse response = emrClient.runJobFlow(jobFlowRequest); - return response.jobFlowId(); - - } catch (EmrException e) { - System.err.println(e.getMessage()); - System.exit(1); + public static String createEmrfsCluster(EmrClient emrClient, + String jar, + String myClass, + String keys, + String logUri, + String name) { + + try { + Map emrfsProperties = new HashMap<>(); + emrfsProperties.put("fs.s3.cse.encryptionMaterialsProvider.uri", + "s3://emrscott/MyCustomEncryptionMaterialsProvider.jar"); + emrfsProperties.put("fs.s3.cse.enabled", "true"); + emrfsProperties.put("fs.s3.consistent", "true"); + emrfsProperties.put("fs.s3.cse.encryptionMaterialsProvider", + "full.class.name.of.EncryptionMaterialsProvider"); + + Configuration configuration = Configuration.builder() + .classification("emrfs-site") + .properties(emrfsProperties) + .build(); + + HadoopJarStepConfig jarStepConfig = HadoopJarStepConfig.builder() + .jar(jar) + .mainClass(myClass) + .build(); + + Application app = Application.builder() + .name("Spark") + .build(); + + StepConfig enabledebugging = StepConfig.builder() + .name("Enable debugging") + .actionOnFailure("TERMINATE_JOB_FLOW") + .hadoopJarStep(jarStepConfig) + .build(); + + JobFlowInstancesConfig instancesConfig = JobFlowInstancesConfig.builder() + .ec2SubnetId("subnet-206a9c58") + .ec2KeyName(keys) + .instanceCount(3) + .keepJobFlowAliveWhenNoSteps(true) + .masterInstanceType("m4.large") + .slaveInstanceType("m4.large") + .build(); + + RunJobFlowRequest jobFlowRequest = RunJobFlowRequest.builder() + .name(name) + .configurations(configuration) + .releaseLabel("emr-5.20.0") + .steps(enabledebugging) + .applications(app) + .logUri(logUri) + .serviceRole("EMR_DefaultRole") + .jobFlowRole("EMR_EC2_DefaultRole") + .instances(instancesConfig) + .build(); + + RunJobFlowResponse response = emrClient.runJobFlow(jobFlowRequest); + return response.jobFlowId(); + + } catch (EmrException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + + return ""; } - - return ""; - } } // snippet-end:[emr.java2.emrfs.main] - diff --git a/javav2/example_code/emr/src/main/java/aws/example/emr/DescribeCluster.java b/javav2/example_code/emr/src/main/java/aws/example/emr/DescribeCluster.java index c8ed5b2280e..64001abbfa3 100644 --- a/javav2/example_code/emr/src/main/java/aws/example/emr/DescribeCluster.java +++ b/javav2/example_code/emr/src/main/java/aws/example/emr/DescribeCluster.java @@ -1,12 +1,6 @@ -//snippet-sourcedescription:[DescribeCluster.java demonstrates how to describe a cluster.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EMR] -//snippet-sourcetype:[full-example] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package aws.example.emr; // snippet-start:[emr.java2.describe_cluster.main] @@ -19,7 +13,8 @@ // snippet-end:[emr.java2.describe_cluster.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,11 +24,11 @@ public class DescribeCluster { public static void main(String[] args) { final String usage = """ - Usage: \s + Usage: \s - Where: - clusterId - The identifier of the cluster to describe.\s - """; + Where: + clusterId - The identifier of the cluster to describe.\s + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +38,8 @@ public static void main(String[] args) { String clusterId = args[0]; Region region = Region.US_WEST_2; EmrClient emrClient = EmrClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeMyCluster(emrClient, clusterId); emrClient.close(); @@ -53,8 +48,8 @@ public static void main(String[] args) { public static void describeMyCluster(EmrClient emrClient, String clusterId) { try { DescribeClusterRequest clusterRequest = DescribeClusterRequest.builder() - .clusterId(clusterId) - .build(); + .clusterId(clusterId) + .build(); DescribeClusterResponse response = emrClient.describeCluster(clusterRequest); System.out.println("The name of the cluster is " + response.cluster().name()); @@ -66,4 +61,3 @@ public static void describeMyCluster(EmrClient emrClient, String clusterId) { } } // snippet-end:[emr.java2.describe_cluster.main] - diff --git a/javav2/example_code/emr/src/main/java/aws/example/emr/ListClusters.java b/javav2/example_code/emr/src/main/java/aws/example/emr/ListClusters.java index 8838f705665..ceee9e64330 100644 --- a/javav2/example_code/emr/src/main/java/aws/example/emr/ListClusters.java +++ b/javav2/example_code/emr/src/main/java/aws/example/emr/ListClusters.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[ListClusters.java demonstrates how to list clusters.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EMR] -//snippet-sourcetype:[full-example] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package aws.example.emr; @@ -22,7 +15,8 @@ // snippet-end:[emr.java2.list_clusters.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,8 +26,8 @@ public class ListClusters { public static void main(String[] args) { Region region = Region.US_WEST_2; EmrClient emrClient = EmrClient.builder() - .region(region) - .build(); + .region(region) + .build(); listAllClusters(emrClient); emrClient.close(); @@ -42,7 +36,7 @@ public static void main(String[] args) { public static void listAllClusters(EmrClient emrClient) { try { ListClustersRequest clustersRequest = ListClustersRequest.builder() - .build(); + .build(); ListClustersResponse response = emrClient.listClusters(clustersRequest); List clusters = response.clusters(); diff --git a/javav2/example_code/emr/src/main/java/aws/example/emr/TerminateJobFlow.java b/javav2/example_code/emr/src/main/java/aws/example/emr/TerminateJobFlow.java index ef71a43fffb..1baa8d80c1b 100644 --- a/javav2/example_code/emr/src/main/java/aws/example/emr/TerminateJobFlow.java +++ b/javav2/example_code/emr/src/main/java/aws/example/emr/TerminateJobFlow.java @@ -1,12 +1,6 @@ -//snippet-sourcedescription:[TerminateJobFlow.java demonstrates how to terminate a given job flow.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-keyword:[Amazon EMR] -//snippet-sourcetype:[full-example] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package aws.example.emr; // snippet-start:[emr.java2.terminate_job.main] @@ -18,7 +12,8 @@ // snippet-end:[emr.java2.terminate_job.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +23,12 @@ public class TerminateJobFlow { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - id - An id of a job flow to shut down. + Where: + id - An id of a job flow to shut down. - """; + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +38,8 @@ public static void main(String[] args) { String id = args[0]; Region region = Region.US_WEST_2; EmrClient emrClient = EmrClient.builder() - .region(region) - .build(); + .region(region) + .build(); terminateFlow(emrClient, id); emrClient.close(); @@ -53,8 +48,8 @@ public static void main(String[] args) { public static void terminateFlow(EmrClient emrClient, String id) { try { TerminateJobFlowsRequest jobFlowsRequest = TerminateJobFlowsRequest.builder() - .jobFlowIds(id) - .build(); + .jobFlowIds(id) + .build(); emrClient.terminateJobFlows(jobFlowsRequest); System.out.println("You have successfully terminated " + id); diff --git a/javav2/example_code/emr/src/test/java/EMRTest.java b/javav2/example_code/emr/src/test/java/EMRTest.java index f0ca769df3b..08c142a3a7a 100644 --- a/javav2/example_code/emr/src/test/java/EMRTest.java +++ b/javav2/example_code/emr/src/test/java/EMRTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import aws.example.emr.*; import com.google.gson.Gson; @@ -24,19 +22,19 @@ public class EMRTest { private static EmrClient emrClient; private static String jar = ""; - private static String myClass = "" ; - private static String keys = "" ; - private static String logUri = "" ; - private static String name = "" ; + private static String myClass = ""; + private static String keys = ""; + private static String logUri = ""; + private static String name = ""; private static String jobFlowId = ""; private static String existingClusterId = ""; @BeforeAll public static void setUp() throws IOException { emrClient = EmrClient.builder() - .region(Region.US_WEST_2) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_WEST_2) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -47,31 +45,32 @@ public static void setUp() throws IOException { keys = values.getKeys(); logUri = values.getLogUri(); name = values.getName(); - existingClusterId= values.getExistingClusterId(); - - - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - - try (InputStream input = EMRTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - // Populate the data members required for all tests. - prop.load(input); - jar = prop.getProperty("jar"); - myClass = prop.getProperty("myClass"); - keys = prop.getProperty("keys"); - logUri = prop.getProperty("logUri"); - name = prop.getProperty("name"); - existingClusterId= prop.getProperty("existingClusterId"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + existingClusterId = values.getExistingClusterId(); + + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * + * try (InputStream input = + * EMRTest.class.getClassLoader().getResourceAsStream("config.properties")) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * // Populate the data members required for all tests. + * prop.load(input); + * jar = prop.getProperty("jar"); + * myClass = prop.getProperty("myClass"); + * keys = prop.getProperty("keys"); + * logUri = prop.getProperty("logUri"); + * name = prop.getProperty("name"); + * existingClusterId= prop.getProperty("existingClusterId"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @@ -85,21 +84,21 @@ public void createClusterTest() { @Test @Order(2) public void describeClusterTest() { - assertDoesNotThrow(() ->DescribeCluster.describeMyCluster(emrClient, existingClusterId)); + assertDoesNotThrow(() -> DescribeCluster.describeMyCluster(emrClient, existingClusterId)); System.out.println("Test 2 passed"); } @Test @Order(3) public void listClusterTest() { - assertDoesNotThrow(() ->ListClusters.listAllClusters(emrClient)); + assertDoesNotThrow(() -> ListClusters.listAllClusters(emrClient)); System.out.println("Test 3 passed"); } @Test @Order(4) public void createEmrFleetTest() { - assertDoesNotThrow(() ->CreateEmrFleet.createFleet(emrClient)); + assertDoesNotThrow(() -> CreateEmrFleet.createFleet(emrClient)); System.out.println("Test 4 passed"); } @@ -112,42 +111,43 @@ public void addStepsTest() { @Test @Order(6) - public void createSparkClusterTest(){ - assertDoesNotThrow(() ->CreateSparkCluster.createCluster(emrClient, jar, myClass, keys, logUri, name)); + public void createSparkClusterTest() { + assertDoesNotThrow(() -> CreateSparkCluster.createCluster(emrClient, jar, myClass, keys, logUri, name)); System.out.println("Test 6 passed"); } @Test @Order(7) public void createHiveClusterTest() { - assertDoesNotThrow(() ->CreateHiveCluster.createCluster(emrClient, jar, myClass, keys, logUri, name)); + assertDoesNotThrow(() -> CreateHiveCluster.createCluster(emrClient, jar, myClass, keys, logUri, name)); System.out.println("Test 7 passed"); } @Test @Order(8) - public void customEmrfsMaterialsTest(){ - assertDoesNotThrow(() ->CustomEmrfsMaterials.createEmrfsCluster(emrClient, jar, myClass, keys, logUri, name)); + public void customEmrfsMaterialsTest() { + assertDoesNotThrow(() -> CustomEmrfsMaterials.createEmrfsCluster(emrClient, jar, myClass, keys, logUri, name)); System.out.println("Test 8 passed"); } @Test @Order(9) - public void terminateJobFlowTest(){ - assertDoesNotThrow(() ->TerminateJobFlow.terminateFlow(emrClient, existingClusterId)); + public void terminateJobFlowTest() { + assertDoesNotThrow(() -> TerminateJobFlow.terminateFlow(emrClient, existingClusterId)); System.out.println("Test 9 passed"); } + private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "text/emr"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -166,13 +166,14 @@ class SecretValues { private String logUri; - public String getLogUri() { return logUri; } + public String getJar() { return jar; } + public String getMyClass() { return myClass; } @@ -190,4 +191,3 @@ public String getExistingClusterId() { } } } - diff --git a/javav2/example_code/eventbridge/src/main/java/com/example/eventbridge/CreateRuleSchedule.java b/javav2/example_code/eventbridge/src/main/java/com/example/eventbridge/CreateRuleSchedule.java index 3863185e2f9..9e066dbf72e 100644 --- a/javav2/example_code/eventbridge/src/main/java/com/example/eventbridge/CreateRuleSchedule.java +++ b/javav2/example_code/eventbridge/src/main/java/com/example/eventbridge/CreateRuleSchedule.java @@ -1,15 +1,8 @@ -//snippet-sourcedescription:[CreateRuleSchedule.java demonstrates how to create an Amazon EventBridge rule that has a target and runs on a schedule.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EventBridge] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.eventbridge; - // snippet-start:[eventbridge.java2._create_schedule_rule.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.eventbridge.EventBridgeClient; @@ -21,7 +14,8 @@ // snippet-end:[eventbridge.java2._create_schedule_rule.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,42 +25,42 @@ public class CreateRuleSchedule { public static void main(String[] args) { final String usage = """ - Usage: - - - Where: - ruleName - The name of the rule to create.\s - cronExpression - The scheduling expression. For example, rate(5 minutes) - lambdaARN - The ARN value of a Lambda function that is the target - json - The JSON to pass the Lambda function - targetId - The ID of the target within the specified rule\s - """; - - if (args.length != 5) { - System.out.println(usage); - System.exit(1); - } - - String ruleName = args[0]; - String cronExpression = args[1]; - String lambdaARN = args[2]; - String json = args[3]; - String targetId = args[4]; - - Region region = Region.US_WEST_2; - EventBridgeClient eventBrClient = EventBridgeClient.builder() + Usage: + + + Where: + ruleName - The name of the rule to create.\s + cronExpression - The scheduling expression. For example, rate(5 minutes) + lambdaARN - The ARN value of a Lambda function that is the target + json - The JSON to pass the Lambda function + targetId - The ID of the target within the specified rule\s + """; + + if (args.length != 5) { + System.out.println(usage); + System.exit(1); + } + + String ruleName = args[0]; + String cronExpression = args[1]; + String lambdaARN = args[2]; + String json = args[3]; + String targetId = args[4]; + + Region region = Region.US_WEST_2; + EventBridgeClient eventBrClient = EventBridgeClient.builder() .region(region) .build(); - createEBRule(eventBrClient, ruleName, cronExpression); - putRuleTarget(eventBrClient, ruleName, lambdaARN, json, targetId ); - eventBrClient.close(); - } + createEBRule(eventBrClient, ruleName, cronExpression); + putRuleTarget(eventBrClient, ruleName, lambdaARN, json, targetId); + eventBrClient.close(); + } - // snippet-start:[eventbridge.java2._create_schedule_rule.main] - public static void createEBRule(EventBridgeClient eventBrClient, String ruleName, String cronExpression) { - try { - PutRuleRequest ruleRequest = PutRuleRequest.builder() + // snippet-start:[eventbridge.java2._create_schedule_rule.main] + public static void createEBRule(EventBridgeClient eventBrClient, String ruleName, String cronExpression) { + try { + PutRuleRequest ruleRequest = PutRuleRequest.builder() .name(ruleName) .eventBusName("default") .scheduleExpression(cronExpression) @@ -74,38 +68,39 @@ public static void createEBRule(EventBridgeClient eventBrClient, String ruleName .description("A test rule that runs on a schedule created by the Java API") .build(); - PutRuleResponse ruleResponse = eventBrClient.putRule(ruleRequest); - System.out.println("The ARN of the new rule is "+ ruleResponse.ruleArn()); + PutRuleResponse ruleResponse = eventBrClient.putRule(ruleRequest); + System.out.println("The ARN of the new rule is " + ruleResponse.ruleArn()); - } catch (EventBridgeException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } + } catch (EventBridgeException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); } - // snippet-end:[eventbridge.java2._create_schedule_rule.main] - - // snippet-start:[eventbridge.java2._create_schedule_rule_target.main] - public static void putRuleTarget(EventBridgeClient eventBrClient, String ruleName, String lambdaARN, String json, String targetId ) { - try { - Target lambdaTarget = Target.builder() + } + // snippet-end:[eventbridge.java2._create_schedule_rule.main] + + // snippet-start:[eventbridge.java2._create_schedule_rule_target.main] + public static void putRuleTarget(EventBridgeClient eventBrClient, String ruleName, String lambdaARN, String json, + String targetId) { + try { + Target lambdaTarget = Target.builder() .arn(lambdaARN) .id(targetId) .input(json) .build(); - PutTargetsRequest targetsRequest = PutTargetsRequest.builder() + PutTargetsRequest targetsRequest = PutTargetsRequest.builder() .eventBusName("default") .rule(ruleName) .targets(lambdaTarget) .build(); - eventBrClient.putTargets(targetsRequest); - System.out.println("The "+lambdaARN + " was successfully used as a target"); + eventBrClient.putTargets(targetsRequest); + System.out.println("The " + lambdaARN + " was successfully used as a target"); - } catch (EventBridgeException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } + } catch (EventBridgeException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); } - // snippet-end:[eventbridge.java2._create_schedule_rule_target.main] + } + // snippet-end:[eventbridge.java2._create_schedule_rule_target.main] } diff --git a/javav2/example_code/eventbridge/src/main/java/com/example/eventbridge/EventbridgeMVP.java b/javav2/example_code/eventbridge/src/main/java/com/example/eventbridge/EventbridgeMVP.java index d5f57e510d6..e4551339376 100644 --- a/javav2/example_code/eventbridge/src/main/java/com/example/eventbridge/EventbridgeMVP.java +++ b/javav2/example_code/eventbridge/src/main/java/com/example/eventbridge/EventbridgeMVP.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[EventbridgeMVP.java demonstrates how to perform various Amazon EventBridge tasks using the AWS SDK for Java v2.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon EventBridge] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.eventbridge; @@ -80,7 +74,8 @@ // snippet-start:[eventbridge.java2.mvp.main] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -90,13 +85,17 @@ * * This Java V2 example performs the following tasks with Amazon EventBridge: * - * 1. Creates an AWS Identity and Access Management (IAM) role to use with Amazon EventBridge. - * 2. Amazon Simple Storage Service (Amazon S3) bucket with EventBridge events enabled. + * 1. Creates an AWS Identity and Access Management (IAM) role to use with + * Amazon EventBridge. + * 2. Amazon Simple Storage Service (Amazon S3) bucket with EventBridge events + * enabled. * 3. Creates a rule that triggers when an object is uploaded to Amazon S3. * 4. Lists rules on the event bus. - * 5. Creates a new Amazon Simple Notification Service (Amazon SNS) topic and lets the user subscribe to it. + * 5. Creates a new Amazon Simple Notification Service (Amazon SNS) topic and + * lets the user subscribe to it. * 6. Adds a target to the rule that sends an email to the specified topic. - * 7. Creates an EventBridge event that sends an email when an Amazon S3 object is created. + * 7. Creates an EventBridge event that sends an email when an Amazon S3 object + * is created. * 8. Lists Targets. * 9. Lists the rules for the same target. * 10. Triggers the rule by uploading a file to the Amazon S3 bucket. @@ -112,18 +111,19 @@ */ public class EventbridgeMVP { public static final String DASHES = new String(new char[80]).replace("\0", "-"); + public static void main(String[] args) throws InterruptedException, IOException { final String usage = """ - Usage: - + Usage: + - Where: - roleName - The name of the role to create. - bucketName - The Amazon Simple Storage Service (Amazon S3) bucket name to create. - topicName - The name of the Amazon Simple Notification Service (Amazon SNS) topic to create. - eventRuleName - The Amazon EventBridge rule name to create. - """; + Where: + roleName - The name of the role to create. + bucketName - The Amazon Simple Storage Service (Amazon S3) bucket name to create. + topicName - The name of the Amazon Simple Notification Service (Amazon SNS) topic to create. + eventRuleName - The Amazon EventBridge rule name to create. + """; if (args.length != 5) { System.out.println(usage); @@ -131,15 +131,15 @@ public static void main(String[] args) throws InterruptedException, IOException } String polJSON = "{" + - "\"Version\": \"2012-10-17\"," + - "\"Statement\": [{" + - "\"Effect\": \"Allow\"," + - "\"Principal\": {" + - "\"Service\": \"events.amazonaws.com\"" + - "}," + - "\"Action\": \"sts:AssumeRole\"" + - "}]" + - "}"; + "\"Version\": \"2012-10-17\"," + + "\"Statement\": [{" + + "\"Effect\": \"Allow\"," + + "\"Principal\": {" + + "\"Service\": \"events.amazonaws.com\"" + + "}," + + "\"Action\": \"sts:AssumeRole\"" + + "}]" + + "}"; Scanner sc = new Scanner(System.in); String roleName = args[0]; @@ -149,35 +149,36 @@ public static void main(String[] args) throws InterruptedException, IOException Region region = Region.US_EAST_1; EventBridgeClient eventBrClient = EventBridgeClient.builder() - .region(region) - .build(); + .region(region) + .build(); S3Client s3Client = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); Region regionGl = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(regionGl) - .build(); + .region(regionGl) + .build(); SnsClient snsClient = SnsClient.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.println(DASHES); System.out.println("Welcome to the Amazon EventBridge example scenario."); System.out.println(DASHES); System.out.println(DASHES); - System.out.println("1. Create an AWS Identity and Access Management (IAM) role to use with Amazon EventBridge."); + System.out + .println("1. Create an AWS Identity and Access Management (IAM) role to use with Amazon EventBridge."); String roleArn = createIAMRole(iam, roleName, polJSON); System.out.println(DASHES); System.out.println(DASHES); System.out.println("2. Create an S3 bucket with EventBridge events enabled."); if (checkBucket(s3Client, bucketName)) { - System.out.println("Bucket "+ bucketName +" already exists. Ending this scenario."); + System.out.println("Bucket " + bucketName + " already exists. Ending this scenario."); System.exit(1); } @@ -207,7 +208,8 @@ public static void main(String[] args) throws InterruptedException, IOException System.out.println("Enter your email to subscribe to the Amazon SNS topic:"); String email = sc.nextLine(); subEmail(snsClient, topicArn, email); - System.out.println("Use the link in the email you received to confirm your subscription. Then, press Enter to continue."); + System.out.println( + "Use the link in the email you received to confirm your subscription. Then, press Enter to continue."); sc.nextLine(); System.out.println(DASHES); @@ -263,9 +265,9 @@ public static void main(String[] args) throws InterruptedException, IOException System.out.println(DASHES); System.out.println(" 16. Update the rule to be a custom rule pattern."); updateToCustomRule(eventBrClient, eventRuleName); - System.out.println("Updated event rule "+eventRuleName +" to use a custom pattern."); + System.out.println("Updated event rule " + eventRuleName + " to use a custom pattern."); updateCustomRuleTargetWithTransform(eventBrClient, topicArn, eventRuleName); - System.out.println("Updated event target "+topicArn +"."); + System.out.println("Updated event target " + topicArn + "."); System.out.println(DASHES); System.out.println(DASHES); @@ -280,7 +282,7 @@ public static void main(String[] args) throws InterruptedException, IOException System.out.println("Do you want to clean up resources (y/n)"); String ans = sc.nextLine(); if (ans.compareTo("y") == 0) { - cleanupResources(eventBrClient, snsClient, s3Client, iam, topicArn, eventRuleName, bucketName, roleName ); + cleanupResources(eventBrClient, snsClient, s3Client, iam, topicArn, eventRuleName, bucketName, roleName); } else { System.out.println("The resources will not be cleaned up. "); } @@ -291,7 +293,8 @@ public static void main(String[] args) throws InterruptedException, IOException System.out.println(DASHES); } - public static void cleanupResources(EventBridgeClient eventBrClient, SnsClient snsClient, S3Client s3Client, IamClient iam, String topicArn, String eventRuleName, String bucketName, String roleName) { + public static void cleanupResources(EventBridgeClient eventBrClient, SnsClient snsClient, S3Client s3Client, + IamClient iam, String topicArn, String eventRuleName, String bucketName, String roleName) { System.out.println("Removing all targets from the event rule."); deleteTargetsFromRule(eventBrClient, eventRuleName); deleteRuleByName(eventBrClient, eventRuleName); @@ -303,27 +306,27 @@ public static void cleanupResources(EventBridgeClient eventBrClient, SnsClient s public static void deleteRole(IamClient iam, String roleName) { String policyArn = "arn:aws:iam::aws:policy/AmazonEventBridgeFullAccess"; DetachRolePolicyRequest policyRequest = DetachRolePolicyRequest.builder() - .policyArn(policyArn) - .roleName(roleName) - .build(); + .policyArn(policyArn) + .roleName(roleName) + .build(); iam.detachRolePolicy(policyRequest); System.out.println("Successfully detached policy " + policyArn + " from role " + roleName); // Delete the role. DeleteRoleRequest roleRequest = DeleteRoleRequest.builder() - .roleName(roleName) - .build(); + .roleName(roleName) + .build(); iam.deleteRole(roleRequest); System.out.println("*** Successfully deleted " + roleName); } - public static void deleteS3Bucket( S3Client s3Client, String bucketName) { + public static void deleteS3Bucket(S3Client s3Client, String bucketName) { // Remove all the objects from the S3 bucket. ListObjectsRequest listObjects = ListObjectsRequest.builder() - .bucket(bucketName) - .build(); + .bucket(bucketName) + .build(); ListObjectsResponse res = s3Client.listObjects(listObjects); List objects = res.contents(); @@ -331,33 +334,33 @@ public static void deleteS3Bucket( S3Client s3Client, String bucketName) { for (S3Object myValue : objects) { toDelete.add(ObjectIdentifier.builder() - .key(myValue.key()) - .build()); + .key(myValue.key()) + .build()); } DeleteObjectsRequest dor = DeleteObjectsRequest.builder() - .bucket(bucketName) - .delete(Delete.builder() - .objects(toDelete).build()) - .build(); + .bucket(bucketName) + .delete(Delete.builder() + .objects(toDelete).build()) + .build(); s3Client.deleteObjects(dor); // Delete the S3 bucket. DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder() - .bucket(bucketName) - .build(); + .bucket(bucketName) + .build(); s3Client.deleteBucket(deleteBucketRequest); System.out.println("You have deleted the bucket and the objects"); } // Delete the SNS topic. - public static void deleteSNSTopic(SnsClient snsClient, String topicArn ) { + public static void deleteSNSTopic(SnsClient snsClient, String topicArn) { try { DeleteTopicRequest request = DeleteTopicRequest.builder() - .topicArn(topicArn) - .build(); + .topicArn(topicArn) + .build(); DeleteTopicResponse result = snsClient.deleteTopic(request); System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode()); @@ -371,8 +374,8 @@ public static void deleteSNSTopic(SnsClient snsClient, String topicArn ) { // snippet-start:[eventbridge.java2._delete_rule.main] public static void deleteRuleByName(EventBridgeClient eventBrClient, String ruleName) { DeleteRuleRequest ruleRequest = DeleteRuleRequest.builder() - .name(ruleName) - .build(); + .name(ruleName) + .build(); eventBrClient.deleteRule(ruleRequest); System.out.println("Successfully deleted the rule"); @@ -383,18 +386,18 @@ public static void deleteRuleByName(EventBridgeClient eventBrClient, String rule public static void deleteTargetsFromRule(EventBridgeClient eventBrClient, String eventRuleName) { // First, get all targets that will be deleted. ListTargetsByRuleRequest request = ListTargetsByRuleRequest.builder() - .rule(eventRuleName) - .build(); + .rule(eventRuleName) + .build(); ListTargetsByRuleResponse response = eventBrClient.listTargetsByRule(request); List allTargets = response.targets(); // Get all targets and delete them. - for (Target myTarget:allTargets) { + for (Target myTarget : allTargets) { RemoveTargetsRequest removeTargetsRequest = RemoveTargetsRequest.builder() - .rule(eventRuleName) - .ids(myTarget.id()) - .build(); + .rule(eventRuleName) + .ids(myTarget.id()) + .build(); eventBrClient.removeTargets(removeTargetsRequest); System.out.println("Successfully removed the target"); @@ -405,44 +408,45 @@ public static void deleteTargetsFromRule(EventBridgeClient eventBrClient, String // snippet-start:[eventbridge.java2._put_event.main] public static void triggerCustomRule(EventBridgeClient eventBrClient, String email) { String json = "{" + - "\"UserEmail\": \""+email+"\"," + - "\"Message\": \"This event was generated by example code.\"," + - "\"UtcTime\": \"Now.\"" + - "}"; + "\"UserEmail\": \"" + email + "\"," + + "\"Message\": \"This event was generated by example code.\"," + + "\"UtcTime\": \"Now.\"" + + "}"; PutEventsRequestEntry entry = PutEventsRequestEntry.builder() - .source("ExampleSource") - .detail(json) - .detailType("ExampleType") - .build(); + .source("ExampleSource") + .detail(json) + .detailType("ExampleType") + .build(); PutEventsRequest eventsRequest = PutEventsRequest.builder() - .entries(entry) - .build(); + .entries(entry) + .build(); eventBrClient.putEvents(eventsRequest); } // snippet-end:[eventbridge.java2._put_event.main] // snippet-start:[eventbridge.java2._put_target.custom.transform.main] - public static void updateCustomRuleTargetWithTransform(EventBridgeClient eventBrClient, String topicArn, String ruleName){ + public static void updateCustomRuleTargetWithTransform(EventBridgeClient eventBrClient, String topicArn, + String ruleName) { String targetId = java.util.UUID.randomUUID().toString(); InputTransformer inputTransformer = InputTransformer.builder() - .inputTemplate("\"Notification: sample event was received.\"") - .build(); + .inputTemplate("\"Notification: sample event was received.\"") + .build(); Target target = Target.builder() - .id(targetId) - .arn(topicArn) - .inputTransformer(inputTransformer) - .build(); + .id(targetId) + .arn(topicArn) + .inputTransformer(inputTransformer) + .build(); try { PutTargetsRequest targetsRequest = PutTargetsRequest.builder() - .rule(ruleName) - .targets(target) - .eventBusName(null) - .build(); + .rule(ruleName) + .targets(target) + .eventBusName(null) + .build(); eventBrClient.putTargets(targetsRequest); } catch (EventBridgeException e) { @@ -455,44 +459,44 @@ public static void updateCustomRuleTargetWithTransform(EventBridgeClient eventBr // snippet-start:[eventbridge.java2.puttargetstransform.main] public static void updateToCustomRule(EventBridgeClient eventBrClient, String ruleName) { String customEventsPattern = "{" + - "\"source\": [\"ExampleSource\"]," + - "\"detail-type\": [\"ExampleType\"]" + - "}"; + "\"source\": [\"ExampleSource\"]," + + "\"detail-type\": [\"ExampleType\"]" + + "}"; PutRuleRequest request = PutRuleRequest.builder() - .name(ruleName) - .description("Custom test rule") - .eventPattern(customEventsPattern) - .build(); + .name(ruleName) + .description("Custom test rule") + .eventPattern(customEventsPattern) + .build(); eventBrClient.putRule(request); } // snippet-end:[eventbridge.java2.puttargetstransform.main] // Update an Amazon S3 object created rule with a transform on the target. - public static void updateSnsEventRule(EventBridgeClient eventBrClient, String topicArn, String ruleName){ + public static void updateSnsEventRule(EventBridgeClient eventBrClient, String topicArn, String ruleName) { String targetId = java.util.UUID.randomUUID().toString(); Map myMap = new HashMap<>(); myMap.put("bucket", "$.detail.bucket.name"); myMap.put("time", "$.time"); InputTransformer inputTransformer = InputTransformer.builder() - .inputTemplate("\"Notification: an object was uploaded to bucket at
    tables = response.tableList(); @@ -342,22 +339,23 @@ public static String getGlueTables(GlueClient glueClient, String dbName){ return myTableName; } - public static void startJob(GlueClient glueClient, String jobName, String inputDatabase, String inputTable, String outBucket) { + public static void startJob(GlueClient glueClient, String jobName, String inputDatabase, String inputTable, + String outBucket) { try { - Map myMap = new HashMap<>(); + Map myMap = new HashMap<>(); myMap.put("--input_database", inputDatabase); myMap.put("--input_table", inputTable); myMap.put("--output_bucket_url", outBucket); StartJobRunRequest runRequest = StartJobRunRequest.builder() - .workerType(WorkerType.G_1_X) - .numberOfWorkers(10) - .arguments(myMap) - .jobName(jobName) - .build(); + .workerType(WorkerType.G_1_X) + .numberOfWorkers(10) + .arguments(myMap) + .jobName(jobName) + .build(); StartJobRunResponse response = glueClient.startJobRun(runRequest); - System.out.println("The request Id of the job is "+ response.responseMetadata().requestId()); + System.out.println("The request Id of the job is " + response.responseMetadata().requestId()); } catch (GlueException e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -368,23 +366,23 @@ public static void startJob(GlueClient glueClient, String jobName, String inputD public static void createJob(GlueClient glueClient, String jobName, String iam, String scriptLocation) { try { JobCommand command = JobCommand.builder() - .pythonVersion("3") - .name("glueetl") - .scriptLocation(scriptLocation) - .build(); + .pythonVersion("3") + .name("glueetl") + .scriptLocation(scriptLocation) + .build(); CreateJobRequest jobRequest = CreateJobRequest.builder() - .description("A Job created by using the AWS SDK for Java V2") - .glueVersion("2.0") - .workerType(WorkerType.G_1_X) - .numberOfWorkers(10) - .name(jobName) - .role(iam) - .command(command) - .build(); + .description("A Job created by using the AWS SDK for Java V2") + .glueVersion("2.0") + .workerType(WorkerType.G_1_X) + .numberOfWorkers(10) + .name(jobName) + .role(iam) + .command(command) + .build(); glueClient.createJob(jobRequest); - System.out.println(jobName +" was successfully created."); + System.out.println(jobName + " was successfully created."); } catch (GlueException e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -395,14 +393,14 @@ public static void createJob(GlueClient glueClient, String jobName, String iam, public static void getAllJobs(GlueClient glueClient) { try { GetJobsRequest jobsRequest = GetJobsRequest.builder() - .maxResults(10) - .build(); + .maxResults(10) + .build(); GetJobsResponse jobsResponse = glueClient.getJobs(jobsRequest); List jobs = jobsResponse.jobs(); - for (Job job: jobs) { - System.out.println("Job name is : "+job.name()); - System.out.println("The job worker type is : "+job.workerType().name()); + for (Job job : jobs) { + System.out.println("Job name is : " + job.name()); + System.out.println("The job worker type is : " + job.workerType().name()); } } catch (GlueException e) { @@ -414,11 +412,11 @@ public static void getAllJobs(GlueClient glueClient) { public static void getJobRuns(GlueClient glueClient, String jobName) { try { GetJobRunsRequest runsRequest = GetJobRunsRequest.builder() - .jobName(jobName) - .maxResults(20) - .build(); + .jobName(jobName) + .maxResults(20) + .build(); - boolean jobDone = false ; + boolean jobDone = false; while (!jobDone) { GetJobRunsResponse response = glueClient.getJobRuns(runsRequest); List jobRuns = response.jobRuns(); @@ -458,11 +456,11 @@ public static void getJobRuns(GlueClient glueClient, String jobName) { public static void deleteJob(GlueClient glueClient, String jobName) { try { DeleteJobRequest jobRequest = DeleteJobRequest.builder() - .jobName(jobName) - .build(); + .jobName(jobName) + .build(); glueClient.deleteJob(jobRequest); - System.out.println(jobName +" was successfully deleted"); + System.out.println(jobName + " was successfully deleted"); } catch (GlueException e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -473,11 +471,11 @@ public static void deleteJob(GlueClient glueClient, String jobName) { public static void deleteDatabase(GlueClient glueClient, String databaseName) { try { DeleteDatabaseRequest request = DeleteDatabaseRequest.builder() - .name(databaseName) - .build(); + .name(databaseName) + .build(); glueClient.deleteDatabase(request); - System.out.println(databaseName +" was successfully deleted"); + System.out.println(databaseName + " was successfully deleted"); } catch (GlueException e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -488,11 +486,11 @@ public static void deleteDatabase(GlueClient glueClient, String databaseName) { public static void deleteSpecificCrawler(GlueClient glueClient, String crawlerName) { try { DeleteCrawlerRequest deleteCrawlerRequest = DeleteCrawlerRequest.builder() - .name(crawlerName) - .build(); + .name(crawlerName) + .build(); glueClient.deleteCrawler(deleteCrawlerRequest); - System.out.println(crawlerName +" was deleted"); + System.out.println(crawlerName + " was deleted"); } catch (GlueException e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -500,4 +498,4 @@ public static void deleteSpecificCrawler(GlueClient glueClient, String crawlerNa } } } -//snippet-end:[glue.java2.scenario.main] \ No newline at end of file +// snippet-end:[glue.java2.scenario.main] \ No newline at end of file diff --git a/javav2/example_code/glue/src/main/java/com/example/glue/HelloGlue.java b/javav2/example_code/glue/src/main/java/com/example/glue/HelloGlue.java index b00a88ce0bd..483769db7ca 100644 --- a/javav2/example_code/glue/src/main/java/com/example/glue/HelloGlue.java +++ b/javav2/example_code/glue/src/main/java/com/example/glue/HelloGlue.java @@ -1,12 +1,7 @@ -//snippet-sourcedescription:[GetDatabase.java demonstrates how to get a database.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS Glue] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -//snippet-start:[glue.java2.hello.main] +// snippet-start:[glue.java2.hello.main] package com.example.glue; import software.amazon.awssdk.regions.Region; @@ -16,17 +11,18 @@ import java.util.List; public class HelloGlue { - public static void main(String[] args){ + public static void main(String[] args) { GlueClient glueClient = GlueClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); listJobs(glueClient); } + public static void listJobs(GlueClient glueClient) { ListJobsRequest request = ListJobsRequest.builder() .maxResults(10) - .build(); + .build(); ListJobsResponse response = glueClient.listJobs(request); List jobList = response.jobNames(); jobList.forEach(job -> { @@ -34,4 +30,4 @@ public static void listJobs(GlueClient glueClient) { }); } } -//snippet-end:[glue.java2.hello.main] \ No newline at end of file +// snippet-end:[glue.java2.hello.main] \ No newline at end of file diff --git a/javav2/example_code/glue/src/main/java/com/example/glue/ListWorkflows.java b/javav2/example_code/glue/src/main/java/com/example/glue/ListWorkflows.java index 28200a51002..9ca8f9c2370 100644 --- a/javav2/example_code/glue/src/main/java/com/example/glue/ListWorkflows.java +++ b/javav2/example_code/glue/src/main/java/com/example/glue/ListWorkflows.java @@ -1,25 +1,21 @@ -//snippet-sourcedescription:[ListWorkflows.java demonstrates how to list workflows.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS Glue] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.glue; -//snippet-start:[glue.java2.list_wfs.main] -//snippet-start:[glue.java2.list_wfs.import] +// snippet-start:[glue.java2.list_wfs.main] +// snippet-start:[glue.java2.list_wfs.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.glue.GlueClient; import software.amazon.awssdk.services.glue.model.GlueException; import software.amazon.awssdk.services.glue.model.ListWorkflowsRequest; import software.amazon.awssdk.services.glue.model.ListWorkflowsResponse; import java.util.List; -//snippet-end:[glue.java2.list_wfs.import] +// snippet-end:[glue.java2.list_wfs.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,8 +25,8 @@ public class ListWorkflows { public static void main(String[] args) { Region region = Region.US_EAST_1; GlueClient glueClient = GlueClient.builder() - .region(region) - .build(); + .region(region) + .build(); listAllWorkflows(glueClient); glueClient.close(); @@ -39,8 +35,8 @@ public static void main(String[] args) { public static void listAllWorkflows(GlueClient glueClient) { try { ListWorkflowsRequest workflowsRequest = ListWorkflowsRequest.builder() - .maxResults(10) - .build(); + .maxResults(10) + .build(); ListWorkflowsResponse workflowsResponse = glueClient.listWorkflows(workflowsRequest); List workflows = workflowsResponse.workflows(); @@ -54,4 +50,4 @@ public static void listAllWorkflows(GlueClient glueClient) { } } } -//snippet-end:[glue.java2.list_wfs.main] +// snippet-end:[glue.java2.list_wfs.main] diff --git a/javav2/example_code/glue/src/main/java/com/example/glue/SearchTables.java b/javav2/example_code/glue/src/main/java/com/example/glue/SearchTables.java index 1e03143d4cc..bf6e369a2ce 100644 --- a/javav2/example_code/glue/src/main/java/com/example/glue/SearchTables.java +++ b/javav2/example_code/glue/src/main/java/com/example/glue/SearchTables.java @@ -1,15 +1,10 @@ -//snippet-sourcedescription:[SearchTables.java demonstrates how to search a set of tables based on properties.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS Glue] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.glue; -//snippet-start:[glue.java2.search_table.main] -//snippet-start:[glue.java2.search_table.import] +// snippet-start:[glue.java2.search_table.main] +// snippet-start:[glue.java2.search_table.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.glue.GlueClient; import software.amazon.awssdk.services.glue.model.GlueException; @@ -17,7 +12,7 @@ import software.amazon.awssdk.services.glue.model.SearchTablesResponse; import software.amazon.awssdk.services.glue.model.Table; import java.util.List; -//snippet-end:[glue.java2.search_table.import] +// snippet-end:[glue.java2.search_table.import] /* * Before running this example, run a crawler to produce a table within a database. @@ -33,12 +28,12 @@ public class SearchTables { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - text - A string used for a text search.\s - """; + Where: + text - A string used for a text search.\s + """; if (args.length != 1) { System.out.println(usage); @@ -48,8 +43,8 @@ public static void main(String[] args) { String text = args[0]; Region region = Region.US_EAST_1; GlueClient glueClient = GlueClient.builder() - .region(region) - .build(); + .region(region) + .build(); searchGlueTable(glueClient, text); glueClient.close(); @@ -58,10 +53,10 @@ public static void main(String[] args) { public static void searchGlueTable(GlueClient glueClient, String text) { try { SearchTablesRequest tablesRequest = SearchTablesRequest.builder() - .searchText(text) - .resourceShareType("ALL") - .maxResults(10) - .build(); + .searchText(text) + .resourceShareType("ALL") + .maxResults(10) + .build(); SearchTablesResponse tablesResponse = glueClient.searchTables(tablesRequest); List
    tables = tablesResponse.tableList(); @@ -76,4 +71,4 @@ public static void searchGlueTable(GlueClient glueClient, String text) { } } } -//snippet-end:[glue.java2.search_table.main] +// snippet-end:[glue.java2.search_table.main] diff --git a/javav2/example_code/glue/src/main/java/com/example/glue/StartCrawler.java b/javav2/example_code/glue/src/main/java/com/example/glue/StartCrawler.java index b2f697dfa75..4a175272f19 100644 --- a/javav2/example_code/glue/src/main/java/com/example/glue/StartCrawler.java +++ b/javav2/example_code/glue/src/main/java/com/example/glue/StartCrawler.java @@ -1,23 +1,19 @@ -//snippet-sourcedescription:[StartCrawler.java demonstrates how to start an AWS Glue crawler.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS Glue] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.glue; -//snippet-start:[glue.java2.start_crawler.main] -//snippet-start:[glue.java2.start_crawler.import] +// snippet-start:[glue.java2.start_crawler.main] +// snippet-start:[glue.java2.start_crawler.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.glue.GlueClient; import software.amazon.awssdk.services.glue.model.GlueException; -import software.amazon.awssdk.services.glue.model.StartCrawlerRequest ; -//snippet-end:[glue.java2.start_crawler.import] +import software.amazon.awssdk.services.glue.model.StartCrawlerRequest; +// snippet-end:[glue.java2.start_crawler.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,12 +23,12 @@ public class StartCrawler { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - crawlerName - The name of the crawler.\s - """; + Where: + crawlerName - The name of the crawler.\s + """; if (args.length != 1) { System.out.println(usage); @@ -42,8 +38,8 @@ public static void main(String[] args) { String crawlerName = args[0]; Region region = Region.US_EAST_1; GlueClient glueClient = GlueClient.builder() - .region(region) - .build(); + .region(region) + .build(); startSpecificCrawler(glueClient, crawlerName); glueClient.close(); @@ -52,8 +48,8 @@ public static void main(String[] args) { public static void startSpecificCrawler(GlueClient glueClient, String crawlerName) { try { StartCrawlerRequest crawlerRequest = StartCrawlerRequest.builder() - .name(crawlerName) - .build(); + .name(crawlerName) + .build(); glueClient.startCrawler(crawlerRequest); @@ -63,5 +59,4 @@ public static void startSpecificCrawler(GlueClient glueClient, String crawlerNam } } } - //snippet-end:[glue.java2.start_crawler.main] - +// snippet-end:[glue.java2.start_crawler.main] diff --git a/javav2/example_code/glue/src/test/java/GlueTest.java b/javav2/example_code/glue/src/test/java/GlueTest.java index c5dbe986015..7aacd8f95bc 100644 --- a/javav2/example_code/glue/src/test/java/GlueTest.java +++ b/javav2/example_code/glue/src/test/java/GlueTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.glue.*; import com.google.gson.Gson; @@ -25,29 +23,29 @@ public class GlueTest { private static GlueClient glueClient; - private static String crawlerName=""; - private static String cron=""; - private static String s3Path=""; - private static String IAM=""; - private static String databaseName=""; - private static String tableName=""; - private static String text=""; - private static String existingDatabaseName=""; - private static String existingCrawlerName=""; - private static String jobNameSc=""; - private static String s3PathSc=""; - private static String dbNameSc=""; - private static String crawlerNameSc=""; - private static String scriptLocationSc=""; - private static String locationUri=""; - private static String bucketNameSc=""; + private static String crawlerName = ""; + private static String cron = ""; + private static String s3Path = ""; + private static String IAM = ""; + private static String databaseName = ""; + private static String tableName = ""; + private static String text = ""; + private static String existingDatabaseName = ""; + private static String existingCrawlerName = ""; + private static String jobNameSc = ""; + private static String s3PathSc = ""; + private static String dbNameSc = ""; + private static String crawlerNameSc = ""; + private static String scriptLocationSc = ""; + private static String locationUri = ""; + private static String bucketNameSc = ""; @BeforeAll public static void setUp() throws IOException, URISyntaxException { glueClient = GlueClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -59,48 +57,53 @@ public static void setUp() throws IOException, URISyntaxException { IAM = values.getIAM(); databaseName = values.getDatabaseName(); tableName = values.getTableName(); - text = values.getText(); + text = values.getText(); existingDatabaseName = values.getExistingDatabaseName(); existingCrawlerName = values.getExistingCrawlerName(); - jobNameSc = values.getJobNameSc()+ java.util.UUID.randomUUID();; - s3PathSc = values.getS3PathSc()+ java.util.UUID.randomUUID();; - dbNameSc = values.getDbNameSc()+ java.util.UUID.randomUUID(); - crawlerNameSc = values.getCrawlerNameSc()+ java.util.UUID.randomUUID(); + jobNameSc = values.getJobNameSc() + java.util.UUID.randomUUID(); + ; + s3PathSc = values.getS3PathSc() + java.util.UUID.randomUUID(); + ; + dbNameSc = values.getDbNameSc() + java.util.UUID.randomUUID(); + crawlerNameSc = values.getCrawlerNameSc() + java.util.UUID.randomUUID(); scriptLocationSc = values.getScriptLocationSc(); locationUri = values.getLocationUri(); bucketNameSc = values.getBucketNameSc(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - - try (InputStream input = GlueTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - prop.load(input); - crawlerName = prop.getProperty("crawlerName"); - s3Path = prop.getProperty("s3Path"); - cron = prop.getProperty("cron"); - IAM = prop.getProperty("IAM"); - databaseName = prop.getProperty("databaseName"); - tableName = prop.getProperty("tableName"); - text = prop.getProperty("text"); - existingDatabaseName = prop.getProperty("existingDatabaseName"); - existingCrawlerName = prop.getProperty("existingCrawlerName"); - jobNameSc = prop.getProperty("jobNameSc")+ java.util.UUID.randomUUID();; - s3PathSc = prop.getProperty("s3PathSc")+ java.util.UUID.randomUUID();; - dbNameSc = prop.getProperty("dbNameSc")+ java.util.UUID.randomUUID(); - crawlerNameSc = prop.getProperty("crawlerNameSc")+ java.util.UUID.randomUUID(); - scriptLocationSc = prop.getProperty("scriptLocationSc"); - locationUri = prop.getProperty("locationUri"); - bucketNameSc = prop.getProperty("bucketNameSc"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * + * try (InputStream input = + * GlueTest.class.getClassLoader().getResourceAsStream("config.properties")) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * prop.load(input); + * crawlerName = prop.getProperty("crawlerName"); + * s3Path = prop.getProperty("s3Path"); + * cron = prop.getProperty("cron"); + * IAM = prop.getProperty("IAM"); + * databaseName = prop.getProperty("databaseName"); + * tableName = prop.getProperty("tableName"); + * text = prop.getProperty("text"); + * existingDatabaseName = prop.getProperty("existingDatabaseName"); + * existingCrawlerName = prop.getProperty("existingCrawlerName"); + * jobNameSc = prop.getProperty("jobNameSc")+ java.util.UUID.randomUUID();; + * s3PathSc = prop.getProperty("s3PathSc")+ java.util.UUID.randomUUID();; + * dbNameSc = prop.getProperty("dbNameSc")+ java.util.UUID.randomUUID(); + * crawlerNameSc = prop.getProperty("crawlerNameSc")+ + * java.util.UUID.randomUUID(); + * scriptLocationSc = prop.getProperty("scriptLocationSc"); + * locationUri = prop.getProperty("locationUri"); + * bucketNameSc = prop.getProperty("bucketNameSc"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @@ -117,26 +120,27 @@ public void ScenarioTest() throws InterruptedException { TimeUnit.MINUTES.sleep(5);// Sleep for 5 minute to get tables ready String myTableName = GlueScenario.getGlueTables(glueClient, dbNameSc); GlueScenario.createJob(glueClient, jobNameSc, IAM, scriptLocationSc); - GlueScenario.startJob(glueClient, jobNameSc, dbNameSc, myTableName, bucketNameSc ); + GlueScenario.startJob(glueClient, jobNameSc, dbNameSc, myTableName, bucketNameSc); GlueScenario.getAllJobs(glueClient); GlueScenario.getJobRuns(glueClient, jobNameSc); GlueScenario.deleteJob(glueClient, jobNameSc); - System.out.println("*** Wait 5 MIN for the "+crawlerNameSc +" to stop"); + System.out.println("*** Wait 5 MIN for the " + crawlerNameSc + " to stop"); TimeUnit.MINUTES.sleep(5); GlueScenario.deleteDatabase(glueClient, dbNameSc); GlueScenario.deleteSpecificCrawler(glueClient, crawlerNameSc); } + private static String getSecretValues() { // Get the Amazon RDS creds from Secrets Manager. SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/glue"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -173,7 +177,6 @@ class SecretValues { private String bucketNameSc; - public String getIAM() { return IAM; } @@ -240,4 +243,3 @@ public String getBucketNameSc() { } } - diff --git a/javav2/example_code/guardduty/src/main/java/com/example/guardduty/GetDetector.java b/javav2/example_code/guardduty/src/main/java/com/example/guardduty/GetDetector.java index 80efc3165ab..37d958e1619 100644 --- a/javav2/example_code/guardduty/src/main/java/com/example/guardduty/GetDetector.java +++ b/javav2/example_code/guardduty/src/main/java/com/example/guardduty/GetDetector.java @@ -1,26 +1,20 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[GetDetector.java demonstrates how to obtain a detector using its id value.] -//snippet-keyword:[AWS SDK for Java v2] -// snippet-keyword:[Amazon GuardDuty] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.guardduty; -//snippet-start:[guard.java2.get_detector.main] -//snippet-start:[guard.java2.get_detector.import] +// snippet-start:[guard.java2.get_detector.main] +// snippet-start:[guard.java2.get_detector.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.guardduty.GuardDutyClient; import software.amazon.awssdk.services.guardduty.model.GetDetectorRequest; import software.amazon.awssdk.services.guardduty.model.GetDetectorResponse; import software.amazon.awssdk.services.guardduty.model.GuardDutyException; -//snippet-end:[guard.java2.get_detector.import] +// snippet-end:[guard.java2.get_detector.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,10 +24,10 @@ public class GetDetector { public static void main(String[] args) { final String usage = """ - To run this example, supply the detector Id value.\s + To run this example, supply the detector Id value.\s - Ex: GetDetector - """; + Ex: GetDetector + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +37,8 @@ public static void main(String[] args) { String detectorId = args[0]; Region region = Region.US_EAST_1; GuardDutyClient guardDutyClient = GuardDutyClient.builder() - .region(region) - .build(); + .region(region) + .build(); getSpecificDetector(guardDutyClient, detectorId); guardDutyClient.close(); @@ -53,8 +47,8 @@ public static void main(String[] args) { public static void getSpecificDetector(GuardDutyClient guardDutyClient, String detectorId) { try { GetDetectorRequest detectorRequest = GetDetectorRequest.builder() - .detectorId(detectorId) - .build(); + .detectorId(detectorId) + .build(); GetDetectorResponse detectorResponse = guardDutyClient.getDetector(detectorRequest); System.out.println("The detector status is " + detectorResponse.status().toString()); @@ -65,4 +59,4 @@ public static void getSpecificDetector(GuardDutyClient guardDutyClient, String d } } } -//snippet-end:[guard.java2.get_detector.main] +// snippet-end:[guard.java2.get_detector.main] diff --git a/javav2/example_code/guardduty/src/main/java/com/example/guardduty/GetFindings.java b/javav2/example_code/guardduty/src/main/java/com/example/guardduty/GetFindings.java index c37a327670d..7c1f28e00ca 100644 --- a/javav2/example_code/guardduty/src/main/java/com/example/guardduty/GetFindings.java +++ b/javav2/example_code/guardduty/src/main/java/com/example/guardduty/GetFindings.java @@ -1,17 +1,10 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[GetFindings.java demonstrates how to List detector id values for existing Amazon GuardDuty detector resources.] -//snippet-keyword:[AWS SDK for Java v2] -// snippet-keyword:[Amazon GuardDuty] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.guardduty; -//snippet-start:[guard.java2.get_findings.main] -//snippet-start:[guard.java2.get_findings.import] +// snippet-start:[guard.java2.get_findings.main] +// snippet-start:[guard.java2.get_findings.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.guardduty.GuardDutyClient; import software.amazon.awssdk.services.guardduty.model.Finding; @@ -20,10 +13,11 @@ import software.amazon.awssdk.services.guardduty.model.GuardDutyException; import java.util.ArrayList; import java.util.List; -//snippet-end:[guard.java2.get_findings.import] +// snippet-end:[guard.java2.get_findings.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -34,10 +28,10 @@ public class GetFindings { public static void main(String[] args) { final String usage = """ - To run this example, supply the findingId value and the detectorId value. \s + To run this example, supply the findingId value and the detectorId value. \s - Ex: GetFindings - """; + Ex: GetFindings + """; if (args.length < 2) { System.out.println(usage); @@ -49,8 +43,8 @@ public static void main(String[] args) { Region region = Region.US_EAST_1; GuardDutyClient guardDutyClient = GuardDutyClient.builder() - .region(region) - .build(); + .region(region) + .build(); getSpecificFinding(guardDutyClient, findingId, detectorId); guardDutyClient.close(); @@ -62,9 +56,9 @@ public static void getSpecificFinding(GuardDutyClient guardDutyClient, String fi myIds.add(findingId); GetFindingsRequest findingsRequest = GetFindingsRequest.builder() - .findingIds(myIds) - .detectorId(detectorId) - .build(); + .findingIds(myIds) + .detectorId(detectorId) + .build(); GetFindingsResponse findingsResponse = guardDutyClient.getFindings(findingsRequest); List findings = findingsResponse.findings(); @@ -80,4 +74,4 @@ public static void getSpecificFinding(GuardDutyClient guardDutyClient, String fi } } } -//snippet-end:[guard.java2.get_findings.main] +// snippet-end:[guard.java2.get_findings.main] diff --git a/javav2/example_code/guardduty/src/main/java/com/example/guardduty/ListDetectors.java b/javav2/example_code/guardduty/src/main/java/com/example/guardduty/ListDetectors.java index 1775cee81eb..3f3907e505a 100644 --- a/javav2/example_code/guardduty/src/main/java/com/example/guardduty/ListDetectors.java +++ b/javav2/example_code/guardduty/src/main/java/com/example/guardduty/ListDetectors.java @@ -1,24 +1,20 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[ListDetectors.java demonstrates how to List detector id valuess of all the existing Amazon GuardDuty detector resources.] -//snippet-keyword:[AWS SDK for Java v2] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.guardduty; -//snippet-start:[guard.java2.list_detectors.main] -//snippet-start:[guard.java2.list_detectors.import] +// snippet-start:[guard.java2.list_detectors.main] +// snippet-start:[guard.java2.list_detectors.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.guardduty.GuardDutyClient; import software.amazon.awssdk.services.guardduty.model.GuardDutyException; import software.amazon.awssdk.services.guardduty.model.ListDetectorsResponse; import java.util.List; -//snippet-end:[guard.java2.list_detectors.import] +// snippet-end:[guard.java2.list_detectors.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,8 +25,8 @@ public class ListDetectors { public static void main(String[] args) { Region region = Region.US_EAST_1; GuardDutyClient guardDutyClient = GuardDutyClient.builder() - .region(region) - .build(); + .region(region) + .build(); listAllDetectors(guardDutyClient); guardDutyClient.close(); @@ -50,4 +46,4 @@ public static void listAllDetectors(GuardDutyClient guardDutyClient) { } } } -//snippet-end:[guard.java2.list_detectors.main] +// snippet-end:[guard.java2.list_detectors.main] diff --git a/javav2/example_code/guardduty/src/test/java/GuarddutyTest.java b/javav2/example_code/guardduty/src/test/java/GuarddutyTest.java index 59a7d2bdf2d..145fab052d3 100644 --- a/javav2/example_code/guardduty/src/test/java/GuarddutyTest.java +++ b/javav2/example_code/guardduty/src/test/java/GuarddutyTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.guardduty.GetDetector; import com.example.guardduty.GetFindings; @@ -24,17 +22,17 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class GuarddutyTest { - private static GuardDutyClient guardDutyClient ; + private static GuardDutyClient guardDutyClient; private static String detectorId = ""; private static String findingId = ""; @BeforeAll - public static void setUp(){ + public static void setUp() { Region region = Region.US_EAST_1; guardDutyClient = GuardDutyClient.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -43,31 +41,34 @@ public static void setUp(){ detectorId = values.getDetectorId(); findingId = values.getFindingId(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - - try (InputStream input = GuarddutyTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - // Populate the data members required for all tests. - prop.load(input); - detectorId = prop.getProperty("detectorId"); - findingId = prop.getProperty("findingId"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * + * try (InputStream input = + * GuarddutyTest.class.getClassLoader().getResourceAsStream("config.properties") + * ) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * // Populate the data members required for all tests. + * prop.load(input); + * detectorId = prop.getProperty("detectorId"); + * findingId = prop.getProperty("findingId"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @Tag("IntegrationTest") @Order(1) public void GetDetector() { - assertDoesNotThrow(() ->GetDetector.getSpecificDetector(guardDutyClient, detectorId)); + assertDoesNotThrow(() -> GetDetector.getSpecificDetector(guardDutyClient, detectorId)); System.out.println("Test 1 passed"); } @@ -75,7 +76,7 @@ public void GetDetector() { @Tag("IntegrationTest") @Order(2) public void GetFindings() { - assertDoesNotThrow(() ->GetFindings.getSpecificFinding(guardDutyClient, findingId, detectorId)); + assertDoesNotThrow(() -> GetFindings.getSpecificFinding(guardDutyClient, findingId, detectorId)); System.out.println("Test 2 passed"); } @@ -83,21 +84,21 @@ public void GetFindings() { @Tag("IntegrationTest") @Order(3) public void ListDetectors() { - assertDoesNotThrow(() ->ListDetectors.listAllDetectors(guardDutyClient)); + assertDoesNotThrow(() -> ListDetectors.listAllDetectors(guardDutyClient)); System.out.println("Test 3 passed"); } private static String getSecretValues() { // Get the Amazon RDS creds from Secrets Manager. SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/guarduty"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -108,6 +109,7 @@ private static String getSecretValues() { class SecretValues { private String detectorId; private String findingId; + public String getDetectorId() { return detectorId; } diff --git a/javav2/example_code/iam/run_example.sh b/javav2/example_code/iam/run_example.sh index 70153e75524..68589ca0984 100755 --- a/javav2/example_code/iam/run_example.sh +++ b/javav2/example_code/iam/run_example.sh @@ -1,13 +1,15 @@ -#!/bin/bash -if [[ -z $* ]] ; then - echo 'Supply the name of one of the example classes as an argument.' - echo 'If there are arguments to the class, put them in quotes after the class name.' - exit 1 -fi -export CLASSPATH=target/sdk-iam-examples-1.0.jar -export className=$1 -echo "## Running $className..." -shift -echo "## arguments $@..." -mvn exec:java -Dexec.mainClass="com.example.iam.$className" -Dexec.args="$@" - +#!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +if [[ -z $* ]] ; then + echo 'Supply the name of one of the example classes as an argument.' + echo 'If there are arguments to the class, put them in quotes after the class name.' + exit 1 +fi +export CLASSPATH=target/sdk-iam-examples-1.0.jar +export className=$1 +echo "## Running $className..." +shift +echo "## arguments $@..." +mvn exec:java -Dexec.mainClass="com.example.iam.$className" -Dexec.args="$@" + diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/AccessKeyLastUsed.java b/javav2/example_code/iam/src/main/java/com/example/iam/AccessKeyLastUsed.java index a33b99c1778..236843bbcbf 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/AccessKeyLastUsed.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/AccessKeyLastUsed.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[AccessKeyLastUsed.java demonstrates how to display the time that an access key was last used.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.iam; @@ -19,7 +13,8 @@ // snippet-end:[iam.java2.access_key_last_used.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,12 +24,12 @@ public class AccessKeyLastUsed { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - accessId - An access key id that you can obtain from the AWS Management Console.\s - """; + Where: + accessId - An access key id that you can obtain from the AWS Management Console.\s + """; if (args.length != 1) { System.out.println(usage); @@ -44,8 +39,8 @@ public static void main(String[] args) { String accessId = args[0]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); getAccessKeyLastUsed(iam, accessId); iam.close(); @@ -54,12 +49,12 @@ public static void main(String[] args) { public static void getAccessKeyLastUsed(IamClient iam, String accessId) { try { GetAccessKeyLastUsedRequest request = GetAccessKeyLastUsedRequest.builder() - .accessKeyId(accessId) - .build(); + .accessKeyId(accessId) + .build(); GetAccessKeyLastUsedResponse response = iam.getAccessKeyLastUsed(request); System.out.println("Access key was last used at: " + - response.accessKeyLastUsed().lastUsedDate()); + response.accessKeyLastUsed().lastUsedDate()); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/AttachRolePolicy.java b/javav2/example_code/iam/src/main/java/com/example/iam/AttachRolePolicy.java index 426e10fef7d..9b53afb70f1 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/AttachRolePolicy.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/AttachRolePolicy.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[AttachRolePolicy.java demonstrates how to attach a policy to an existing AWS Identity and Access Management (IAM) role.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.iam; // snippet-start:[iam.java2.attach_role_policy.main] @@ -20,9 +15,9 @@ import java.util.List; // snippet-end:[iam.java2.attach_role_policy.import] - /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,13 +27,13 @@ public class AttachRolePolicy { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - roleName - A role name that you can obtain from the AWS Management Console.\s - policyArn - A policy ARN that you can obtain from the AWS Management Console.\s - """; + Where: + roleName - A role name that you can obtain from the AWS Management Console.\s + policyArn - A policy ARN that you can obtain from the AWS Management Console.\s + """; if (args.length != 2) { System.out.println(usage); @@ -51,8 +46,8 @@ public static void main(String[] args) { // snippet-start:[iam.java2.attach_role_policy.client] Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); // snippet-end:[iam.java2.attach_role_policy.client] attachIAMRolePolicy(iam, roleName, policyArn); @@ -62,8 +57,8 @@ public static void main(String[] args) { public static void attachIAMRolePolicy(IamClient iam, String roleName, String policyArn) { try { ListAttachedRolePoliciesRequest request = ListAttachedRolePoliciesRequest.builder() - .roleName(roleName) - .build(); + .roleName(roleName) + .build(); ListAttachedRolePoliciesResponse response = iam.listAttachedRolePolicies(request); List attachedPolicies = response.attachedPolicies(); @@ -80,15 +75,15 @@ public static void attachIAMRolePolicy(IamClient iam, String roleName, String po // snippet-start:[iam.java2.attach_role_policy.attach] AttachRolePolicyRequest attachRequest = AttachRolePolicyRequest.builder() - .roleName(roleName) - .policyArn(policyArn) - .build(); + .roleName(roleName) + .policyArn(policyArn) + .build(); iam.attachRolePolicy(attachRequest); // snippet-end:[iam.java2.attach_role_policy.attach] System.out.println("Successfully attached policy " + policyArn + - " to role " + roleName); + " to role " + roleName); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/CreateAccessKey.java b/javav2/example_code/iam/src/main/java/com/example/iam/CreateAccessKey.java index f8de62d047b..b0588b18782 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/CreateAccessKey.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/CreateAccessKey.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[CreateAccessKey.java demonstrates how to create an access key for an AWS Identity and Access Management (IAM) user.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.iam; // snippet-start:[iam.java2.create_access_key.main] @@ -18,7 +13,8 @@ // snippet-end:[iam.java2.create_access_key.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +24,12 @@ public class CreateAccessKey { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - user - An AWS IAM user that you can obtain from the AWS Management Console. - """; + Where: + user - An AWS IAM user that you can obtain from the AWS Management Console. + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +39,8 @@ public static void main(String[] args) { String user = args[0]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); String keyId = createIAMAccessKey(iam, user); System.out.println("The Key Id is " + keyId); @@ -54,8 +50,8 @@ public static void main(String[] args) { public static String createIAMAccessKey(IamClient iam, String user) { try { CreateAccessKeyRequest request = CreateAccessKeyRequest.builder() - .userName(user) - .build(); + .userName(user) + .build(); CreateAccessKeyResponse response = iam.createAccessKey(request); return response.accessKey().accessKeyId(); diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/CreateAccountAlias.java b/javav2/example_code/iam/src/main/java/com/example/iam/CreateAccountAlias.java index 82e0aef2baa..4d2264c1510 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/CreateAccountAlias.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/CreateAccountAlias.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[CreateAccountAlias.java demonstrates how to create an alias for an AWS account.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.iam; // snippet-start:[iam.java2.create_account_alias.main] @@ -17,7 +12,8 @@ // snippet-end:[iam.java2.create_account_alias.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -26,12 +22,12 @@ public class CreateAccountAlias { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - alias - The account alias to create (for example, myawsaccount).\s - """; + Where: + alias - The account alias to create (for example, myawsaccount).\s + """; if (args.length != 1) { System.out.println(usage); @@ -41,8 +37,8 @@ public static void main(String[] args) { String alias = args[0]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); createIAMAccountAlias(iam, alias); iam.close(); @@ -52,8 +48,8 @@ public static void main(String[] args) { public static void createIAMAccountAlias(IamClient iam, String alias) { try { CreateAccountAliasRequest request = CreateAccountAliasRequest.builder() - .accountAlias(alias) - .build(); + .accountAlias(alias) + .build(); iam.createAccountAlias(request); System.out.println("Successfully created account alias: " + alias); diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/CreatePolicy.java b/javav2/example_code/iam/src/main/java/com/example/iam/CreatePolicy.java index 9b6430dc673..540917d2195 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/CreatePolicy.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/CreatePolicy.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[CreatePolicy.java demonstrates how to create a policy by using waiters.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.iam; // snippet-start:[iam.java2.create_policy.main] @@ -22,7 +17,8 @@ // snippet-end:[iam.java2.create_policy.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,8 +27,7 @@ public class CreatePolicy { // snippet-start:[iam.java2.create_policy.policy_document] - public static final String PolicyDocument = - "{" + + public static final String PolicyDocument = "{" + " \"Version\": \"2012-10-17\"," + " \"Statement\": [" + " {" + @@ -53,12 +48,12 @@ public class CreatePolicy { public static void main(String[] args) { final String usage = """ - Usage: - CreatePolicy \s + Usage: + CreatePolicy \s - Where: - policyName - A unique policy name.\s - """; + Where: + policyName - A unique policy name.\s + """; if (args.length != 1) { System.out.println(usage); @@ -68,8 +63,8 @@ public static void main(String[] args) { String policyName = args[0]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); String result = createIAMPolicy(iam, policyName); System.out.println("Successfully created a policy with this ARN value: " + result); @@ -82,16 +77,16 @@ public static String createIAMPolicy(IamClient iam, String policyName) { IamWaiter iamWaiter = iam.waiter(); CreatePolicyRequest request = CreatePolicyRequest.builder() - .policyName(policyName) - .policyDocument(PolicyDocument) - .build(); + .policyName(policyName) + .policyDocument(PolicyDocument) + .build(); CreatePolicyResponse response = iam.createPolicy(request); // Wait until the policy is created. GetPolicyRequest polRequest = GetPolicyRequest.builder() - .policyArn(response.policy().arn()) - .build(); + .policyArn(response.policy().arn()) + .build(); WaiterResponse waitUntilPolicyExists = iamWaiter.waitUntilPolicyExists(polRequest); waitUntilPolicyExists.matched().response().ifPresent(System.out::println); diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/CreateRole.java b/javav2/example_code/iam/src/main/java/com/example/iam/CreateRole.java index a2ee8333a24..6c8569ba02e 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/CreateRole.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/CreateRole.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[CreateRole.java demonstrates how to create an AWS Identity and Access Management (IAM) role.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.iam; @@ -36,13 +30,13 @@ public class CreateRole { public static void main(String[] args) throws Exception { final String usage = """ - Usage: - \s + Usage: + \s - Where: - rolename - The name of the role to create.\s - fileLocation - The location of the JSON document that represents the trust policy.\s - """; + Where: + rolename - The name of the role to create.\s + fileLocation - The location of the JSON document that represents the trust policy.\s + """; if (args.length != 2) { System.out.println(usage); @@ -53,8 +47,8 @@ public static void main(String[] args) throws Exception { String fileLocation = args[1]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); String result = createIAMRole(iam, rolename, fileLocation); System.out.println("Successfully created user: " + result); @@ -65,10 +59,10 @@ public static String createIAMRole(IamClient iam, String rolename, String fileLo try { JSONObject jsonObject = (JSONObject) readJsonSimpleDemo(fileLocation); CreateRoleRequest request = CreateRoleRequest.builder() - .roleName(rolename) - .assumeRolePolicyDocument(jsonObject.toJSONString()) - .description("Created using the AWS SDK for Java") - .build(); + .roleName(rolename) + .assumeRolePolicyDocument(jsonObject.toJSONString()) + .description("Created using the AWS SDK for Java") + .build(); CreateRoleResponse response = iam.createRole(request); System.out.println("The ARN of the role is " + response.role().arn()); diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/CreateUser.java b/javav2/example_code/iam/src/main/java/com/example/iam/CreateUser.java index e343733f696..cbfcfdf7a30 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/CreateUser.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/CreateUser.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[CreateUser.java demonstrates how to create an AWS Identity and Access Management (IAM) user by using waiters.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.iam; // snippet-start:[iam.java2.create_user.main] @@ -22,7 +17,8 @@ // snippet-end:[iam.java2.create_user.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,12 +28,12 @@ public class CreateUser { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - username - The name of the user to create.\s - """; + Where: + username - The name of the user to create.\s + """; if (args.length != 1) { System.out.println(usage); @@ -47,28 +43,29 @@ public static void main(String[] args) { String username = args[0]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); String result = createIAMUser(iam, username); System.out.println("Successfully created user: " + result); iam.close(); } + public static String createIAMUser(IamClient iam, String username) { try { // Create an IamWaiter object. IamWaiter iamWaiter = iam.waiter(); CreateUserRequest request = CreateUserRequest.builder() - .userName(username) - .build(); + .userName(username) + .build(); CreateUserResponse response = iam.createUser(request); // Wait until the user is created. GetUserRequest userRequest = GetUserRequest.builder() - .userName(response.user().userName()) - .build(); + .userName(response.user().userName()) + .build(); WaiterResponse waitUntilUserExists = iamWaiter.waitUntilUserExists(userRequest); waitUntilUserExists.matched().response().ifPresent(System.out::println); diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/DeleteAccessKey.java b/javav2/example_code/iam/src/main/java/com/example/iam/DeleteAccessKey.java index c55e3451cc7..fb72c5c570e 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/DeleteAccessKey.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/DeleteAccessKey.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[DeleteAccessKey.java demonstrates how to delete an access key from an AWS Identity and Access Management (IAM) user.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.iam; // snippet-start:[iam.java2.delete_access_key.main] @@ -17,7 +12,8 @@ // snippet-end:[iam.java2.delete_access_key.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,13 +23,13 @@ public class DeleteAccessKey { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - username - The name of the user.\s - accessKey - The access key ID for the secret access key you want to delete.\s - """; + Where: + username - The name of the user.\s + accessKey - The access key ID for the secret access key you want to delete.\s + """; if (args.length != 2) { System.out.println(usage); @@ -44,8 +40,8 @@ public static void main(String[] args) { String accessKey = args[1]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteKey(iam, username, accessKey); iam.close(); } @@ -53,13 +49,13 @@ public static void main(String[] args) { public static void deleteKey(IamClient iam, String username, String accessKey) { try { DeleteAccessKeyRequest request = DeleteAccessKeyRequest.builder() - .accessKeyId(accessKey) - .userName(username) - .build(); + .accessKeyId(accessKey) + .userName(username) + .build(); iam.deleteAccessKey(request); System.out.println("Successfully deleted access key " + accessKey + - " from user " + username); + " from user " + username); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/DeleteAccountAlias.java b/javav2/example_code/iam/src/main/java/com/example/iam/DeleteAccountAlias.java index 6a0269f6b89..2d136ecc5a3 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/DeleteAccountAlias.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/DeleteAccountAlias.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[DeleteAccountAlias.java demonstrates how to delete an alias from an AWS account.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.iam; // snippet-start:[iam.java2.delete_account_alias.main] @@ -17,7 +12,8 @@ // snippet-end:[iam.java2.delete_account_alias.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,12 +23,12 @@ public class DeleteAccountAlias { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - alias - The account alias to delete.\s - """; + Where: + alias - The account alias to delete.\s + """; if (args.length != 1) { System.out.println(usage); @@ -42,8 +38,8 @@ public static void main(String[] args) { String alias = args[0]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteIAMAccountAlias(iam, alias); iam.close(); @@ -52,8 +48,8 @@ public static void main(String[] args) { public static void deleteIAMAccountAlias(IamClient iam, String alias) { try { DeleteAccountAliasRequest request = DeleteAccountAliasRequest.builder() - .accountAlias(alias) - .build(); + .accountAlias(alias) + .build(); iam.deleteAccountAlias(request); System.out.println("Successfully deleted account alias " + alias); diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/DeletePolicy.java b/javav2/example_code/iam/src/main/java/com/example/iam/DeletePolicy.java index a80f560256d..11e2bb3ae5e 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/DeletePolicy.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/DeletePolicy.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[DeletePolicy.java demonstrates how to delete a fixed policy with a provided policy name.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.iam; @@ -17,7 +12,8 @@ // snippet-end:[iam.java2.delete_policy.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,12 +23,12 @@ public class DeletePolicy { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - policyARN - A policy ARN value to delete.\s - """; + Where: + policyARN - A policy ARN value to delete.\s + """; if (args.length != 1) { System.out.println(usage); @@ -42,8 +38,8 @@ public static void main(String[] args) { String policyARN = args[0]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteIAMPolicy(iam, policyARN); iam.close(); @@ -52,8 +48,8 @@ public static void main(String[] args) { public static void deleteIAMPolicy(IamClient iam, String policyARN) { try { DeletePolicyRequest request = DeletePolicyRequest.builder() - .policyArn(policyARN) - .build(); + .policyArn(policyARN) + .build(); iam.deletePolicy(request); System.out.println("Successfully deleted the policy"); @@ -66,4 +62,3 @@ public static void deleteIAMPolicy(IamClient iam, String policyARN) { } } // snippet-end:[iam.java2.delete_policy.main] - diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/DeleteServerCertificate.java b/javav2/example_code/iam/src/main/java/com/example/iam/DeleteServerCertificate.java index d9cd96a760e..4f5750cbf30 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/DeleteServerCertificate.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/DeleteServerCertificate.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[DeleteServerCertificate.java demonstrates how to delete an AWS Identity and Access Management (IAM) server certificate.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.iam; // snippet-start:[iam.java2.delete_server_certificate.main] @@ -17,7 +12,8 @@ // snippet-end:[iam.java2.delete_server_certificate.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,12 +23,12 @@ public class DeleteServerCertificate { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - certName - A certificate name to delete.\s - """; + Where: + certName - A certificate name to delete.\s + """; if (args.length != 1) { System.out.println(usage); @@ -42,19 +38,19 @@ public static void main(String[] args) { String certName = args[0]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); - deleteCert(iam, certName) ; + deleteCert(iam, certName); System.out.println("Done"); iam.close(); } - public static void deleteCert(IamClient iam,String certName ) { + public static void deleteCert(IamClient iam, String certName) { try { DeleteServerCertificateRequest request = DeleteServerCertificateRequest.builder() - .serverCertificateName(certName) - .build(); + .serverCertificateName(certName) + .build(); iam.deleteServerCertificate(request); System.out.println("Successfully deleted server certificate " + certName); @@ -66,4 +62,3 @@ public static void deleteCert(IamClient iam,String certName ) { } } // snippet-end:[iam.java2.delete_server_certificate.main] - diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/DeleteUser.java b/javav2/example_code/iam/src/main/java/com/example/iam/DeleteUser.java index 17886ab16ce..41f9958dbad 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/DeleteUser.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/DeleteUser.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[DeleteUser.java demonstrates how to delete an AWS Identity and Access Management (IAM) user. This is only possible for users with no associated resources.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.iam; // snippet-start:[iam.java2.delete_user.main] @@ -17,7 +12,8 @@ // snippet-end:[iam.java2.delete_user.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,12 +23,12 @@ public class DeleteUser { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - userName - The name of the user to delete.\s - """; + Where: + userName - The name of the user to delete.\s + """; if (args.length != 1) { System.out.println(usage); @@ -42,8 +38,8 @@ public static void main(String[] args) { String userName = args[0]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteIAMUser(iam, userName); System.out.println("Done"); @@ -53,8 +49,8 @@ public static void main(String[] args) { public static void deleteIAMUser(IamClient iam, String userName) { try { DeleteUserRequest request = DeleteUserRequest.builder() - .userName(userName) - .build(); + .userName(userName) + .build(); iam.deleteUser(request); System.out.println("Successfully deleted IAM user " + userName); diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/DetachRolePolicy.java b/javav2/example_code/iam/src/main/java/com/example/iam/DetachRolePolicy.java index c3a190437e6..c6ce73f5128 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/DetachRolePolicy.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/DetachRolePolicy.java @@ -1,10 +1,6 @@ -//snippet-sourcedescription:[DetachRolePolicy.java demonstrates how to detach a policy from an AWS Identity and Access Management (IAM) role.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.iam; // snippet-start:[iam.java2.detach_role_policy.main] @@ -16,7 +12,8 @@ // snippet-end:[iam.java2.detach_role_policy.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -26,13 +23,13 @@ public class DetachRolePolicy { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - roleName - A role name that you can obtain from the AWS Management Console.\s - policyArn - A policy ARN that you can obtain from the AWS Management Console.\s - """; + Where: + roleName - A role name that you can obtain from the AWS Management Console.\s + policyArn - A policy ARN that you can obtain from the AWS Management Console.\s + """; if (args.length != 2) { System.out.println(usage); @@ -43,8 +40,8 @@ public static void main(String[] args) { String policyArn = args[1]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); detachPolicy(iam, roleName, policyArn); System.out.println("Done"); iam.close(); @@ -53,13 +50,13 @@ public static void main(String[] args) { public static void detachPolicy(IamClient iam, String roleName, String policyArn) { try { DetachRolePolicyRequest request = DetachRolePolicyRequest.builder() - .roleName(roleName) - .policyArn(policyArn) - .build(); + .roleName(roleName) + .policyArn(policyArn) + .build(); iam.detachRolePolicy(request); System.out.println("Successfully detached policy " + policyArn + - " from role " + roleName); + " from role " + roleName); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/GetPolicy.java b/javav2/example_code/iam/src/main/java/com/example/iam/GetPolicy.java index c11b412e4d7..decc275d26f 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/GetPolicy.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/GetPolicy.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[GetPolicy.java demonstrates how to get the details for an AWS Identity and Access Management (IAM) policy.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.iam; // snippet-start:[iam.java2.get_policy.main] @@ -18,7 +13,8 @@ // snippet-end:[iam.java2.get_policy.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +24,12 @@ public class GetPolicy { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - policyArn - A policy ARN that you can obtain from the AWS Management Console.\s - """; + Where: + policyArn - A policy ARN that you can obtain from the AWS Management Console.\s + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +39,8 @@ public static void main(String[] args) { String policyArn = args[0]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); getIAMPolicy(iam, policyArn); System.out.println("Done"); @@ -54,12 +50,12 @@ public static void main(String[] args) { public static void getIAMPolicy(IamClient iam, String policyArn) { try { GetPolicyRequest request = GetPolicyRequest.builder() - .policyArn(policyArn) - .build(); + .policyArn(policyArn) + .build(); GetPolicyResponse response = iam.getPolicy(request); System.out.format("Successfully retrieved policy %s", - response.policy().policyName()); + response.policy().policyName()); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/GetRole.java b/javav2/example_code/iam/src/main/java/com/example/iam/GetRole.java index 759574d8307..0715488852c 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/GetRole.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/GetRole.java @@ -1,10 +1,6 @@ -//snippet-sourcedescription:[GetRole.java demonstrates how to get information about the specified AWS Identity and Access Management (IAM) role.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.iam; import software.amazon.awssdk.services.iam.model.GetRoleRequest; @@ -14,7 +10,8 @@ import software.amazon.awssdk.services.iam.IamClient; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -25,12 +22,12 @@ public class GetRole { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - policyArn - A policy ARN that you can obtain from the AWS Management Console.\s - """; + Where: + policyArn - A policy ARN that you can obtain from the AWS Management Console.\s + """; if (args.length != 1) { System.out.println(usage); @@ -40,8 +37,8 @@ public static void main(String[] args) { String roleName = args[0]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); getRoleInformation(iam, roleName); System.out.println("Done"); @@ -51,11 +48,11 @@ public static void main(String[] args) { public static void getRoleInformation(IamClient iam, String roleName) { try { GetRoleRequest roleRequest = GetRoleRequest.builder() - .roleName(roleName) - .build(); + .roleName(roleName) + .build(); - GetRoleResponse response = iam.getRole(roleRequest) ; - System.out.println("The ARN of the role is " +response.role().arn()); + GetRoleResponse response = iam.getRole(roleRequest); + System.out.println("The ARN of the role is " + response.role().arn()); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/GetServerCertificate.java b/javav2/example_code/iam/src/main/java/com/example/iam/GetServerCertificate.java index 98b6dd1b2ef..09a3d8a3e1c 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/GetServerCertificate.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/GetServerCertificate.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[GetServerCertificate.java demonstrates how to get information about the specified AWS Identity and Access Management (IAM) role..] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.iam; // snippet-start:[iam.java2.get_server_certificate.main] @@ -18,7 +13,8 @@ // snippet-end:[iam.java2.get_server_certificate.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +24,12 @@ public class GetServerCertificate { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - certName - A certificate name.\s - """; + Where: + certName - A certificate name.\s + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +39,8 @@ public static void main(String[] args) { String certName = args[0]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); getCertificate(iam, certName); System.out.println("Done"); @@ -54,12 +50,12 @@ public static void main(String[] args) { public static void getCertificate(IamClient iam, String certName) { try { GetServerCertificateRequest request = GetServerCertificateRequest.builder() - .serverCertificateName(certName) - .build(); + .serverCertificateName(certName) + .build(); GetServerCertificateResponse response = iam.getServerCertificate(request); System.out.format("Successfully retrieved certificate with body %s", - response.serverCertificate().certificateBody()); + response.serverCertificate().certificateBody()); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/HelloIAM.java b/javav2/example_code/iam/src/main/java/com/example/iam/HelloIAM.java index 6166f8e1ab4..cf327b4454a 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/HelloIAM.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/HelloIAM.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[HelloIAM.java demonstrates how to list AWS Identity and Access Management (IAM) policies.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.iam; @@ -16,18 +11,19 @@ import java.util.List; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class HelloIAM { - public static void main(String[] args){ + public static void main(String[] args) { Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); listPolicies(iam); } diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/IAMScenario.java b/javav2/example_code/iam/src/main/java/com/example/iam/IAMScenario.java index 137821a9a28..11d575331c5 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/IAMScenario.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/IAMScenario.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[IAMScenario.java demonstrates how to perform various AWS Identity and Access Management (IAM) operations.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS IAM] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.iam; // snippet-start:[iam.java2.scenario.import] @@ -73,8 +68,7 @@ public class IAMScenario { public static final String DASHES = new String(new char[80]).replace("\0", "-"); - public static final String PolicyDocument = - "{" + + public static final String PolicyDocument = "{" + " \"Version\": \"2012-10-17\"," + " \"Statement\": [" + " {" + @@ -88,20 +82,21 @@ public class IAMScenario { "}"; public static String userArn; + public static void main(String[] args) throws Exception { final String usage = """ - Usage: - \s + Usage: + \s - Where: - username - The name of the IAM user to create.\s - policyName - The name of the policy to create.\s - roleName - The name of the role to create.\s - roleSessionName - The name of the session required for the assumeRole operation.\s - bucketName - The name of the Amazon S3 bucket from which objects are read.\s - """; + Where: + username - The name of the IAM user to create.\s + policyName - The name of the policy to create.\s + roleName - The name of the role to create.\s + roleSessionName - The name of the session required for the assumeRole operation.\s + bucketName - The name of the Amazon S3 bucket from which objects are read.\s + """; if (args.length != 5) { System.out.println(usage); @@ -116,8 +111,8 @@ public static void main(String[] args) throws Exception { Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.println(DASHES); System.out.println("Welcome to the AWS IAM example scenario."); @@ -134,15 +129,15 @@ public static void main(String[] args) throws Exception { String accessKey = myKey.accessKeyId(); String secretKey = myKey.secretAccessKey(); String assumeRolePolicyDocument = "{" + - "\"Version\": \"2012-10-17\"," + - "\"Statement\": [{" + - "\"Effect\": \"Allow\"," + - "\"Principal\": {" + - " \"AWS\": \"" + userArn + "\"" + - "}," + - "\"Action\": \"sts:AssumeRole\"" + - "}]" + - "}"; + "\"Version\": \"2012-10-17\"," + + "\"Statement\": [{" + + "\"Effect\": \"Allow\"," + + "\"Principal\": {" + + " \"AWS\": \"" + userArn + "\"" + + "}," + + "\"Action\": \"sts:AssumeRole\"" + + "}]" + + "}"; System.out.println(assumeRolePolicyDocument); System.out.println(userName + " was successfully created."); @@ -174,7 +169,7 @@ public static void main(String[] args) throws Exception { System.out.println(DASHES); System.out.println("6 Getting ready to delete the AWS resources"); - deleteKey(iam, userName, accessKey ); + deleteKey(iam, userName, accessKey); deleteRole(iam, roleName, polArn); deleteIAMUser(iam, userName); System.out.println(DASHES); @@ -187,8 +182,8 @@ public static void main(String[] args) throws Exception { public static AccessKey createIAMAccessKey(IamClient iam, String user) { try { CreateAccessKeyRequest request = CreateAccessKeyRequest.builder() - .userName(user) - .build(); + .userName(user) + .build(); CreateAccessKeyResponse response = iam.createAccessKey(request); return response.accessKey(); @@ -205,14 +200,14 @@ public static User createIAMUser(IamClient iam, String username) { // Create an IamWaiter object IamWaiter iamWaiter = iam.waiter(); CreateUserRequest request = CreateUserRequest.builder() - .userName(username) - .build(); + .userName(username) + .build(); // Wait until the user is created. CreateUserResponse response = iam.createUser(request); GetUserRequest userRequest = GetUserRequest.builder() - .userName(response.user().userName()) - .build(); + .userName(response.user().userName()) + .build(); WaiterResponse waitUntilUserExists = iamWaiter.waitUntilUserExists(userRequest); waitUntilUserExists.matched().response().ifPresent(System.out::println); @@ -229,10 +224,10 @@ public static String createIAMRole(IamClient iam, String rolename, String json) try { CreateRoleRequest request = CreateRoleRequest.builder() - .roleName(rolename) - .assumeRolePolicyDocument(json) - .description("Created using the AWS SDK for Java") - .build(); + .roleName(rolename) + .assumeRolePolicyDocument(json) + .description("Created using the AWS SDK for Java") + .build(); CreateRoleResponse response = iam.createRole(request); System.out.println("The ARN of the role is " + response.role().arn()); @@ -250,13 +245,13 @@ public static String createIAMPolicy(IamClient iam, String policyName) { // Create an IamWaiter object. IamWaiter iamWaiter = iam.waiter(); CreatePolicyRequest request = CreatePolicyRequest.builder() - .policyName(policyName) - .policyDocument(PolicyDocument).build(); + .policyName(policyName) + .policyDocument(PolicyDocument).build(); CreatePolicyResponse response = iam.createPolicy(request); GetPolicyRequest polRequest = GetPolicyRequest.builder() - .policyArn(response.policy().arn()) - .build(); + .policyArn(response.policy().arn()) + .build(); WaiterResponse waitUntilPolicyExists = iamWaiter.waitUntilPolicyExists(polRequest); waitUntilPolicyExists.matched().response().ifPresent(System.out::println); @@ -272,8 +267,8 @@ public static String createIAMPolicy(IamClient iam, String policyName) { public static void attachIAMRolePolicy(IamClient iam, String roleName, String policyArn) { try { ListAttachedRolePoliciesRequest request = ListAttachedRolePoliciesRequest.builder() - .roleName(roleName) - .build(); + .roleName(roleName) + .build(); ListAttachedRolePoliciesResponse response = iam.listAttachedRolePolicies(request); List attachedPolicies = response.attachedPolicies(); @@ -287,9 +282,9 @@ public static void attachIAMRolePolicy(IamClient iam, String roleName, String po } AttachRolePolicyRequest attachRequest = AttachRolePolicyRequest.builder() - .roleName(roleName) - .policyArn(policyArn) - .build(); + .roleName(roleName) + .policyArn(policyArn) + .build(); iam.attachRolePolicy(attachRequest); System.out.println("Successfully attached policy " + policyArn + " to role " + roleName); @@ -302,20 +297,21 @@ public static void attachIAMRolePolicy(IamClient iam, String roleName, String po // Invoke an Amazon S3 operation using the Assumed Role. // snippet-start:[iam.java2.scenario.assumeRole] - public static void assumeRole(String roleArn, String roleSessionName, String bucketName, String keyVal, String keySecret) { + public static void assumeRole(String roleArn, String roleSessionName, String bucketName, String keyVal, + String keySecret) { // Use the creds of the new IAM user that was created in this code example. AwsBasicCredentials credentials = AwsBasicCredentials.create(keyVal, keySecret); StsClient stsClient = StsClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(StaticCredentialsProvider.create(credentials)) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(StaticCredentialsProvider.create(credentials)) + .build(); try { AssumeRoleRequest roleRequest = AssumeRoleRequest.builder() - .roleArn(roleArn) - .roleSessionName(roleSessionName) - .build(); + .roleArn(roleArn) + .roleSessionName(roleSessionName) + .build(); AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest); Credentials myCreds = roleResponse.credentials(); @@ -323,18 +319,20 @@ public static void assumeRole(String roleArn, String roleSessionName, String buc String secKey = myCreds.secretAccessKey(); String secToken = myCreds.sessionToken(); - // List all objects in an Amazon S3 bucket using the temp creds retrieved by invoking assumeRole. + // List all objects in an Amazon S3 bucket using the temp creds retrieved by + // invoking assumeRole. Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .credentialsProvider(StaticCredentialsProvider.create(AwsSessionCredentials.create(key, secKey, secToken))) - .region(region) - .build(); + .credentialsProvider( + StaticCredentialsProvider.create(AwsSessionCredentials.create(key, secKey, secToken))) + .region(region) + .build(); System.out.println("Created a S3Client using temp credentials."); System.out.println("Listing objects in " + bucketName); ListObjectsRequest listObjects = ListObjectsRequest.builder() - .bucket(bucketName) - .build(); + .bucket(bucketName) + .build(); ListObjectsResponse res = s3.listObjects(listObjects); List objects = res.contents(); @@ -348,30 +346,31 @@ public static void assumeRole(String roleArn, String roleSessionName, String buc System.exit(1); } } + // snippet-end:[iam.java2.scenario.assumeRole] public static void deleteRole(IamClient iam, String roleName, String polArn) { try { // First the policy needs to be detached. DetachRolePolicyRequest rolePolicyRequest = DetachRolePolicyRequest.builder() - .policyArn(polArn) - .roleName(roleName) - .build(); + .policyArn(polArn) + .roleName(roleName) + .build(); iam.detachRolePolicy(rolePolicyRequest); // Delete the policy. DeletePolicyRequest request = DeletePolicyRequest.builder() - .policyArn(polArn) - .build(); + .policyArn(polArn) + .build(); iam.deletePolicy(request); System.out.println("*** Successfully deleted " + polArn); // Delete the role. DeleteRoleRequest roleRequest = DeleteRoleRequest.builder() - .roleName(roleName) - .build(); + .roleName(roleName) + .build(); iam.deleteRole(roleRequest); System.out.println("*** Successfully deleted " + roleName); @@ -382,16 +381,16 @@ public static void deleteRole(IamClient iam, String roleName, String polArn) { } } - public static void deleteKey(IamClient iam ,String username, String accessKey ) { + public static void deleteKey(IamClient iam, String username, String accessKey) { try { DeleteAccessKeyRequest request = DeleteAccessKeyRequest.builder() - .accessKeyId(accessKey) - .userName(username) - .build(); + .accessKeyId(accessKey) + .userName(username) + .build(); iam.deleteAccessKey(request); System.out.println("Successfully deleted access key " + accessKey + - " from user " + username); + " from user " + username); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -402,8 +401,8 @@ public static void deleteKey(IamClient iam ,String username, String accessKey ) public static void deleteIAMUser(IamClient iam, String userName) { try { DeleteUserRequest request = DeleteUserRequest.builder() - .userName(userName) - .build(); + .userName(userName) + .build(); iam.deleteUser(request); System.out.println("*** Successfully deleted " + userName); diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/IamPolicyBuilderExamples.java b/javav2/example_code/iam/src/main/java/com/example/iam/IamPolicyBuilderExamples.java index 9551ef2831f..eeb1d59fed8 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/IamPolicyBuilderExamples.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/IamPolicyBuilderExamples.java @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.iam; // snippet-start:[iam.java2.policy_builder.policy_builder_examples.imports] @@ -29,221 +27,231 @@ // snippet-end:[iam.java2.policy_builder.policy_builder_examples.imports] public class IamPolicyBuilderExamples { - private static final Logger logger = LoggerFactory.getLogger(IamPolicyBuilderExamples.class); + private static final Logger logger = LoggerFactory.getLogger(IamPolicyBuilderExamples.class); - public static void main(String[] args) { - IamPolicyBuilderExamples iamPolicyBuilderExamples = new IamPolicyBuilderExamples(); - // snippet-start:[iam.java2.policy_builder.policy_builder_examples.iamclient_build] - IamClient iam = IamClient.builder().region(Region.AWS_GLOBAL).build(); - // snippet-end:[iam.java2.policy_builder.policy_builder_examples.iamclient_build] + public static void main(String[] args) { + IamPolicyBuilderExamples iamPolicyBuilderExamples = new IamPolicyBuilderExamples(); + // snippet-start:[iam.java2.policy_builder.policy_builder_examples.iamclient_build] + IamClient iam = IamClient.builder().region(Region.AWS_GLOBAL).build(); + // snippet-end:[iam.java2.policy_builder.policy_builder_examples.iamclient_build] - iamPolicyBuilderExamples.runCreateAndUploadPolicyExample(iam); - iamPolicyBuilderExamples.runCreateNewBasedOnExisingPolicyExample(iam); + iamPolicyBuilderExamples.runCreateAndUploadPolicyExample(iam); + iamPolicyBuilderExamples.runCreateNewBasedOnExisingPolicyExample(iam); - if (iam != null) { - iam.close(); + if (iam != null) { + iam.close(); + } + + iamPolicyBuilderExamples.runTimeBasedPolicyExample(); + iamPolicyBuilderExamples.runMultipleConditionsExample(); + iamPolicyBuilderExamples.runSpecifyPrincipalsExample(); + iamPolicyBuilderExamples.runAllowCrossAccountAccessExample(); + } + + // snippet-start:[iam.java2.policy_builder.create_and_upload_policy] + public String createAndUploadPolicyExample(IamClient iam, String accountID, String policyName) { + // Build the policy. + IamPolicy policy = IamPolicy.builder() // 'version' defaults to "2012-10-17". + .addStatement(IamStatement.builder() + .effect(IamEffect.ALLOW) + .addAction("dynamodb:PutItem") + .addResource("arn:aws:dynamodb:us-east-1:" + accountID + + ":table/exampleTableName") + .build()) + .build(); + // Upload the policy. + iam.createPolicy(r -> r.policyName(policyName).policyDocument(policy.toJson())); + return policy.toJson(IamPolicyWriter.builder().prettyPrint(true).build()); + } + // snippet-end:[iam.java2.policy_builder.create_and_upload_policy] + + private void runCreateAndUploadPolicyExample(IamClient iam) { + String accountId = getAccountID(); + String policyName = "AllowPutItemToExampleTable"; + + String jsonPolicy = createAndUploadPolicyExample(iam, accountId, policyName); + logger.info(jsonPolicy); + + GetPolicyResponse putItemPolicy = iam + .getPolicy(b -> b.policyArn("arn:aws:iam::" + accountId + ":policy/" + policyName)); + iam.deletePolicy(b -> b.policyArn(putItemPolicy.policy().arn())); + logger.info("Policy [{}] deleted", putItemPolicy.policy().arn()); + } + + // snippet-start:[iam.java2.policy_builder.create_new_based_on_existing_policy] + public String createNewBasedOnExistingPolicyExample(IamClient iam, String accountID, String policyName, + String newPolicyName) { + + String policyArn = "arn:aws:iam::" + accountID + ":policy/" + policyName; + GetPolicyResponse getPolicyResponse = iam.getPolicy(r -> r.policyArn(policyArn)); + + String policyVersion = getPolicyResponse.policy().defaultVersionId(); + GetPolicyVersionResponse getPolicyVersionResponse = iam + .getPolicyVersion(r -> r.policyArn(policyArn).versionId(policyVersion)); + + // Create an IamPolicy instance from the JSON string returned from IAM. + String decodedPolicy = URLDecoder.decode(getPolicyVersionResponse.policyVersion().document(), + StandardCharsets.UTF_8); + IamPolicy policy = IamPolicy.fromJson(decodedPolicy); + + /* + * All IamPolicy components are immutable, so use the copy method that creates a + * new instance that + * can be altered in the same method call. + * + * Add the ability to get an item from DynamoDB as an additional action. + */ + IamStatement newStatement = policy.statements().get(0).copy(s -> s.addAction("dynamodb:GetItem")); + + // Create a new statement that replaces the original statement. + IamPolicy newPolicy = policy.copy(p -> p.statements(Arrays.asList(newStatement))); + + // Upload the new policy. IAM now has both policies. + iam.createPolicy(r -> r.policyName(newPolicyName) + .policyDocument(newPolicy.toJson())); + + return newPolicy.toJson(IamPolicyWriter.builder().prettyPrint(true).build()); + } + // snippet-end:[iam.java2.policy_builder.create_new_based_on_existing_policy] + + private void runCreateNewBasedOnExisingPolicyExample(IamClient iam) { + String accountID = getAccountID(); + String policyName = "AllowPutItemToExampleTable"; + String newPolicyName = "AllowGetAndPutItemToExampleTable"; + // First part of the example is to create the policy. + String jsonPolicy = createAndUploadPolicyExample(iam, accountID, policyName); + logger.info(jsonPolicy); + + String jsonNewPolicy = createNewBasedOnExistingPolicyExample(iam, accountID, policyName, newPolicyName); + logger.info(jsonNewPolicy); + + // Delete the two policies + GetPolicyResponse putItemPolicy = iam + .getPolicy(b -> b.policyArn("arn:aws:iam::" + accountID + ":policy/" + policyName)); + iam.deletePolicy(b -> b.policyArn(putItemPolicy.policy().arn())); + logger.info("Policy [{}] deleted", putItemPolicy.policy().arn()); + + GetPolicyResponse getAndPutItemPolicy = iam + .getPolicy(b -> b.policyArn("arn:aws:iam::" + accountID + ":policy/" + newPolicyName)); + iam.deletePolicy(b -> b.policyArn(getAndPutItemPolicy.policy().arn())); + logger.info("Policy [{}] deleted", getAndPutItemPolicy.policy().arn()); + } + + // snippet-start:[iam.java2.policy_builder.multiple_conditions] + public String multipleConditionsExample() { + IamPolicy policy = IamPolicy.builder() + .addStatement(b -> b + .effect(IamEffect.ALLOW) + .addAction("dynamodb:GetItem") + .addAction("dynamodb:BatchGetItem") + .addAction("dynamodb:Query") + .addAction("dynamodb:PutItem") + .addAction("dynamodb:UpdateItem") + .addAction("dynamodb:DeleteItem") + .addAction("dynamodb:BatchWriteItem") + .addResource("arn:aws:dynamodb:*:*:table/table-name") + .addConditions(IamConditionOperator.STRING_EQUALS + .addPrefix("ForAllValues:"), + "dynamodb:Attributes", + List.of("column-name1", "column-name2", "column-name3")) + .addCondition(b1 -> b1 + .operator(IamConditionOperator.STRING_EQUALS + .addSuffix("IfExists")) + .key("dynamodb:Select") + .value("SPECIFIC_ATTRIBUTES"))) + .build(); + + return policy.toJson(IamPolicyWriter.builder() + .prettyPrint(true).build()); + } + // snippet-end:[iam.java2.policy_builder.multiple_conditions] + + private void runMultipleConditionsExample() { + String jsonPolicy = multipleConditionsExample(); + logger.info(jsonPolicy); + + } + + // snippet-start:[iam.java2.policy_builder.time_based] + public String timeBasedPolicyExample() { + IamPolicy policy = IamPolicy.builder() + .addStatement(b -> b + .effect(IamEffect.ALLOW) + .addAction("dynamodb:GetItem") + .addResource(IamResource.ALL) + .addCondition(b1 -> b1 + .operator(IamConditionOperator.DATE_GREATER_THAN) + .key("aws:CurrentTime") + .value("2020-04-01T00:00:00Z")) + .addCondition(b1 -> b1 + .operator(IamConditionOperator.DATE_LESS_THAN) + .key("aws:CurrentTime") + .value("2020-06-30T23:59:59Z"))) + .build(); + + // Use an IamPolicyWriter to write out the JSON string to a more readable + // format. + return policy.toJson(IamPolicyWriter.builder() + .prettyPrint(true) + .build()); + } + // snippet-end:[iam.java2.policy_builder.time_based] + + private void runTimeBasedPolicyExample() { + String policyJson = timeBasedPolicyExample(); + logger.info(policyJson); + } + + // snippet-start:[iam.java2.policy_builder.specify_principals] + public String specifyPrincipalsExample() { + IamPolicy policy = IamPolicy.builder() + .addStatement(b -> b + .effect(IamEffect.DENY) + .addAction("s3:*") + .addPrincipal(IamPrincipal.ALL) + .addResource("arn:aws:s3:::BUCKETNAME/*") + .addResource("arn:aws:s3:::BUCKETNAME") + .addCondition(b1 -> b1 + .operator(IamConditionOperator.ARN_NOT_EQUALS) + .key("aws:PrincipalArn") + .value("arn:aws:iam::444455556666:user/user-name"))) + .build(); + return policy.toJson(IamPolicyWriter.builder() + .prettyPrint(true).build()); + } + // snippet-end:[iam.java2.policy_builder.specify_principals] + + private void runSpecifyPrincipalsExample() { + String policyJson = specifyPrincipalsExample(); + logger.info(policyJson); + } + + // snippet-start:[iam.java2.policy_builder.allow_cross_account_access] + public String allowCrossAccountAccessExample() { + IamPolicy policy = IamPolicy.builder() + .addStatement(b -> b + .effect(IamEffect.ALLOW) + .addPrincipal(IamPrincipalType.AWS, "111122223333") + .addAction("s3:PutObject") + .addResource("arn:aws:s3:::DOC-EXAMPLE-BUCKET/*") + .addCondition(b1 -> b1 + .operator(IamConditionOperator.STRING_EQUALS) + .key("s3:x-amz-acl") + .value("bucket-owner-full-control"))) + .build(); + return policy.toJson(IamPolicyWriter.builder() + .prettyPrint(true).build()); + } + // snippet-end:[iam.java2.policy_builder.allow_cross_account_access] + + private void runAllowCrossAccountAccessExample() { + String policyJson = allowCrossAccountAccessExample(); + logger.info(policyJson); } - iamPolicyBuilderExamples.runTimeBasedPolicyExample(); - iamPolicyBuilderExamples.runMultipleConditionsExample(); - iamPolicyBuilderExamples.runSpecifyPrincipalsExample(); - iamPolicyBuilderExamples.runAllowCrossAccountAccessExample(); - } - - // snippet-start:[iam.java2.policy_builder.create_and_upload_policy] - public String createAndUploadPolicyExample(IamClient iam, String accountID, String policyName) { - // Build the policy. - IamPolicy policy = - IamPolicy.builder() // 'version' defaults to "2012-10-17". - .addStatement(IamStatement.builder() - .effect(IamEffect.ALLOW) - .addAction("dynamodb:PutItem") - .addResource("arn:aws:dynamodb:us-east-1:" + accountID + ":table/exampleTableName") - .build()) - .build(); - // Upload the policy. - iam.createPolicy(r -> r.policyName(policyName).policyDocument(policy.toJson())); - return policy.toJson(IamPolicyWriter.builder().prettyPrint(true).build()); - } - // snippet-end:[iam.java2.policy_builder.create_and_upload_policy] - - private void runCreateAndUploadPolicyExample(IamClient iam) { - String accountId = getAccountID(); - String policyName = "AllowPutItemToExampleTable"; - - String jsonPolicy = createAndUploadPolicyExample(iam, accountId, policyName); - logger.info(jsonPolicy); - - GetPolicyResponse putItemPolicy = iam.getPolicy(b -> b.policyArn("arn:aws:iam::" + accountId + ":policy/" + policyName)); - iam.deletePolicy(b -> b.policyArn(putItemPolicy.policy().arn())); - logger.info("Policy [{}] deleted", putItemPolicy.policy().arn()); - } - - // snippet-start:[iam.java2.policy_builder.create_new_based_on_existing_policy] - public String createNewBasedOnExistingPolicyExample(IamClient iam, String accountID, String policyName, String newPolicyName) { - - String policyArn = "arn:aws:iam::" + accountID + ":policy/" + policyName; - GetPolicyResponse getPolicyResponse = iam.getPolicy(r -> r.policyArn(policyArn)); - - String policyVersion = getPolicyResponse.policy().defaultVersionId(); - GetPolicyVersionResponse getPolicyVersionResponse = - iam.getPolicyVersion(r -> r.policyArn(policyArn).versionId(policyVersion)); - - // Create an IamPolicy instance from the JSON string returned from IAM. - String decodedPolicy = URLDecoder.decode(getPolicyVersionResponse.policyVersion().document(), StandardCharsets.UTF_8); - IamPolicy policy = IamPolicy.fromJson(decodedPolicy); - - /* - All IamPolicy components are immutable, so use the copy method that creates a new instance that - can be altered in the same method call. - - Add the ability to get an item from DynamoDB as an additional action. - */ - IamStatement newStatement = policy.statements().get(0).copy(s -> s.addAction("dynamodb:GetItem")); - - // Create a new statement that replaces the original statement. - IamPolicy newPolicy = policy.copy(p -> p.statements(Arrays.asList(newStatement))); - - // Upload the new policy. IAM now has both policies. - iam.createPolicy(r -> r.policyName(newPolicyName) - .policyDocument(newPolicy.toJson())); - - return newPolicy.toJson(IamPolicyWriter.builder().prettyPrint(true).build()); - } - // snippet-end:[iam.java2.policy_builder.create_new_based_on_existing_policy] - - private void runCreateNewBasedOnExisingPolicyExample(IamClient iam) { - String accountID = getAccountID(); - String policyName = "AllowPutItemToExampleTable"; - String newPolicyName = "AllowGetAndPutItemToExampleTable"; - // First part of the example is to create the policy. - String jsonPolicy = createAndUploadPolicyExample(iam, accountID, policyName); - logger.info(jsonPolicy); - - String jsonNewPolicy = createNewBasedOnExistingPolicyExample(iam, accountID, policyName, newPolicyName); - logger.info(jsonNewPolicy); - - // Delete the two policies - GetPolicyResponse putItemPolicy = iam.getPolicy(b -> b.policyArn("arn:aws:iam::" + accountID + ":policy/" + policyName)); - iam.deletePolicy(b -> b.policyArn(putItemPolicy.policy().arn())); - logger.info("Policy [{}] deleted", putItemPolicy.policy().arn()); - - GetPolicyResponse getAndPutItemPolicy = iam.getPolicy(b -> b.policyArn("arn:aws:iam::" + accountID + ":policy/" + newPolicyName)); - iam.deletePolicy(b -> b.policyArn(getAndPutItemPolicy.policy().arn())); - logger.info("Policy [{}] deleted", getAndPutItemPolicy.policy().arn()); - } - - // snippet-start:[iam.java2.policy_builder.multiple_conditions] - public String multipleConditionsExample() { - IamPolicy policy = IamPolicy.builder() - .addStatement(b -> b - .effect(IamEffect.ALLOW) - .addAction("dynamodb:GetItem") - .addAction("dynamodb:BatchGetItem") - .addAction("dynamodb:Query") - .addAction("dynamodb:PutItem") - .addAction("dynamodb:UpdateItem") - .addAction("dynamodb:DeleteItem") - .addAction("dynamodb:BatchWriteItem") - .addResource("arn:aws:dynamodb:*:*:table/table-name") - .addConditions(IamConditionOperator.STRING_EQUALS.addPrefix("ForAllValues:"), - "dynamodb:Attributes", - List.of("column-name1", "column-name2", "column-name3")) - .addCondition(b1 -> b1.operator(IamConditionOperator.STRING_EQUALS.addSuffix("IfExists")) - .key("dynamodb:Select") - .value("SPECIFIC_ATTRIBUTES"))) - .build(); - - return policy.toJson(IamPolicyWriter.builder() - .prettyPrint(true).build()); - } - // snippet-end:[iam.java2.policy_builder.multiple_conditions] - - private void runMultipleConditionsExample() { - String jsonPolicy = multipleConditionsExample(); - logger.info(jsonPolicy); - - } - - // snippet-start:[iam.java2.policy_builder.time_based] - public String timeBasedPolicyExample() { - IamPolicy policy = IamPolicy.builder() - .addStatement(b -> b - .effect(IamEffect.ALLOW) - .addAction("dynamodb:GetItem") - .addResource(IamResource.ALL) - .addCondition(b1 -> b1 - .operator(IamConditionOperator.DATE_GREATER_THAN) - .key("aws:CurrentTime") - .value("2020-04-01T00:00:00Z")) - .addCondition(b1 -> b1 - .operator(IamConditionOperator.DATE_LESS_THAN) - .key("aws:CurrentTime") - .value("2020-06-30T23:59:59Z"))) - .build(); - - // Use an IamPolicyWriter to write out the JSON string to a more readable format. - return policy.toJson(IamPolicyWriter.builder() - .prettyPrint(true) - .build()); - } - // snippet-end:[iam.java2.policy_builder.time_based] - - private void runTimeBasedPolicyExample() { - String policyJson = timeBasedPolicyExample(); - logger.info(policyJson); - } - - // snippet-start:[iam.java2.policy_builder.specify_principals] - public String specifyPrincipalsExample() { - IamPolicy policy = IamPolicy.builder() - .addStatement(b -> b - .effect(IamEffect.DENY) - .addAction("s3:*") - .addPrincipal(IamPrincipal.ALL) - .addResource("arn:aws:s3:::BUCKETNAME/*") - .addResource("arn:aws:s3:::BUCKETNAME") - .addCondition(b1 -> b1 - .operator(IamConditionOperator.ARN_NOT_EQUALS) - .key("aws:PrincipalArn") - .value("arn:aws:iam::444455556666:user/user-name"))) - .build(); - return policy.toJson(IamPolicyWriter.builder() - .prettyPrint(true).build()); - } - // snippet-end:[iam.java2.policy_builder.specify_principals] - - private void runSpecifyPrincipalsExample() { - String policyJson = specifyPrincipalsExample(); - logger.info(policyJson); - } - - // snippet-start:[iam.java2.policy_builder.allow_cross_account_access] - public String allowCrossAccountAccessExample() { - IamPolicy policy = IamPolicy.builder() - .addStatement(b -> b - .effect(IamEffect.ALLOW) - .addPrincipal(IamPrincipalType.AWS, "111122223333") - .addAction("s3:PutObject") - .addResource("arn:aws:s3:::DOC-EXAMPLE-BUCKET/*") - .addCondition(b1 -> b1 - .operator(IamConditionOperator.STRING_EQUALS) - .key("s3:x-amz-acl") - .value("bucket-owner-full-control"))) - .build(); - return policy.toJson(IamPolicyWriter.builder() - .prettyPrint(true).build()); - } - // snippet-end:[iam.java2.policy_builder.allow_cross_account_access] - - private void runAllowCrossAccountAccessExample() { - String policyJson = allowCrossAccountAccessExample(); - logger.info(policyJson); - } - - String getAccountID() { - try (StsClient stsClient = StsClient.create()) { - return stsClient.getCallerIdentity().account(); + String getAccountID() { + try (StsClient stsClient = StsClient.create()) { + return stsClient.getCallerIdentity().account(); + } } - } } diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/ListAccessKeys.java b/javav2/example_code/iam/src/main/java/com/example/iam/ListAccessKeys.java index 4c021e7794c..80db7f51897 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/ListAccessKeys.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/ListAccessKeys.java @@ -1,10 +1,6 @@ -//snippet-sourcedescription:[ListAccessKeys.java demonstrates how to list access keys associated with an AWS Identity and Access Management (IAM) user.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.iam; // snippet-start:[iam.java2.list_access_keys.main] @@ -18,7 +14,8 @@ // snippet-end:[iam.java2.list_access_keys.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +25,12 @@ public class ListAccessKeys { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - userName - The name of the user for which access keys are retrieved.\s - """; + Where: + userName - The name of the user for which access keys are retrieved.\s + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +40,8 @@ public static void main(String[] args) { String userName = args[0]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); listKeys(iam, userName); System.out.println("Done"); @@ -61,16 +58,16 @@ public static void listKeys(IamClient iam, String userName) { if (newMarker == null) { ListAccessKeysRequest request = ListAccessKeysRequest.builder() - .userName(userName) - .build(); + .userName(userName) + .build(); response = iam.listAccessKeys(request); } else { ListAccessKeysRequest request = ListAccessKeysRequest.builder() - .userName(userName) - .marker(newMarker) - .build(); + .userName(userName) + .marker(newMarker) + .build(); response = iam.listAccessKeys(request); } diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/ListAccountAliases.java b/javav2/example_code/iam/src/main/java/com/example/iam/ListAccountAliases.java index c792a10f89b..9f5058776c5 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/ListAccountAliases.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/ListAccountAliases.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[ListAccountAliases.java demonstrates how to list all aliases associated with an AWS account.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.iam; // snippet-start:[iam.java2.list_account_aliases.main] @@ -17,7 +12,8 @@ // snippet-end:[iam.java2.list_account_aliases.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,8 +23,8 @@ public class ListAccountAliases { public static void main(String[] args) { Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); listAliases(iam); System.out.println("Done"); diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/ListServerCertificates.java b/javav2/example_code/iam/src/main/java/com/example/iam/ListServerCertificates.java index 9942477042f..171734ada92 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/ListServerCertificates.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/ListServerCertificates.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[ListServerCertificates.java demonstrates how to list all server certificates associated with an AWS account.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.iam; // snippet-start:[iam.java2.list_server_certificates.main] @@ -19,7 +14,8 @@ // snippet-end:[iam.java2.list_server_certificates.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,8 +25,8 @@ public class ListServerCertificates { public static void main(String[] args) { Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); listCertificates(iam); System.out.println("Done"); @@ -50,8 +46,8 @@ public static void listCertificates(IamClient iam) { response = iam.listServerCertificates(request); } else { ListServerCertificatesRequest request = ListServerCertificatesRequest.builder() - .marker(newMarker) - .build(); + .marker(newMarker) + .build(); response = iam.listServerCertificates(request); } diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/ListUsers.java b/javav2/example_code/iam/src/main/java/com/example/iam/ListUsers.java index 3066a1d1224..a8ce4de5c44 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/ListUsers.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/ListUsers.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[ListUsers.java demonstrates how to list all AWS Identity and Access Management (IAM) users.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.iam; // snippet-start:[iam.java2.list_users.main] @@ -20,7 +15,8 @@ // snippet-end:[iam.java2.list_users.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,8 +26,8 @@ public class ListUsers { public static void main(String[] args) { Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); listAllUsers(iam); System.out.println("Done"); @@ -49,8 +45,8 @@ public static void listAllUsers(IamClient iam) { response = iam.listUsers(request); } else { ListUsersRequest request = ListUsersRequest.builder() - .marker(newMarker) - .build(); + .marker(newMarker) + .build(); response = iam.listUsers(request); } @@ -59,7 +55,8 @@ public static void listAllUsers(IamClient iam) { System.out.format("\n Retrieved user %s", user.userName()); AttachedPermissionsBoundary permissionsBoundary = user.permissionsBoundary(); if (permissionsBoundary != null) - System.out.format("\n Permissions boundary details %s", permissionsBoundary.permissionsBoundaryTypeAsString()); + System.out.format("\n Permissions boundary details %s", + permissionsBoundary.permissionsBoundaryTypeAsString()); } if (!response.isTruncated()) { diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/UpdateAccessKey.java b/javav2/example_code/iam/src/main/java/com/example/iam/UpdateAccessKey.java index 7ca34ae2cc6..fadce676f14 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/UpdateAccessKey.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/UpdateAccessKey.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[UpdateAccessKey.java demonstrates how to update the status of an access key for an AWS Identity and Access Management (IAM) user.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.iam; // snippet-start:[iam.java2.update_access_key.main] @@ -18,7 +13,8 @@ // snippet-end:[iam.java2.update_access_key.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,17 +23,18 @@ public class UpdateAccessKey { private static StatusType statusType; + public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - username - The name of the user whose key you want to update.\s - accessId - The access key ID of the secret access key you want to update.\s - status - The status you want to assign to the secret access key.\s - """; + Where: + username - The name of the user whose key you want to update.\s + accessId - The access key ID of the secret access key you want to update.\s + status - The status you want to assign to the secret access key.\s + """; if (args.length != 3) { System.out.println(usage); @@ -49,8 +46,8 @@ public static void main(String[] args) { String status = args[2]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); updateKey(iam, username, accessId, status); System.out.println("Done"); @@ -68,14 +65,14 @@ public static void updateKey(IamClient iam, String username, String accessId, St } UpdateAccessKeyRequest request = UpdateAccessKeyRequest.builder() - .accessKeyId(accessId) - .userName(username) - .status(statusType) - .build(); + .accessKeyId(accessId) + .userName(username) + .status(statusType) + .build(); iam.updateAccessKey(request); System.out.printf("Successfully updated the status of access key %s to" + - "status %s for user %s", accessId, status, username); + "status %s for user %s", accessId, status, username); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/UpdateServerCertificate.java b/javav2/example_code/iam/src/main/java/com/example/iam/UpdateServerCertificate.java index be664d1c90a..3a8fc4ef0fa 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/UpdateServerCertificate.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/UpdateServerCertificate.java @@ -1,10 +1,6 @@ -//snippet-sourcedescription:[UpdateServerCertificate.java demonstrates how to update the name of an AWS Identity and Access Management (IAM) server certificate.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.iam; // snippet-start:[iam.java2.update_server_certificate.complete] @@ -17,7 +13,8 @@ // snippet-end:[iam.java2.update_server_certificate.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,13 +24,13 @@ public class UpdateServerCertificate { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - curName - The current certificate name.\s - newName - An updated certificate name.\s - """; + Where: + curName - The current certificate name.\s + newName - An updated certificate name.\s + """; if (args.length != 2) { System.out.println(usage); @@ -44,19 +41,20 @@ public static void main(String[] args) { String newName = args[1]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); - updateCertificate(iam, curName, newName) ; + updateCertificate(iam, curName, newName); System.out.println("Done"); iam.close(); } + public static void updateCertificate(IamClient iam, String curName, String newName) { try { UpdateServerCertificateRequest request = UpdateServerCertificateRequest.builder() - .serverCertificateName(curName) - .newServerCertificateName(newName) - .build(); + .serverCertificateName(curName) + .newServerCertificateName(newName) + .build(); iam.updateServerCertificate(request); System.out.printf("Successfully updated server certificate to name %s", newName); diff --git a/javav2/example_code/iam/src/main/java/com/example/iam/UpdateUser.java b/javav2/example_code/iam/src/main/java/com/example/iam/UpdateUser.java index 756a9b90dad..16ed498fa6a 100644 --- a/javav2/example_code/iam/src/main/java/com/example/iam/UpdateUser.java +++ b/javav2/example_code/iam/src/main/java/com/example/iam/UpdateUser.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[UpdateUser.java demonstrates how to update the name of an AWS Identity and Access Management (IAM) user.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[IAM] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.iam; // snippet-start:[iam.java2.update_user.main] @@ -17,7 +12,8 @@ // snippet-end:[iam.java2.update_user.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,13 +23,13 @@ public class UpdateUser { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - curName - The current user name.\s - newName - An updated user name.\s - """; + Where: + curName - The current user name.\s + newName - An updated user name.\s + """; if (args.length != 2) { System.out.println(usage); @@ -44,8 +40,8 @@ public static void main(String[] args) { String newName = args[1]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() - .region(region) - .build(); + .region(region) + .build(); updateIAMUser(iam, curName, newName); System.out.println("Done"); @@ -55,9 +51,9 @@ public static void main(String[] args) { public static void updateIAMUser(IamClient iam, String curName, String newName) { try { UpdateUserRequest request = UpdateUserRequest.builder() - .userName(curName) - .newUserName(newName) - .build(); + .userName(curName) + .newUserName(newName) + .build(); iam.updateUser(request); System.out.printf("Successfully updated user to username %s", newName); diff --git a/javav2/example_code/iam/src/test/java/IAMServiceTest.java b/javav2/example_code/iam/src/test/java/IAMServiceTest.java index 538dcbe9997..eec835bd976 100644 --- a/javav2/example_code/iam/src/test/java/IAMServiceTest.java +++ b/javav2/example_code/iam/src/test/java/IAMServiceTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.iam.*; import com.google.gson.Gson; @@ -27,12 +25,12 @@ public class IAMServiceTest { private static IamClient iam; - private static String userName=""; - private static String policyName=""; - private static String roleName=""; - private static String policyARN=""; - private static String keyId ="" ; - private static String accountAlias=""; + private static String userName = ""; + private static String policyName = ""; + private static String roleName = ""; + private static String policyARN = ""; + private static String keyId = ""; + private static String accountAlias = ""; private static String usernameSc = ""; private static String policyNameSc = ""; private static String roleNameSc = ""; @@ -44,52 +42,55 @@ public class IAMServiceTest { public static void setUp() { Region region = Region.AWS_GLOBAL; iam = IamClient.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); String json = getSecretValues(); SecretValues values = gson.fromJson(json, SecretValues.class); userName = values.getUserName(); - policyName= values.getPolicyName(); - roleName= values.getRoleName(); - accountAlias=values.getAccountAlias(); - usernameSc=values.getUsernameSc(); - policyNameSc=values.getPolicyNameSc(); - roleNameSc=values.getRoleNameSc(); - roleSessionName=values.getRoleName(); - fileLocationSc=values.getFileLocationSc(); - bucketNameSc=values.getBucketNameSc(); - - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - - try (InputStream input = IAMServiceTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - prop.load(input); - userName = prop.getProperty("userName"); - policyName= prop.getProperty("policyName"); - policyARN= prop.getProperty("policyARN"); - roleName=prop.getProperty("roleName"); - accountAlias=prop.getProperty("accountAlias"); - usernameSc=prop.getProperty("usernameSc"); - policyNameSc=prop.getProperty("policyNameSc"); - roleNameSc=prop.getProperty("roleNameSc"); - roleSessionName=prop.getProperty("roleSessionName"); - fileLocationSc=prop.getProperty("fileLocationSc"); - bucketNameSc=prop.getProperty("bucketNameSc"); - - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + policyName = values.getPolicyName(); + roleName = values.getRoleName(); + accountAlias = values.getAccountAlias(); + usernameSc = values.getUsernameSc(); + policyNameSc = values.getPolicyNameSc(); + roleNameSc = values.getRoleNameSc(); + roleSessionName = values.getRoleName(); + fileLocationSc = values.getFileLocationSc(); + bucketNameSc = values.getBucketNameSc(); + + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * + * try (InputStream input = + * IAMServiceTest.class.getClassLoader().getResourceAsStream("config.properties" + * )) { + * Properties prop = new Properties(); + * prop.load(input); + * userName = prop.getProperty("userName"); + * policyName= prop.getProperty("policyName"); + * policyARN= prop.getProperty("policyARN"); + * roleName=prop.getProperty("roleName"); + * accountAlias=prop.getProperty("accountAlias"); + * usernameSc=prop.getProperty("usernameSc"); + * policyNameSc=prop.getProperty("policyNameSc"); + * roleNameSc=prop.getProperty("roleNameSc"); + * roleSessionName=prop.getProperty("roleSessionName"); + * fileLocationSc=prop.getProperty("fileLocationSc"); + * bucketNameSc=prop.getProperty("bucketNameSc"); + * + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @@ -114,7 +115,7 @@ public void CreatePolicy() { @Tag("IntegrationTest") @Order(3) public void CreateAccessKey() { - keyId = CreateAccessKey.createIAMAccessKey(iam,userName); + keyId = CreateAccessKey.createIAMAccessKey(iam, userName); assertFalse(keyId.isEmpty()); System.out.println("Test 3 passed"); } @@ -123,7 +124,7 @@ public void CreateAccessKey() { @Tag("IntegrationTest") @Order(4) public void AttachRolePolicy() { - assertDoesNotThrow(() ->AttachRolePolicy.attachIAMRolePolicy(iam, roleName, policyARN)); + assertDoesNotThrow(() -> AttachRolePolicy.attachIAMRolePolicy(iam, roleName, policyARN)); System.out.println("\n Test 4 passed"); } @@ -131,7 +132,7 @@ public void AttachRolePolicy() { @Tag("IntegrationTest") @Order(5) public void DetachRolePolicy() { - assertDoesNotThrow(() ->DetachRolePolicy.detachPolicy(iam, roleName, policyARN)); + assertDoesNotThrow(() -> DetachRolePolicy.detachPolicy(iam, roleName, policyARN)); System.out.println("Test 5 passed"); } @@ -139,7 +140,7 @@ public void DetachRolePolicy() { @Tag("IntegrationTest") @Order(6) public void GetPolicy() { - assertDoesNotThrow(() ->GetPolicy.getIAMPolicy(iam, policyARN)); + assertDoesNotThrow(() -> GetPolicy.getIAMPolicy(iam, policyARN)); System.out.println("Test 6 passed"); } @@ -147,7 +148,7 @@ public void GetPolicy() { @Tag("IntegrationTest") @Order(7) public void ListAccessKeys() { - assertDoesNotThrow(() ->ListAccessKeys.listKeys(iam,userName)); + assertDoesNotThrow(() -> ListAccessKeys.listKeys(iam, userName)); System.out.println("Test 7 passed"); } @@ -155,23 +156,23 @@ public void ListAccessKeys() { @Tag("IntegrationTest") @Order(8) public void ListUsers() { - assertDoesNotThrow(() ->ListUsers.listAllUsers(iam)); + assertDoesNotThrow(() -> ListUsers.listAllUsers(iam)); System.out.println("Test 8 passed"); } @Test @Tag("IntegrationTest") @Order(9) - public void CreateAccountAlias() { - assertDoesNotThrow(() ->CreateAccountAlias.createIAMAccountAlias(iam, accountAlias)); - System.out.println("Test 9 passed"); + public void CreateAccountAlias() { + assertDoesNotThrow(() -> CreateAccountAlias.createIAMAccountAlias(iam, accountAlias)); + System.out.println("Test 9 passed"); } @Test @Tag("IntegrationTest") @Order(10) public void DeleteAccountAlias() { - assertDoesNotThrow(() ->DeleteAccountAlias.deleteIAMAccountAlias(iam, accountAlias)); + assertDoesNotThrow(() -> DeleteAccountAlias.deleteIAMAccountAlias(iam, accountAlias)); System.out.println("Test 10 passed"); } @@ -179,23 +180,23 @@ public void DeleteAccountAlias() { @Tag("IntegrationTest") @Order(11) public void DeletePolicy() { - assertDoesNotThrow(() ->DeletePolicy.deleteIAMPolicy(iam, policyARN)); - System.out.println("Test 12 passed"); + assertDoesNotThrow(() -> DeletePolicy.deleteIAMPolicy(iam, policyARN)); + System.out.println("Test 12 passed"); } @Test @Tag("IntegrationTest") @Order(12) - public void DeleteAccessKey() { - assertDoesNotThrow(() ->DeleteAccessKey.deleteKey(iam, userName, keyId)); - System.out.println("Test 12 passed"); - } + public void DeleteAccessKey() { + assertDoesNotThrow(() -> DeleteAccessKey.deleteKey(iam, userName, keyId)); + System.out.println("Test 12 passed"); + } @Test @Tag("IntegrationTest") @Order(13) public void DeleteUser() { - assertDoesNotThrow(() ->DeleteUser.deleteIAMUser(iam,userName)); + assertDoesNotThrow(() -> DeleteUser.deleteIAMUser(iam, userName)); System.out.println("Test 13 passed"); } @@ -214,15 +215,15 @@ public void TestIAMScenario() throws Exception { String accessKey = myKey.accessKeyId(); String secretKey = myKey.secretAccessKey(); String assumeRolePolicyDocument = "{" + - "\"Version\": \"2012-10-17\"," + - "\"Statement\": [{" + - "\"Effect\": \"Allow\"," + - "\"Principal\": {" + - " \"AWS\": \"" + userArn + "\"" + - "}," + - "\"Action\": \"sts:AssumeRole\"" + - "}]" + - "}"; + "\"Version\": \"2012-10-17\"," + + "\"Statement\": [{" + + "\"Effect\": \"Allow\"," + + "\"Principal\": {" + + " \"AWS\": \"" + userArn + "\"" + + "}," + + "\"Action\": \"sts:AssumeRole\"" + + "}]" + + "}"; System.out.println(assumeRolePolicyDocument); System.out.println(usernameSc + " was successfully created."); @@ -254,22 +255,22 @@ public void TestIAMScenario() throws Exception { System.out.println(DASHES); System.out.println("6 Getting ready to delete the AWS resources"); - IAMScenario.deleteKey(iam, usernameSc, accessKey ); + IAMScenario.deleteKey(iam, usernameSc, accessKey); IAMScenario.deleteRole(iam, roleNameSc, polArn); IAMScenario.deleteIAMUser(iam, usernameSc); System.out.println(DASHES); } private static String getSecretValues() { - SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + SecretsManagerClient secretClient = SecretsManagerClient.builder() + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/iam"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -295,6 +296,7 @@ class SecretValues { private String fileLocationSc; private String bucketNameSc; + public String getUserName() { return userName; } @@ -332,4 +334,3 @@ public String getBucketNameSc() { } } } - diff --git a/javav2/example_code/iam/src/test/java/com/example/iam/IamPolicyBuilderExamplesTest.java b/javav2/example_code/iam/src/test/java/com/example/iam/IamPolicyBuilderExamplesTest.java index b203764751f..b8c4193355d 100644 --- a/javav2/example_code/iam/src/test/java/com/example/iam/IamPolicyBuilderExamplesTest.java +++ b/javav2/example_code/iam/src/test/java/com/example/iam/IamPolicyBuilderExamplesTest.java @@ -1,7 +1,5 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0 - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.iam; import org.junit.jupiter.api.AfterEach; @@ -28,8 +26,8 @@ private static void analyze(String policyJson, PolicyType policyType) { final ValidatePolicyResponse response = analyzerClient.validatePolicy(b -> b .policyDocument(policyJson) .policyType(policyType)); - response.findings().forEach(f -> - logger.info("Type [{}]; Detail [{}]", f.findingType().name(), f.findingDetails())); + response.findings() + .forEach(f -> logger.info("Type [{}]; Detail [{}]", f.findingType().name(), f.findingDetails())); Assertions.assertEquals(0, response.findings().size()); } } @@ -48,7 +46,8 @@ void tearDown() { } /** - * If this test succeeds, the syntax of the policy that is created is checked by the IAM service on upload. + * If this test succeeds, the syntax of the policy that is created is checked by + * the IAM service on upload. */ @Test @Tag("IntegrationTest") @@ -58,13 +57,15 @@ void createAndUploadPolicyExample() { String jsonPolicy = examples.createAndUploadPolicyExample(iam, accountId, policyName); logger.info(jsonPolicy); - GetPolicyResponse putItemPolicy = iam.getPolicy(b -> b.policyArn("arn:aws:iam::" + accountId + ":policy/" + policyName)); + GetPolicyResponse putItemPolicy = iam + .getPolicy(b -> b.policyArn("arn:aws:iam::" + accountId + ":policy/" + policyName)); iam.deletePolicy(b -> b.policyArn(putItemPolicy.policy().arn())); logger.info("Policy [{}] deleted", putItemPolicy.policy().arn()); } /** - * If this test succeeds, the syntax of the policies that are created and uploaded will be checked by the IAM service. + * If this test succeeds, the syntax of the policies that are created and + * uploaded will be checked by the IAM service. */ @Test @Tag("IntegrationTest") @@ -76,15 +77,18 @@ void createNewBasedOnExisingPolicyExample() { String jsonPolicy = examples.createAndUploadPolicyExample(iam, accountID, policyName); logger.info(jsonPolicy); - String jsonNewPolicy = examples.createNewBasedOnExistingPolicyExample(iam, accountID, policyName, newPolicyName); + String jsonNewPolicy = examples.createNewBasedOnExistingPolicyExample(iam, accountID, policyName, + newPolicyName); logger.info(jsonNewPolicy); // Delete the two policies - GetPolicyResponse putItemPolicy = iam.getPolicy(b -> b.policyArn("arn:aws:iam::" + accountID + ":policy/" + policyName)); + GetPolicyResponse putItemPolicy = iam + .getPolicy(b -> b.policyArn("arn:aws:iam::" + accountID + ":policy/" + policyName)); iam.deletePolicy(b -> b.policyArn(putItemPolicy.policy().arn())); logger.info("Policy [{}] deleted", putItemPolicy.policy().arn()); - GetPolicyResponse getAndPutItemPolicy = iam.getPolicy(b -> b.policyArn("arn:aws:iam::" + accountID + ":policy/" + newPolicyName)); + GetPolicyResponse getAndPutItemPolicy = iam + .getPolicy(b -> b.policyArn("arn:aws:iam::" + accountID + ":policy/" + newPolicyName)); iam.deletePolicy(b -> b.policyArn(getAndPutItemPolicy.policy().arn())); logger.info("Policy [{}] deleted", getAndPutItemPolicy.policy().arn()); } diff --git a/javav2/example_code/identitystore/run_example.sh b/javav2/example_code/identitystore/run_example.sh index a3beb4c2ef3..eaeb21704a2 100755 --- a/javav2/example_code/identitystore/run_example.sh +++ b/javav2/example_code/identitystore/run_example.sh @@ -1,13 +1,15 @@ -#!/bin/bash -if [[ -z $* ]] ; then - echo 'Supply the name of one of the example classes as an argument.' - echo 'If there are arguments to the class, put them in quotes after the class name.' - exit 1 -fi -export CLASSPATH=target/sdk-identitystore-examples-1.0.jar -export className=$1 -echo "## Running $className..." -shift -echo "## arguments $@..." -mvn exec:java -Dexec.mainClass="com.example.identitystore.$className" -Dexec.args="$@" - +#!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +if [[ -z $* ]] ; then + echo 'Supply the name of one of the example classes as an argument.' + echo 'If there are arguments to the class, put them in quotes after the class name.' + exit 1 +fi +export CLASSPATH=target/sdk-identitystore-examples-1.0.jar +export className=$1 +echo "## Running $className..." +shift +echo "## arguments $@..." +mvn exec:java -Dexec.mainClass="com.example.identitystore.$className" -Dexec.args="$@" + diff --git a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/CreateGroup.java b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/CreateGroup.java index b267160ac60..5b7e25ee924 100644 --- a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/CreateGroup.java +++ b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/CreateGroup.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[CreateGroup.java demonstrates how to create a group within the specified AWS Identitystore.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Identitystore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.identitystore; @@ -18,7 +12,8 @@ // snippet-end:[Identitystore.java2.create_group.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,13 +25,13 @@ public class CreateGroup { public static void main(String... args) { final String usage = """ - Usage: - \s - Where: - identitystoreId - The id of the identitystore.\s - groupName - The name of the group to create.\s - groupDescription - The description of the group to create.\s - """; + Usage: + \s + Where: + identitystoreId - The id of the identitystore.\s + groupName - The name of the group to create.\s + groupDescription - The description of the group to create.\s + """; if (args.length != 3) { System.out.println(usage); @@ -53,13 +48,14 @@ public static void main(String... args) { identitystore.close(); } - public static String createGroup(IdentitystoreClient identitystore, String identitystoreId, String groupName, String groupDescription) { + public static String createGroup(IdentitystoreClient identitystore, String identitystoreId, String groupName, + String groupDescription) { try { CreateGroupRequest request = CreateGroupRequest.builder() - .identityStoreId(identitystoreId) - .displayName(groupName) - .description(groupDescription) - .build(); + .identityStoreId(identitystoreId) + .displayName(groupName) + .description(groupDescription) + .build(); CreateGroupResponse response = identitystore.createGroup(request); return response.groupId(); diff --git a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/CreateGroupMembership.java b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/CreateGroupMembership.java index 1da33839888..8497de27668 100644 --- a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/CreateGroupMembership.java +++ b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/CreateGroupMembership.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[CreateGroupMembership.java demonstrates how to create a relationship between a member(user) and a group in a specified AWS Identitystore.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Identitystore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.identitystore; @@ -19,7 +13,8 @@ // snippet-end:[Identitystore.java2.create_group_membership.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,14 +25,14 @@ public class CreateGroupMembership { public static void main(String... args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - identitystoreId - The id of the identitystore.\s - groupId - The id of the group.\s - userId - The id of the user.\s - """; + Where: + identitystoreId - The id of the identitystore.\s + groupId - The id of the group.\s + userId - The id of the user.\s + """; if (args.length != 3) { System.out.println(usage); @@ -54,17 +49,18 @@ public static void main(String... args) { identitystore.close(); } - public static String createGroupMembership(IdentitystoreClient identitystore, String identitystoreId, String groupId, String userId) { + public static String createGroupMembership(IdentitystoreClient identitystore, String identitystoreId, + String groupId, String userId) { try { MemberId memberId = MemberId.builder() - .userId(userId) - .build(); + .userId(userId) + .build(); CreateGroupMembershipRequest request = CreateGroupMembershipRequest.builder() - .identityStoreId(identitystoreId) - .groupId(groupId) - .memberId(memberId) - .build(); + .identityStoreId(identitystoreId) + .groupId(groupId) + .memberId(memberId) + .build(); CreateGroupMembershipResponse response = identitystore.createGroupMembership(request); return response.membershipId(); diff --git a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/CreateUser.java b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/CreateUser.java index 67a1013d827..12aed98eeb7 100644 --- a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/CreateUser.java +++ b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/CreateUser.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[CreateUser.java demonstrates how to create a user within the specified AWS Identitystore.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Identitystore] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.identitystore; // snippet-start:[identitystore.java2.create_user.main] @@ -17,9 +12,9 @@ import software.amazon.awssdk.services.identitystore.model.Name; // snippet-end:[Identitystore.java2.create_user.import] - /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,15 +24,15 @@ public class CreateUser { public static void main(String... args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - identitystoreId - The id of the identitystore.\s - userName - The name of the user to create.\s - givenName - The first name of the user to create.\s - familyName - The lastName of the user to create.\s - """; + Where: + identitystoreId - The id of the identitystore.\s + userName - The name of the user to create.\s + givenName - The first name of the user to create.\s + familyName - The lastName of the user to create.\s + """; if (args.length != 4) { System.out.println(usage); @@ -55,20 +50,21 @@ public static void main(String... args) { identitystore.close(); } - public static String createUser(IdentitystoreClient identitystore, String identitystoreId, String userName, String givenName, String familyName) { + public static String createUser(IdentitystoreClient identitystore, String identitystoreId, String userName, + String givenName, String familyName) { try { String displayName = givenName + " " + familyName; Name name = Name.builder() - .givenName(givenName) - .familyName(familyName) - .build(); + .givenName(givenName) + .familyName(familyName) + .build(); CreateUserRequest request = CreateUserRequest.builder() - .identityStoreId(identitystoreId) - .userName(userName) - .displayName(displayName) - .name(name) - .build(); + .identityStoreId(identitystoreId) + .userName(userName) + .displayName(displayName) + .name(name) + .build(); CreateUserResponse response = identitystore.createUser(request); return response.userId(); diff --git a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DeleteGroup.java b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DeleteGroup.java index 712ddaa1f1d..54e11ce561c 100644 --- a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DeleteGroup.java +++ b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DeleteGroup.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DeleteGroup.java demonstrates how to delete a group within an AWS Identitystore given groupId.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Identitystore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.identitystore; @@ -18,7 +12,8 @@ // snippet-end:[Identitystore.java2.delete_group.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,13 +24,13 @@ public class DeleteGroup { public static void main(String... args) { final String usage = """ - Usage: - + Usage: + - Where: - identitystoreId - The id of the identitystore.\s - groupId - The id of the group to delete.\s - """; + Where: + identitystoreId - The id of the identitystore.\s + groupId - The id of the group to delete.\s + """; if (args.length != 2) { System.out.println(usage); @@ -53,9 +48,9 @@ public static void main(String... args) { public static String deleteGroup(IdentitystoreClient identitystore, String identitystoreId, String groupId) { try { DeleteGroupRequest request = DeleteGroupRequest.builder() - .identityStoreId(identitystoreId) - .groupId(groupId) - .build(); + .identityStoreId(identitystoreId) + .groupId(groupId) + .build(); DeleteGroupResponse response = identitystore.deleteGroup(request); diff --git a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DeleteGroupMembership.java b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DeleteGroupMembership.java index e9d68669e3a..4dd4a6c5875 100644 --- a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DeleteGroupMembership.java +++ b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DeleteGroupMembership.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DeleteGroupMembership.java demonstrates how to Delete a membership within a group given membershipId in AWS Identitystore.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Identitystore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.identitystore; @@ -18,7 +12,8 @@ // snippet-end:[Identitystore.java2.delete_group_membership.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,14 +24,14 @@ public class DeleteGroupMembership { public static void main(String... args) { final String usage = """ - Usage: - + Usage: + - Where: - identitystoreId - The id of the identitystore.\s - membershipId - The id of the user member of the group.\s + Where: + identitystoreId - The id of the identitystore.\s + membershipId - The id of the user member of the group.\s - """; + """; if (args.length != 2) { System.out.println(usage); @@ -51,12 +46,13 @@ public static void main(String... args) { identitystore.close(); } - public static String deleteGroupMembership(IdentitystoreClient identitystore, String identitystoreId, String membershipId) { + public static String deleteGroupMembership(IdentitystoreClient identitystore, String identitystoreId, + String membershipId) { try { DeleteGroupMembershipRequest request = DeleteGroupMembershipRequest.builder() - .identityStoreId(identitystoreId) - .membershipId(membershipId) - .build(); + .identityStoreId(identitystoreId) + .membershipId(membershipId) + .build(); DeleteGroupMembershipResponse response = identitystore.deleteGroupMembership(request); return membershipId; diff --git a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DeleteUser.java b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DeleteUser.java index 187e0ad1e2d..9c3bee3d9ad 100644 --- a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DeleteUser.java +++ b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DeleteUser.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DeleteUser.java demonstrates how to delete a user within an AWS Identitystore given UserId.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Identitystore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.identitystore; @@ -18,7 +12,8 @@ // snippet-end:[Identitystore.java2.delete_user.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,13 +24,13 @@ public class DeleteUser { public static void main(String... args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - identitystoreId - The id of the identitystore.\s - userId - The id of the user to delete.\s - """; + Where: + identitystoreId - The id of the identitystore.\s + userId - The id of the user to delete.\s + """; if (args.length != 2) { System.out.println(usage); @@ -53,9 +48,9 @@ public static String deleteUser(IdentitystoreClient identitystore, String identi try { DeleteUserRequest request = DeleteUserRequest.builder() - .identityStoreId(identitystoreId) - .userId(userId) - .build(); + .identityStoreId(identitystoreId) + .userId(userId) + .build(); DeleteUserResponse response = identitystore.deleteUser(request); @@ -69,4 +64,4 @@ public static String deleteUser(IdentitystoreClient identitystore, String identi return ""; } } - // snippet-end:[identitystore.java2.delete_user.main] +// snippet-end:[identitystore.java2.delete_user.main] diff --git a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DescribeGroup.java b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DescribeGroup.java index 6c39b7e611c..6cc7e142575 100644 --- a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DescribeGroup.java +++ b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DescribeGroup.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeGroup.java demonstrates how to retrieves the group metadata and attributes from groupId in an AWS Identitystore.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Identitystore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.identitystore; @@ -18,7 +12,8 @@ // snippet-end:[Identitystore.java2.describe_group.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,14 +25,14 @@ public static void main(String... args) { final String usage = """ - Usage: - + Usage: + - Where: - identitystoreId - The id of the identitystore.\s - groupId - The id of the group.\s + Where: + identitystoreId - The id of the identitystore.\s + groupId - The id of the group.\s - """; + """; if (args.length != 2) { System.out.println(usage); @@ -56,9 +51,9 @@ public static String describeGroup(IdentitystoreClient identitystore, String ide try { DescribeGroupRequest request = DescribeGroupRequest.builder() - .identityStoreId(identitystoreId) - .groupId(groupId) - .build(); + .identityStoreId(identitystoreId) + .groupId(groupId) + .build(); DescribeGroupResponse response = identitystore.describeGroup(request); return response.displayName() + " " + response.description(); diff --git a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DescribeGroupMembership.java b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DescribeGroupMembership.java index 787cf94021d..3e8359235e8 100644 --- a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DescribeGroupMembership.java +++ b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DescribeGroupMembership.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeGroupMembership.java demonstrates how to retrieves membership metadata and attributes from membershipId in an AWS Identitystore.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Identitystore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.identitystore; @@ -17,9 +11,9 @@ import software.amazon.awssdk.services.identitystore.model.DescribeGroupMembershipResponse; // snippet-end:[Identitystore.java2.describe_group_membership.import] - /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,13 +25,13 @@ public static void main(String... args) { final String usage = """ - Usage: - + Usage: + - Where: - identitystoreId - The id of the identitystore.\s - membershipId - The id of the member of a group.\s - """; + Where: + identitystoreId - The id of the identitystore.\s + membershipId - The id of the member of a group.\s + """; if (args.length != 2) { System.out.println(usage); @@ -52,12 +46,13 @@ public static void main(String... args) { identitystore.close(); } - public static String describeGroupMembershipId(IdentitystoreClient identitystore, String identitystoreId, String membershipId) { + public static String describeGroupMembershipId(IdentitystoreClient identitystore, String identitystoreId, + String membershipId) { try { DescribeGroupMembershipRequest request = DescribeGroupMembershipRequest.builder() - .identityStoreId(identitystoreId) - .membershipId(membershipId) - .build(); + .identityStoreId(identitystoreId) + .membershipId(membershipId) + .build(); DescribeGroupMembershipResponse response = identitystore.describeGroupMembership(request); return response.groupId() + " " + response.memberId(); @@ -71,4 +66,3 @@ public static String describeGroupMembershipId(IdentitystoreClient identitystore } } // snippet-end:[identitystore.java2.describe_group_membership.main] - diff --git a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DescribeUser.java b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DescribeUser.java index 9f27a7eaa8b..3d66994929d 100644 --- a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DescribeUser.java +++ b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/DescribeUser.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeUser.java demonstrates how to retrieves the user metadata and attributes from the userId in an AWS Identitystore.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Identitystore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.identitystore; @@ -17,9 +11,9 @@ import software.amazon.awssdk.services.identitystore.model.DescribeUserResponse; // snippet-end:[Identitystore.java2.describe_user.import] - /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,14 +24,14 @@ public class DescribeUser { public static void main(String... args) { final String usage = """ - Usage: - + Usage: + - Where: - identitystoreId - The id of the identitystore.\s - userid - The id of the user.\s + Where: + identitystoreId - The id of the identitystore.\s + userid - The id of the user.\s - """; + """; if (args.length != 2) { System.out.println(usage); @@ -55,9 +49,9 @@ public static String describeUser(IdentitystoreClient identitystore, String iden try { DescribeUserRequest request = DescribeUserRequest.builder() - .identityStoreId(identitystoreID) - .userId(userId) - .build(); + .identityStoreId(identitystoreID) + .userId(userId) + .build(); DescribeUserResponse response = identitystore.describeUser(request); return response.userId() + " " + response.displayName(); diff --git a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/GetGroupId.java b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/GetGroupId.java index 5102c63a79c..49722f59a96 100644 --- a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/GetGroupId.java +++ b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/GetGroupId.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[GetGroupId.java demonstrates how to retrieve the groupid based on other unique keys from AWS Identitystore.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Identitystore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.identitystore; @@ -20,9 +14,9 @@ import software.amazon.awssdk.core.document.Document; // snippet-end:[Identitystore.java2.get_group_id.import] - /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -33,14 +27,14 @@ public class GetGroupId { public static void main(String... args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - identitystoreId - The id of the identitystore.\s - groupAttributeName - The name of the unique attribute of the group.\s - groupAttributeValue - The value of the specified group attribute.\s - """; + Where: + identitystoreId - The id of the identitystore.\s + groupAttributeName - The name of the unique attribute of the group.\s + groupAttributeValue - The value of the specified group attribute.\s + """; if (args.length != 3) { System.out.println(usage); @@ -55,24 +49,25 @@ public static void main(String... args) { identitystore.close(); } - public static String getGroupId(IdentitystoreClient identitystore, String identitystoreId, String groupAttributeName, String groupAttributeValue) { + public static String getGroupId(IdentitystoreClient identitystore, String identitystoreId, + String groupAttributeName, String groupAttributeValue) { try { String attributePath = groupAttributeName; Document attributeValue = Document.fromString(groupAttributeValue); UniqueAttribute uniqueAttribute = UniqueAttribute.builder() - .attributePath(attributePath) - .attributeValue(attributeValue) - .build(); + .attributePath(attributePath) + .attributeValue(attributeValue) + .build(); AlternateIdentifier alternateIdentifier = AlternateIdentifier.builder() - .uniqueAttribute(uniqueAttribute) - .build(); + .uniqueAttribute(uniqueAttribute) + .build(); GetGroupIdRequest request = GetGroupIdRequest.builder() - .identityStoreId(identitystoreId) - .alternateIdentifier(alternateIdentifier) - .build(); + .identityStoreId(identitystoreId) + .alternateIdentifier(alternateIdentifier) + .build(); GetGroupIdResponse response = identitystore.getGroupId(request); return response.groupId(); diff --git a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/GetGroupMembershipId.java b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/GetGroupMembershipId.java index ae234f164db..7452836c2f4 100644 --- a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/GetGroupMembershipId.java +++ b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/GetGroupMembershipId.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[GetGroupMembershipId.java demonstrates how to retrieve the user membership from a group in AWS Identitystore.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Identitystore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.identitystore; @@ -19,7 +13,8 @@ // snippet-end:[Identitystore.java2.get_group_membershipid.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,12 +25,12 @@ public class GetGroupMembershipId { public static void main(String... args) { final String usage = "\n" + - "Usage:\n" + - " \n\n" + - "Where:\n" + - " identitystoreId - The id of the identitystore. \n" + - " groupId - The id of the group. \n" + - " userId - The id of the user. \n\n"; + "Usage:\n" + + " \n\n" + + "Where:\n" + + " identitystoreId - The id of the identitystore. \n" + + " groupId - The id of the group. \n" + + " userId - The id of the user. \n\n"; if (args.length != 3) { System.out.println(usage); @@ -51,16 +46,17 @@ public static void main(String... args) { identitystore.close(); } - public static String getGroupMembershipId(IdentitystoreClient identitystore, String identitystoreId, String groupId, String userId) { + public static String getGroupMembershipId(IdentitystoreClient identitystore, String identitystoreId, String groupId, + String userId) { try { MemberId memberId = MemberId.builder() - .userId(userId) - .build(); + .userId(userId) + .build(); GetGroupMembershipIdRequest request = GetGroupMembershipIdRequest.builder() - .identityStoreId(identitystoreId) - .groupId(groupId) - .memberId(memberId) - .build(); + .identityStoreId(identitystoreId) + .groupId(groupId) + .memberId(memberId) + .build(); GetGroupMembershipIdResponse response = identitystore.getGroupMembershipId(request); return response.membershipId(); diff --git a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/GetUserId.java b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/GetUserId.java index 7a7a19fc283..8ee5e35e3ed 100644 --- a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/GetUserId.java +++ b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/GetUserId.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[GetUserId.java demonstrates how to retrieve the userid based on other unique keys from AWS Identitystore.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Identitystore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.identitystore; @@ -21,7 +15,8 @@ // snippet-end:[Identitystore.java2.get_userid.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,15 +27,15 @@ public static void main(String... args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - identitystoreId - The id of the identitystore.\s - userAttributeName - The name of the unique attribute of the user.\s - userAttributeValue - The value of the specified user attribute.\s + Where: + identitystoreId - The id of the identitystore.\s + userAttributeName - The name of the unique attribute of the user.\s + userAttributeValue - The value of the specified user attribute.\s - """; + """; if (args.length != 3) { System.out.println(usage); @@ -56,24 +51,25 @@ public static void main(String... args) { identitystore.close(); } - public static String getUserId(IdentitystoreClient identitystore, String identitystoreId, String userAttributeName, String userAttributeValue) { + public static String getUserId(IdentitystoreClient identitystore, String identitystoreId, String userAttributeName, + String userAttributeValue) { try { String attributePath = userAttributeName; Document attributeValue = Document.fromString(userAttributeValue); UniqueAttribute uniqueAttribute = UniqueAttribute.builder() - .attributePath(attributePath) - .attributeValue(attributeValue) - .build(); + .attributePath(attributePath) + .attributeValue(attributeValue) + .build(); AlternateIdentifier alternateIdentifier = AlternateIdentifier.builder() - .uniqueAttribute(uniqueAttribute) - .build(); + .uniqueAttribute(uniqueAttribute) + .build(); GetUserIdRequest request = GetUserIdRequest.builder() - .identityStoreId(identitystoreId) - .alternateIdentifier(alternateIdentifier) - .build(); + .identityStoreId(identitystoreId) + .alternateIdentifier(alternateIdentifier) + .build(); GetUserIdResponse response = identitystore.getUserId(request); return response.userId(); diff --git a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/IsMemberInGroups.java b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/IsMemberInGroups.java index 4ad75ca8549..1916c42f6d2 100644 --- a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/IsMemberInGroups.java +++ b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/IsMemberInGroups.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[IsMemberInGroups.java checks the user's membership in all requested groups and returns if the member exists in all queried groups in a AWS Identitystore.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Identitystore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.identitystore; @@ -22,7 +16,8 @@ // snippet-end:[Identitystore.java2.is_member_in_groups.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -35,15 +30,15 @@ public static void main(String... args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - identitystoreId - The id of the identitystore.\s - userId - The id of the user.\s - list of groupIds - The list of groupids of one or more groups.\s + Where: + identitystoreId - The id of the identitystore.\s + userId - The id of the user.\s + list of groupIds - The list of groupids of one or more groups.\s - """; + """; if (args.length < 3) { System.out.println(usage); @@ -63,22 +58,24 @@ public static void main(String... args) { identitystore.close(); } - public static String isMemberInGroups(IdentitystoreClient identitystore, String identitystoreId, String userId, List groupIdList) { + public static String isMemberInGroups(IdentitystoreClient identitystore, String identitystoreId, String userId, + List groupIdList) { try { MemberId memberId = MemberId.builder() - .userId(userId) - .build(); + .userId(userId) + .build(); IsMemberInGroupsRequest request = IsMemberInGroupsRequest.builder() - .identityStoreId(identitystoreId) - .memberId(memberId) - .groupIds(groupIdList) - .build(); + .identityStoreId(identitystoreId) + .memberId(memberId) + .groupIds(groupIdList) + .build(); IsMemberInGroupsResponse response = identitystore.isMemberInGroups(request); System.out.format("Results: \n"); for (GroupMembershipExistenceResult result : response.results()) { - System.out.format("GroupId: %s, UserId: %s, MembershipExists: %s\n", result.groupId(), result.memberId().userId(), result.membershipExists()); + System.out.format("GroupId: %s, UserId: %s, MembershipExists: %s\n", result.groupId(), + result.memberId().userId(), result.membershipExists()); } return "Done"; diff --git a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/ListGroupMemberships.java b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/ListGroupMemberships.java index 73bd8915ea4..84f6eff0458 100644 --- a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/ListGroupMemberships.java +++ b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/ListGroupMemberships.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[ListGroupMemberships.java demonstrates how to retrieve the list of users attached to a group in AWS Identitystore.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Identitystore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.identitystore; @@ -19,25 +13,25 @@ // snippet-end:[Identitystore.java2.list_group_memberships.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ - public class ListGroupMemberships { public static void main(String... args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - identitystoreId - The id of the identitystore.\s - groupId - The id of the group.\s - """; + Where: + identitystoreId - The id of the identitystore.\s + groupId - The id of the group.\s + """; if (args.length != 2) { System.out.println(usage); @@ -63,22 +57,23 @@ public static int listGroupMemberships(IdentitystoreClient identitystore, String ListGroupMembershipsResponse response; if (nextToken == null) { ListGroupMembershipsRequest request = ListGroupMembershipsRequest.builder() - .identityStoreId(identitystoreId) - .groupId(groupId) - .build(); + .identityStoreId(identitystoreId) + .groupId(groupId) + .build(); response = identitystore.listGroupMemberships(request); } else { ListGroupMembershipsRequest request = ListGroupMembershipsRequest.builder() - .nextToken(nextToken) - .identityStoreId(identitystoreId) - .groupId(groupId) - .build(); + .nextToken(nextToken) + .identityStoreId(identitystoreId) + .groupId(groupId) + .build(); response = identitystore.listGroupMemberships(request); } for (GroupMembership groupmembership : response.groupMemberships()) { count++; - System.out.format("GroupId: %s, UserId: %s, MembershipId: %s\n", groupmembership.groupId(), groupmembership.memberId().userId(), groupmembership.membershipId()); + System.out.format("GroupId: %s, UserId: %s, MembershipId: %s\n", groupmembership.groupId(), + groupmembership.memberId().userId(), groupmembership.membershipId()); } nextToken = response.nextToken(); @@ -96,4 +91,4 @@ public static int listGroupMemberships(IdentitystoreClient identitystore, String return 0; } } - // snippet-end:[identitystore.java2.list_group_memberships.main] +// snippet-end:[identitystore.java2.list_group_memberships.main] diff --git a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/ListGroupMembershipsForMember.java b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/ListGroupMembershipsForMember.java index d08d90f19d4..280e6dcb261 100644 --- a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/ListGroupMembershipsForMember.java +++ b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/ListGroupMembershipsForMember.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[ListGroupMembershipsForMember.java demonstrates how to get the list of groups that a user is attached to in AWS Identitystore.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Identitystore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.identitystore; @@ -20,7 +14,8 @@ // snippet-end:[Identitystore.java2.list_group_memberships_For_Member.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,15 +26,14 @@ public class ListGroupMembershipsForMember { public static void main(String... args) { final String usage = """ - Usage: - \s - - Where: - identitystoreId - The id of the identitystore.\s - userId - The id of the user.\s + Usage: + \s - """; + Where: + identitystoreId - The id of the identitystore.\s + userId - The id of the user.\s + """; if (args.length != 2) { System.out.println(usage); @@ -54,36 +48,38 @@ public static void main(String... args) { identitystore.close(); } - public static int listGroupMembershipsForMember(IdentitystoreClient identitystore, String identitystoreId, String userId) { + public static int listGroupMembershipsForMember(IdentitystoreClient identitystore, String identitystoreId, + String userId) { try { boolean done = false; int count = 0; String nextToken = null; MemberId memberId = MemberId.builder() - .userId(userId) - .build(); + .userId(userId) + .build(); while (!done) { ListGroupMembershipsForMemberResponse response; if (nextToken == null) { ListGroupMembershipsForMemberRequest request = ListGroupMembershipsForMemberRequest.builder() - .identityStoreId(identitystoreId) - .memberId(memberId) - .build(); + .identityStoreId(identitystoreId) + .memberId(memberId) + .build(); response = identitystore.listGroupMembershipsForMember(request); } else { ListGroupMembershipsForMemberRequest request = ListGroupMembershipsForMemberRequest.builder() - .nextToken(nextToken) - .identityStoreId(identitystoreId) - .memberId(memberId) - .build(); + .nextToken(nextToken) + .identityStoreId(identitystoreId) + .memberId(memberId) + .build(); response = identitystore.listGroupMembershipsForMember(request); } for (GroupMembership groupMemberShip : response.groupMemberships()) { count++; - System.out.format("GroupId: %s, UserId: %s, MembershipId: %s\n", groupMemberShip.groupId(), groupMemberShip.memberId().userId(), groupMemberShip.membershipId()); + System.out.format("GroupId: %s, UserId: %s, MembershipId: %s\n", groupMemberShip.groupId(), + groupMemberShip.memberId().userId(), groupMemberShip.membershipId()); } nextToken = response.nextToken(); @@ -101,4 +97,4 @@ public static int listGroupMembershipsForMember(IdentitystoreClient identitystor return 0; } } - // snippet-end:[identitystore.java2.list_group_memberships_For_Member.main] +// snippet-end:[identitystore.java2.list_group_memberships_For_Member.main] diff --git a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/ListGroups.java b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/ListGroups.java index d442978fdc9..42273ff6837 100644 --- a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/ListGroups.java +++ b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/ListGroups.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[ListGroups.java demonstrates how to get list of groups in AWS Identitystore.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Identitystore] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.identitystore; // snippet-start:[identitystore.java2.list_groups.main] @@ -18,7 +13,8 @@ // snippet-end:[Identitystore.java2.list_groups.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,11 +25,10 @@ public class ListGroups { public static void main(String... args) { final String usage = "\n" + - "Usage:\n" + - " \n\n" + - "Where:\n" + - " identitystoreId - The id of the identitystore. \n\n"; - + "Usage:\n" + + " \n\n" + + "Where:\n" + + " identitystoreId - The id of the identitystore. \n\n"; if (args.length != 1) { System.out.println(usage); @@ -61,13 +56,15 @@ public static int listGroups(IdentitystoreClient identitystore, String identitys ListGroupsRequest request = ListGroupsRequest.builder().identityStoreId(identitystoreId).build(); response = identitystore.listGroups(request); } else { - ListGroupsRequest request = ListGroupsRequest.builder().nextToken(nextToken).identityStoreId(identitystoreId).build(); + ListGroupsRequest request = ListGroupsRequest.builder().nextToken(nextToken) + .identityStoreId(identitystoreId).build(); response = identitystore.listGroups(request); } for (Group group : response.groups()) { count++; - System.out.format("GroupName: %s, GroupId: %s, GroupDescription: %s\n", group.displayName(), group.groupId(), group.description()); + System.out.format("GroupName: %s, GroupId: %s, GroupDescription: %s\n", group.displayName(), + group.groupId(), group.description()); } nextToken = response.nextToken(); diff --git a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/ListUsers.java b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/ListUsers.java index a9898cb6476..92589f6b268 100644 --- a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/ListUsers.java +++ b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/ListUsers.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[ListUsers.java demonstrates how to get list of users in AWS Identitystore.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Identitystore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.identitystore; @@ -19,7 +13,8 @@ // snippet-end:[Identitystore.java2.list_users.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,14 +25,13 @@ public class ListUsers { public static void main(String... args) { final String usage = """ - Usage: - \s - - Where: - identitystoreId - The id of the identitystore.\s + Usage: + \s - """; + Where: + identitystoreId - The id of the identitystore.\s + """; if (args.length != 1) { System.out.println(usage); @@ -64,7 +58,8 @@ public static int listUsers(IdentitystoreClient identitystore, String identityst ListUsersRequest request = ListUsersRequest.builder().identityStoreId(identitystoreId).build(); response = identitystore.listUsers(request); } else { - ListUsersRequest request = ListUsersRequest.builder().nextToken(nextToken).identityStoreId(identitystoreId).build(); + ListUsersRequest request = ListUsersRequest.builder().nextToken(nextToken) + .identityStoreId(identitystoreId).build(); response = identitystore.listUsers(request); } @@ -87,4 +82,4 @@ public static int listUsers(IdentitystoreClient identitystore, String identityst return 0; } } - // snippet-end:[identitystore.java2.list_users.main] \ No newline at end of file +// snippet-end:[identitystore.java2.list_users.main] \ No newline at end of file diff --git a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/UpdateGroup.java b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/UpdateGroup.java index fc7d05a9f81..ff3b7b37464 100644 --- a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/UpdateGroup.java +++ b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/UpdateGroup.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[UpdateGroup.java demonstrates how to update the group metadata and attributes in AWS Identitystore.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Identitystore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.identitystore; @@ -20,7 +14,8 @@ // snippet-end:[Identitystore.java2.update_group.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,16 +26,16 @@ public static void main(String... args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - identitystoreId - The id of the identitystore.\s - groupId - The id of the group.\s - groupAttributeName - The name of the unique attribute of the group.\s - groupAttributeValue - The value of the specified group attribute.\s + Where: + identitystoreId - The id of the identitystore.\s + groupId - The id of the group.\s + groupAttributeName - The name of the unique attribute of the group.\s + groupAttributeValue - The value of the specified group attribute.\s - """; + """; if (args.length != 4) { System.out.println(usage); @@ -57,25 +52,27 @@ public static void main(String... args) { identitystore.close(); } - public static String updateGroup(IdentitystoreClient identitystore, String identitystoreId, String groupId, String groupAttributePath, String groupAttributeValue) { + public static String updateGroup(IdentitystoreClient identitystore, String identitystoreId, String groupId, + String groupAttributePath, String groupAttributeValue) { try { String attributePath = groupAttributePath; Document attributeValue = Document.fromString(groupAttributeValue); AttributeOperation attributeOperation = AttributeOperation.builder() - .attributePath(attributePath) - .attributeValue(attributeValue) - .build(); + .attributePath(attributePath) + .attributeValue(attributeValue) + .build(); UpdateGroupRequest request = UpdateGroupRequest.builder() - .identityStoreId(identitystoreId) - .groupId(groupId) - .operations(attributeOperation) - .build(); + .identityStoreId(identitystoreId) + .groupId(groupId) + .operations(attributeOperation) + .build(); UpdateGroupResponse response = identitystore.updateGroup(request); - System.out.format("Group Field Name is updated with new value %s for groupId %s\n", attributePath, attributeValue, groupId); + System.out.format("Group Field Name is updated with new value %s for groupId %s\n", attributePath, + attributeValue, groupId); return "Updated"; } catch (IdentitystoreException e) { diff --git a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/UpdateUser.java b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/UpdateUser.java index cbfb63626ac..e92e6f81b43 100644 --- a/javav2/example_code/identitystore/src/main/java/com/example/identitystore/UpdateUser.java +++ b/javav2/example_code/identitystore/src/main/java/com/example/identitystore/UpdateUser.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[UpdateUser.java demonstrates how to update the user metadata and attributes in AWS Identitystore] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Identitystore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.identitystore; @@ -20,7 +14,8 @@ // snippet-end:[Identitystore.java2.update_user.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,15 +25,15 @@ public class UpdateUser { public static void main(String... args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - identitystoreId - The id of the identitystore.\s - userId - The id of the user.\s - userAttributeName - The name of the unique attribute of the user.\s - userAttributeValue - The value of the specified user attribute.\s - """; + Where: + identitystoreId - The id of the identitystore.\s + userId - The id of the user.\s + userAttributeName - The name of the unique attribute of the user.\s + userAttributeValue - The value of the specified user attribute.\s + """; if (args.length != 4) { System.out.println(usage); @@ -55,24 +50,26 @@ public static void main(String... args) { identitystore.close(); } - public static String updateUser(IdentitystoreClient identitystore, String identitystoreId, String userId, String userAttributePath, String userAttributeValue) { + public static String updateUser(IdentitystoreClient identitystore, String identitystoreId, String userId, + String userAttributePath, String userAttributeValue) { try { String attributePath = userAttributePath; Document attributeValue = Document.fromString(userAttributeValue); AttributeOperation attributeOperation = AttributeOperation.builder() - .attributePath(attributePath) - .attributeValue(attributeValue) - .build(); + .attributePath(attributePath) + .attributeValue(attributeValue) + .build(); UpdateUserRequest request = UpdateUserRequest.builder() - .identityStoreId(identitystoreId) - .userId(userId) - .operations(attributeOperation) - .build(); + .identityStoreId(identitystoreId) + .userId(userId) + .operations(attributeOperation) + .build(); identitystore.updateUser(request); - System.out.format("User Field Name %s is updated with new value %s for userId %s\n", attributePath, attributeValue, userId); + System.out.format("User Field Name %s is updated with new value %s for userId %s\n", attributePath, + attributeValue, userId); return "Updated"; } catch (IdentitystoreException e) { @@ -83,4 +80,4 @@ public static String updateUser(IdentitystoreClient identitystore, String identi return ""; } } - // snippet-end:[identitystore.java2.update_user.main] +// snippet-end:[identitystore.java2.update_user.main] diff --git a/javav2/example_code/identitystore/src/test/java/IdentitystoreServiceTest.java b/javav2/example_code/identitystore/src/test/java/IdentitystoreServiceTest.java index 5f7172e8ae2..bbb0c3f3d0b 100644 --- a/javav2/example_code/identitystore/src/test/java/IdentitystoreServiceTest.java +++ b/javav2/example_code/identitystore/src/test/java/IdentitystoreServiceTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.identitystore.*; import org.junit.jupiter.api.*; @@ -12,7 +10,6 @@ import software.amazon.awssdk.services.identitystore.model.IdentitystoreException; import software.amazon.awssdk.services.identitystore.model.Group; - import java.io.*; import java.util.*; import java.util.concurrent.TimeUnit; @@ -22,23 +19,23 @@ public class IdentitystoreServiceTest { private static IdentitystoreClient identitystore; - private static String identitystoreId=""; - private static String groupName=""; - private static String groupDesc=""; - private static String groupId=""; - private static String userName=""; - private static String givenName=""; - private static String familyName=""; - private static String userId=""; - private static String membershipId=""; + private static String identitystoreId = ""; + private static String groupName = ""; + private static String groupDesc = ""; + private static String groupId = ""; + private static String userName = ""; + private static String givenName = ""; + private static String familyName = ""; + private static String userId = ""; + private static String membershipId = ""; @BeforeAll public static void setUp() throws IOException { - identitystore = IdentitystoreClient.builder() - .build(); - + identitystore = IdentitystoreClient.builder() + .build(); - try (InputStream input = IdentitystoreServiceTest.class.getClassLoader().getResourceAsStream("config.properties")) { + try (InputStream input = IdentitystoreServiceTest.class.getClassLoader() + .getResourceAsStream("config.properties")) { Properties prop = new Properties(); prop.load(input); @@ -85,7 +82,7 @@ public void GetGroupId() { assertTrue(!groupId.isEmpty()); System.out.println("\n Test 3 passed"); } - + @Test @Order(4) public void DescribeGroup() { @@ -97,7 +94,8 @@ public void DescribeGroup() { @Test @Order(5) public void UpdateGroup() { - String result5 = UpdateGroup.updateGroup(identitystore, identitystoreId, groupId, "Description", "TestingUpdateAPI"); + String result5 = UpdateGroup.updateGroup(identitystore, identitystoreId, groupId, "Description", + "TestingUpdateAPI"); assertTrue(!result5.isEmpty()); System.out.println("\n Test 5 passed"); } @@ -106,7 +104,7 @@ public void UpdateGroup() { @Order(6) public void ListGroups() { int result6 = ListGroups.listGroups(identitystore, identitystoreId); - assertTrue(result6>=0); + assertTrue(result6 >= 0); System.out.println("\n Test 6 passed"); } @@ -137,7 +135,8 @@ public void DescribeUser() { @Test @Order(10) public void UpdateUser() { - String result10 = UpdateUser.updateUser(identitystore, identitystoreId, userId, "displayName", "TestingUpdateAPI"); + String result10 = UpdateUser.updateUser(identitystore, identitystoreId, userId, "displayName", + "TestingUpdateAPI"); assertTrue(!result10.isEmpty()); System.out.println("\n Test 10 passed"); } @@ -146,7 +145,7 @@ public void UpdateUser() { @Order(11) public void ListUsers() { int result11 = ListUsers.listUsers(identitystore, identitystoreId); - assertTrue(result11>=0); + assertTrue(result11 >= 0); System.out.println("\n Test 11 passed"); } @@ -169,7 +168,8 @@ public void GetGroupMembershipId() { @Test @Order(14) public void DescribeGroupMembership() { - String result14 = DescribeGroupMembership.describeGroupMembershipId(identitystore, identitystoreId, membershipId); + String result14 = DescribeGroupMembership.describeGroupMembershipId(identitystore, identitystoreId, + membershipId); assertTrue(!result14.isEmpty()); System.out.println("\n Test 14 passed"); } @@ -188,15 +188,16 @@ public void IsMemberInGroups() { @Order(16) public void ListGroupMemberships() { int result16 = ListGroupMemberships.listGroupMemberships(identitystore, identitystoreId, groupId); - assertTrue(result16>=0); + assertTrue(result16 >= 0); System.out.println("\n Test 16 passed"); } @Test @Order(17) public void ListGroupMembershipsForMember() { - int result17 = ListGroupMembershipsForMember.listGroupMembershipsForMember(identitystore, identitystoreId, userId); - assertTrue(result17>=0); + int result17 = ListGroupMembershipsForMember.listGroupMembershipsForMember(identitystore, identitystoreId, + userId); + assertTrue(result17 >= 0); System.out.println("\n Test 17 passed"); } diff --git a/javav2/example_code/kendra/src/main/java/com/example/kendra/CreateIndexAndDataSourceExample.java b/javav2/example_code/kendra/src/main/java/com/example/kendra/CreateIndexAndDataSourceExample.java index f0e11402242..01b629c678c 100644 --- a/javav2/example_code/kendra/src/main/java/com/example/kendra/CreateIndexAndDataSourceExample.java +++ b/javav2/example_code/kendra/src/main/java/com/example/kendra/CreateIndexAndDataSourceExample.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[CreateIndexAndDataSourceExample.java demonstrates how to create an Amazon Kendra index and data source.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon Kendra] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kendra; @@ -32,7 +27,8 @@ // snippet-end:[kendra.java2.index.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -43,18 +39,18 @@ public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - indexDescription - A description for the index. - indexName - The name for the new index. - indexRoleArn - An Identity and Access Management (IAM) role that gives Amazon Kendra permissions to access your Amazon CloudWatch logs and metrics. - dataSourceRoleArn - The ARN of am IAM role with permission to access the data source. - dataSourceName - The name for the new data source. - dataSourceDescription - A description for the data source. - s3BucketName - An Amazon S3 bucket used as your data source. - """; + Where: + indexDescription - A description for the index. + indexName - The name for the new index. + indexRoleArn - An Identity and Access Management (IAM) role that gives Amazon Kendra permissions to access your Amazon CloudWatch logs and metrics. + dataSourceRoleArn - The ARN of am IAM role with permission to access the data source. + dataSourceName - The name for the new data source. + dataSourceDescription - A description for the data source. + s3BucketName - An Amazon S3 bucket used as your data source. + """; if (args.length != 7) { System.out.println(usage); @@ -70,32 +66,34 @@ public static void main(String[] args) { String s3BucketName = args[6]; KendraClient kendra = KendraClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); String indexId = createIndex(kendra, indexDescription, indexName, indexRoleArn); - String dataSourceId = CreateIndexAndDataSourceExample.createDataSource(kendra, s3BucketName, dataSourceName, dataSourceDescription, indexId, dataSourceRoleArn); + String dataSourceId = CreateIndexAndDataSourceExample.createDataSource(kendra, s3BucketName, dataSourceName, + dataSourceDescription, indexId, dataSourceRoleArn); startDataSource(kendra, indexId, dataSourceId); } - public static String createIndex(KendraClient kendra, String indexDescription, String indexName, String indexRoleArn) { + public static String createIndex(KendraClient kendra, String indexDescription, String indexName, + String indexRoleArn) { try { - System.out.println("Creating an index named " +indexName); + System.out.println("Creating an index named " + indexName); CreateIndexRequest createIndexRequest = CreateIndexRequest.builder() - .description(indexDescription) - .name(indexName) - .roleArn(indexRoleArn) - .build(); + .description(indexDescription) + .name(indexName) + .roleArn(indexRoleArn) + .build(); CreateIndexResponse createIndexResponse = kendra.createIndex(createIndexRequest); - System.out.println("Index response " +createIndexResponse); + System.out.println("Index response " + createIndexResponse); String indexId = createIndexResponse.id(); - System.out.println("Waiting until the index with index ID "+indexId +" is created."); + System.out.println("Waiting until the index with index ID " + indexId + " is created."); while (true) { DescribeIndexRequest describeIndexRequest = DescribeIndexRequest.builder().id(indexId).build(); DescribeIndexResponse describeIndexResponse = kendra.describeIndex(describeIndexRequest); IndexStatus status = describeIndexResponse.status(); - System.out.println("Status is " +status); + System.out.println("Status is " + status); if (status != IndexStatus.CREATING) { break; } @@ -103,76 +101,80 @@ public static String createIndex(KendraClient kendra, String indexDescription, S TimeUnit.SECONDS.sleep(60); } - return indexId ; + return indexId; } catch (KendraException | InterruptedException e) { System.err.println(e.getMessage()); System.exit(1); } - return "" ; - } + return ""; + } // snippet-end:[kendra.java2.index.main] // snippet-start:[kendra.java2.datasource.main] - public static String createDataSource(KendraClient kendra, String s3BucketName, String dataSourceName, String dataSourceDescription, String indexId, String dataSourceRoleArn) { - - System.out.println("Creating an S3 data source"); - try { - CreateDataSourceRequest createDataSourceRequest = CreateDataSourceRequest - .builder() - .indexId(indexId) - .name(dataSourceName) - .description(dataSourceDescription) - .roleArn(dataSourceRoleArn) - .type(DataSourceType.S3) - .configuration(DataSourceConfiguration.builder() - .s3Configuration(S3DataSourceConfiguration.builder() - .bucketName(s3BucketName) - .build() - ).build() - ).build(); - - CreateDataSourceResponse createDataSourceResponse = kendra.createDataSource(createDataSourceRequest); - System.out.println("Response of creating data source " +createDataSourceResponse); - String dataSourceId = createDataSourceResponse.id(); - System.out.println("Waiting for Kendra to create the data source " +dataSourceId); - DescribeDataSourceRequest describeDataSourceRequest = DescribeDataSourceRequest.builder() - .indexId(indexId) - .id(dataSourceId) - .build(); - - while (true) { - DescribeDataSourceResponse describeDataSourceResponse = kendra.describeDataSource(describeDataSourceRequest); - DataSourceStatus status = describeDataSourceResponse.status(); - System.out.println("Creating data source. Status is " +status); - if (status != DataSourceStatus.CREATING) { - break; - } + public static String createDataSource(KendraClient kendra, String s3BucketName, String dataSourceName, + String dataSourceDescription, String indexId, String dataSourceRoleArn) { + + System.out.println("Creating an S3 data source"); + try { + CreateDataSourceRequest createDataSourceRequest = CreateDataSourceRequest + .builder() + .indexId(indexId) + .name(dataSourceName) + .description(dataSourceDescription) + .roleArn(dataSourceRoleArn) + .type(DataSourceType.S3) + .configuration(DataSourceConfiguration.builder() + .s3Configuration(S3DataSourceConfiguration.builder() + .bucketName(s3BucketName) + .build()) + .build()) + .build(); + + CreateDataSourceResponse createDataSourceResponse = kendra.createDataSource(createDataSourceRequest); + System.out.println("Response of creating data source " + createDataSourceResponse); + String dataSourceId = createDataSourceResponse.id(); + System.out.println("Waiting for Kendra to create the data source " + dataSourceId); + DescribeDataSourceRequest describeDataSourceRequest = DescribeDataSourceRequest.builder() + .indexId(indexId) + .id(dataSourceId) + .build(); + + while (true) { + DescribeDataSourceResponse describeDataSourceResponse = kendra + .describeDataSource(describeDataSourceRequest); + DataSourceStatus status = describeDataSourceResponse.status(); + System.out.println("Creating data source. Status is " + status); + if (status != DataSourceStatus.CREATING) { + break; + } TimeUnit.SECONDS.sleep(60); - } - - return dataSourceId; - } catch (KendraException | InterruptedException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - return "" ; + } + + return dataSourceId; + } catch (KendraException | InterruptedException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + return ""; } // snippet-end:[kendra.java2.datasource.main] // snippet-start:[kendra.java2.start.datasource.main] - public static void startDataSource (KendraClient kendra, String indexId, String dataSourceId) { - try{ - System.out.println("Synchronize the data source " +dataSourceId); + public static void startDataSource(KendraClient kendra, String indexId, String dataSourceId) { + try { + System.out.println("Synchronize the data source " + dataSourceId); StartDataSourceSyncJobRequest startDataSourceSyncJobRequest = StartDataSourceSyncJobRequest - .builder() - .indexId(indexId) - .id(dataSourceId) - .build(); - - StartDataSourceSyncJobResponse startDataSourceSyncJobResponse = kendra.startDataSourceSyncJob(startDataSourceSyncJobRequest); - System.out.println("Waiting for the data source to sync with the index "+indexId + " for execution ID " +startDataSourceSyncJobResponse.executionId()); + .builder() + .indexId(indexId) + .id(dataSourceId) + .build(); + + StartDataSourceSyncJobResponse startDataSourceSyncJobResponse = kendra + .startDataSourceSyncJob(startDataSourceSyncJobRequest); + System.out.println("Waiting for the data source to sync with the index " + indexId + " for execution ID " + + startDataSourceSyncJobResponse.executionId()); } catch (KendraException e) { System.err.println(e.getMessage()); diff --git a/javav2/example_code/kendra/src/main/java/com/example/kendra/DeleteDataSource.java b/javav2/example_code/kendra/src/main/java/com/example/kendra/DeleteDataSource.java index 3f3fd7c95e1..543d8541d23 100644 --- a/javav2/example_code/kendra/src/main/java/com/example/kendra/DeleteDataSource.java +++ b/javav2/example_code/kendra/src/main/java/com/example/kendra/DeleteDataSource.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DeleteDataSource.java demonstrates how to delete an Amazon Kendra data source.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon Kendra] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kendra; @@ -18,7 +12,8 @@ // snippet-end:[kendra.java2.delete.datasource.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,13 +23,13 @@ public class DeleteDataSource { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - dataSourceId - The id value of the data source. - indexId - The id value of the index. - """; + Where: + dataSourceId - The id value of the data source. + indexId - The id value of the index. + """; if (args.length != 2) { System.out.println(usage); @@ -44,17 +39,17 @@ public static void main(String[] args) { String dataSourceId = args[0]; String indexId = args[1]; KendraClient kendra = KendraClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); deleteSpecificDataSource(kendra, indexId, dataSourceId); } public static void deleteSpecificDataSource(KendraClient kendra, String indexId, String dataSourceId) { try { DeleteDataSourceRequest dataSourceRequest = DeleteDataSourceRequest.builder() - .id(dataSourceId) - .indexId(indexId) - .build(); + .id(dataSourceId) + .indexId(indexId) + .build(); kendra.deleteDataSource(dataSourceRequest); System.out.println(dataSourceId + " was successfully deleted."); diff --git a/javav2/example_code/kendra/src/main/java/com/example/kendra/DeleteIndex.java b/javav2/example_code/kendra/src/main/java/com/example/kendra/DeleteIndex.java index df402ba05c3..503fe62938c 100644 --- a/javav2/example_code/kendra/src/main/java/com/example/kendra/DeleteIndex.java +++ b/javav2/example_code/kendra/src/main/java/com/example/kendra/DeleteIndex.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DeleteIndex.java demonstrates how to delete an Amazon Kendra index.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon Kendra] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kendra; @@ -18,7 +12,8 @@ // snippet-end:[kendra.java2.delete.index.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,12 +24,12 @@ public class DeleteIndex { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - indexId - The id value of the index. - """; + Where: + indexId - The id value of the index. + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +38,8 @@ public static void main(String[] args) { String indexId = args[0]; KendraClient kendra = KendraClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); deleteSpecificIndex(kendra, indexId); } @@ -52,8 +47,8 @@ public static void main(String[] args) { public static void deleteSpecificIndex(KendraClient kendra, String indexId) { try { DeleteIndexRequest deleteIndexRequest = DeleteIndexRequest.builder() - .id(indexId) - .build(); + .id(indexId) + .build(); kendra.deleteIndex(deleteIndexRequest); System.out.println(indexId + " was successfully deleted."); diff --git a/javav2/example_code/kendra/src/main/java/com/example/kendra/ListDataSourceSyncJobs.java b/javav2/example_code/kendra/src/main/java/com/example/kendra/ListDataSourceSyncJobs.java index 72213bb2ece..299a10a5763 100644 --- a/javav2/example_code/kendra/src/main/java/com/example/kendra/ListDataSourceSyncJobs.java +++ b/javav2/example_code/kendra/src/main/java/com/example/kendra/ListDataSourceSyncJobs.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[ListDataSourceSyncJobs.java demonstrates how to get statistics about synchronizing Amazon Kendra with a data source.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon Kendra] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kendra; @@ -21,7 +15,8 @@ // snippet-end:[kendra.java2.list.sync.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,13 +27,13 @@ public class ListDataSourceSyncJobs { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - indexId - The id value of the index. - dataSourceId - The id value of the data source. - """; + Where: + indexId - The id value of the index. + dataSourceId - The id value of the data source. + """; if (args.length != 2) { System.out.println(usage); @@ -49,8 +44,8 @@ public static void main(String[] args) { String dataSourceId = args[1]; System.out.printf("Gets statistics about synchronizing Amazon Kendra with a data source %s%n", dataSourceId); KendraClient kendra = KendraClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); listSyncJobs(kendra, indexId, dataSourceId); } @@ -58,10 +53,10 @@ public static void main(String[] args) { public static void listSyncJobs(KendraClient kendra, String indexId, String dataSourceId) { try { ListDataSourceSyncJobsRequest jobsRequest = ListDataSourceSyncJobsRequest.builder() - .indexId(indexId) - .maxResults(10) - .id(dataSourceId) - .build(); + .indexId(indexId) + .maxResults(10) + .id(dataSourceId) + .build(); ListDataSourceSyncJobsResponse response = kendra.listDataSourceSyncJobs(jobsRequest); List jobs = response.history(); diff --git a/javav2/example_code/kendra/src/main/java/com/example/kendra/QueryIndex.java b/javav2/example_code/kendra/src/main/java/com/example/kendra/QueryIndex.java index d63ca925258..7db1f061e32 100644 --- a/javav2/example_code/kendra/src/main/java/com/example/kendra/QueryIndex.java +++ b/javav2/example_code/kendra/src/main/java/com/example/kendra/QueryIndex.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[QueryIndex.java demonstrates how to query an Amazon Kendra index.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon Kendra] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kendra; @@ -23,7 +17,8 @@ // snippet-end:[kendra.java2.query.index.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -34,13 +29,13 @@ public class QueryIndex { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - indexId - The Id value of the index. - text - The text to use. - """; + Where: + indexId - The Id value of the index. + text - The text to use. + """; if (args.length != 2) { System.out.println(usage); @@ -50,18 +45,18 @@ public static void main(String[] args) { String indexId = args[0]; String text = args[1]; KendraClient kendra = KendraClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); querySpecificIndex(kendra, indexId, text); } public static void querySpecificIndex(KendraClient kendra, String indexId, String text) { try { QueryRequest queryRequest = QueryRequest.builder() - .indexId(indexId) - .queryResultTypeFilter(QueryResultType.DOCUMENT) - .queryText("Spring MVC") - .build(); + .indexId(indexId) + .queryResultTypeFilter(QueryResultType.DOCUMENT) + .queryText("Spring MVC") + .build(); QueryResponse response = kendra.query(queryRequest); List items = response.resultItems(); diff --git a/javav2/example_code/kendra/src/test/java/KendraTest.java b/javav2/example_code/kendra/src/test/java/KendraTest.java index 9e280493212..81ae4567a16 100644 --- a/javav2/example_code/kendra/src/test/java/KendraTest.java +++ b/javav2/example_code/kendra/src/test/java/KendraTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.kendra.*; import com.google.gson.Gson; @@ -38,15 +36,15 @@ public class KendraTest { @BeforeAll public static void setUp() { kendra = KendraClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); String json = getSecretValues(); SecretValues values = gson.fromJson(json, SecretValues.class); - indexName = values.getIndexName()+ java.util.UUID.randomUUID(); + indexName = values.getIndexName() + java.util.UUID.randomUUID(); indexRoleArn = values.getIndexRoleArn(); indexDescription = values.getIndexDescription(); s3BucketName = values.getS3BucketName(); @@ -55,33 +53,35 @@ public static void setUp() { dataSourceRoleArn = values.getDataSourceRoleArn(); text = values.getText(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - - try (InputStream input = KendraTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - // Load a properties file from the class path. - prop.load(input); - - // Populate the data members required for all tests. - indexName = prop.getProperty("indexName")+ java.util.UUID.randomUUID(); - indexRoleArn = prop.getProperty("indexRoleArn"); - indexDescription = prop.getProperty("indexDescription"); - s3BucketName = prop.getProperty("s3BucketName"); - dataSourceName = prop.getProperty("dataSourceName"); - dataSourceDescription = prop.getProperty("dataSourceDescription"); - dataSourceRoleArn = prop.getProperty("dataSourceRoleArn"); - text = prop.getProperty("text"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * + * try (InputStream input = + * KendraTest.class.getClassLoader().getResourceAsStream("config.properties")) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * // Load a properties file from the class path. + * prop.load(input); + * + * // Populate the data members required for all tests. + * indexName = prop.getProperty("indexName")+ java.util.UUID.randomUUID(); + * indexRoleArn = prop.getProperty("indexRoleArn"); + * indexDescription = prop.getProperty("indexDescription"); + * s3BucketName = prop.getProperty("s3BucketName"); + * dataSourceName = prop.getProperty("dataSourceName"); + * dataSourceDescription = prop.getProperty("dataSourceDescription"); + * dataSourceRoleArn = prop.getProperty("dataSourceRoleArn"); + * text = prop.getProperty("text"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @@ -97,17 +97,17 @@ public void CreateIndex() { @Tag("IntegrationTest") @Order(2) public void CreateDataSource() { - dataSourceId = CreateIndexAndDataSourceExample.createDataSource(kendra, s3BucketName, dataSourceName, dataSourceDescription, indexId, dataSourceRoleArn); + dataSourceId = CreateIndexAndDataSourceExample.createDataSource(kendra, s3BucketName, dataSourceName, + dataSourceDescription, indexId, dataSourceRoleArn); assertFalse(dataSourceId.isEmpty()); System.out.println("Test 2 passed"); } - @Test @Tag("IntegrationTest") @Order(3) public void SyncDataSource() { - assertDoesNotThrow(() ->CreateIndexAndDataSourceExample.startDataSource(kendra, indexId, dataSourceId)); + assertDoesNotThrow(() -> CreateIndexAndDataSourceExample.startDataSource(kendra, indexId, dataSourceId)); System.out.println("Test 3 passed"); } @@ -115,25 +115,23 @@ public void SyncDataSource() { @Tag("IntegrationTest") @Order(4) public void ListSyncJobs() { - assertDoesNotThrow(() ->ListDataSourceSyncJobs.listSyncJobs(kendra, indexId, dataSourceId)); + assertDoesNotThrow(() -> ListDataSourceSyncJobs.listSyncJobs(kendra, indexId, dataSourceId)); System.out.println("Test 4 passed"); } - @Test @Tag("IntegrationTest") @Order(5) public void QueryIndex() { - assertDoesNotThrow(() ->QueryIndex.querySpecificIndex(kendra, indexId, text)); + assertDoesNotThrow(() -> QueryIndex.querySpecificIndex(kendra, indexId, text)); System.out.println("Test 5 passed"); } - @Test @Tag("IntegrationTest") @Order(6) public void DeleteDataSource() { - assertDoesNotThrow(() ->DeleteDataSource.deleteSpecificDataSource(kendra, indexId, dataSourceId)); + assertDoesNotThrow(() -> DeleteDataSource.deleteSpecificDataSource(kendra, indexId, dataSourceId)); System.out.println("Test 6 passed"); } @@ -141,19 +139,20 @@ public void DeleteDataSource() { @Tag("IntegrationTest") @Order(7) public void DeleteIndex() { - assertDoesNotThrow(() ->DeleteIndex.deleteSpecificIndex(kendra, indexId)); + assertDoesNotThrow(() -> DeleteIndex.deleteSpecificIndex(kendra, indexId)); System.out.println("Test 7 passed"); } + private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/kendra"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); diff --git a/javav2/example_code/keyspaces/src/main/java/com/example/keyspace/HelloKeyspaces.java b/javav2/example_code/keyspaces/src/main/java/com/example/keyspace/HelloKeyspaces.java index e347f536c57..4265cb3f667 100644 --- a/javav2/example_code/keyspaces/src/main/java/com/example/keyspace/HelloKeyspaces.java +++ b/javav2/example_code/keyspaces/src/main/java/com/example/keyspace/HelloKeyspaces.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[HelloKeyspaces.java demonstrates how to display all current keyspace names and Amazon Resource Names (ARNs).] -///snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Keyspaces] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.keyspace; @@ -20,31 +13,33 @@ import java.util.List; /** - * Before running this Java (v2) code example, set up your development environment, including your credentials. + * Before running this Java (v2) code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ - public class HelloKeyspaces { - public static void main(String[]args) { +public class HelloKeyspaces { + public static void main(String[] args) { Region region = Region.US_EAST_1; KeyspacesClient keyClient = KeyspacesClient.builder() - .region(region) - .build(); + .region(region) + .build(); listKeyspaces(keyClient); } + public static void listKeyspaces(KeyspacesClient keyClient) { try { ListKeyspacesRequest keyspacesRequest = ListKeyspacesRequest.builder() - .maxResults(10) - .build(); + .maxResults(10) + .build(); ListKeyspacesResponse response = keyClient.listKeyspaces(keyspacesRequest); List keyspaces = response.keyspaces(); - for (KeyspaceSummary keyspace: keyspaces) { - System.out.println("The name of the keyspace is "+keyspace.keyspaceName()); + for (KeyspaceSummary keyspace : keyspaces) { + System.out.println("The name of the keyspace is " + keyspace.keyspaceName()); } } catch (KeyspacesException e) { diff --git a/javav2/example_code/keyspaces/src/main/java/com/example/keyspace/ScenarioKeyspaces.java b/javav2/example_code/keyspaces/src/main/java/com/example/keyspace/ScenarioKeyspaces.java index 223623d2fe9..8e3cc3dfd97 100644 --- a/javav2/example_code/keyspaces/src/main/java/com/example/keyspace/ScenarioKeyspaces.java +++ b/javav2/example_code/keyspaces/src/main/java/com/example/keyspace/ScenarioKeyspaces.java @@ -1,11 +1,5 @@ -// snippet-sourcedescription:[ScenarioKeyspaces.java demonstrates how to perform various Amazon Keyspace operations.] -///snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Keyspaces] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.keyspace; @@ -58,9 +52,10 @@ import java.util.Iterator; import java.util.List; -//snippet-start:[keyspace.java2.scenario.main] +// snippet-start:[keyspace.java2.scenario.main] /** - * Before running this Java (v2) code example, set up your development environment, including your credentials. + * Before running this Java (v2) code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -80,7 +75,8 @@ * 1. Create a keyspace. * 2. Check for keyspace existence. * 3. List keyspaces using a paginator. - * 4. Create a table with a simple movie data schema and enable point-in-time recovery. + * 4. Create a table with a simple movie data schema and enable point-in-time + * recovery. * 5. Check for the table to be in an Active state. * 6. List all tables in the keyspace. * 7. Use a Cassandra driver to insert some records into the Movie table. @@ -98,29 +94,30 @@ */ public class ScenarioKeyspaces { - public static final String DASHES = new String(new char[80]).replace("\0", "-") ; + public static final String DASHES = new String(new char[80]).replace("\0", "-"); /* - Usage: - fileName - The name of the JSON file that contains movie data. (Get this file from the GitHub repo at resources/sample_file.) - keyspaceName - The name of the keyspace to create. - */ - public static void main(String[]args) throws InterruptedException, IOException { - String fileName = "" ; + * Usage: + * fileName - The name of the JSON file that contains movie data. (Get this file + * from the GitHub repo at resources/sample_file.) + * keyspaceName - The name of the keyspace to create. + */ + public static void main(String[] args) throws InterruptedException, IOException { + String fileName = ""; String keyspaceName = ""; String titleUpdate = "The Family"; - int yearUpdate = 2013 ; - String tableName = "Movie" ; - String tableNameRestore = "MovieRestore" ; + int yearUpdate = 2013; + String tableName = "Movie"; + String tableNameRestore = "MovieRestore"; Region region = Region.US_EAST_1; KeyspacesClient keyClient = KeyspacesClient.builder() - .region(region) - .build(); + .region(region) + .build(); DriverConfigLoader loader = DriverConfigLoader.fromClasspath("application.conf"); CqlSession session = CqlSession.builder() - .withConfigLoader(loader) - .build(); + .withConfigLoader(loader) + .build(); System.out.println(DASHES); System.out.println("Welcome to the Amazon Keyspaces example scenario."); @@ -230,12 +227,12 @@ public static void main(String[]args) throws InterruptedException, IOException { System.out.println(DASHES); } - //snippet-start:[keyspace.java2.scenario.delete.keyspace.main] + // snippet-start:[keyspace.java2.scenario.delete.keyspace.main] public static void deleteKeyspace(KeyspacesClient keyClient, String keyspaceName) { try { DeleteKeyspaceRequest deleteKeyspaceRequest = DeleteKeyspaceRequest.builder() - .keyspaceName(keyspaceName) - .build(); + .keyspaceName(keyspaceName) + .build(); keyClient.deleteKeyspace(deleteKeyspaceRequest); @@ -244,22 +241,24 @@ public static void deleteKeyspace(KeyspacesClient keyClient, String keyspaceName System.exit(1); } } - //snippet-end:[keyspace.java2.scenario.delete.keyspace.main] + // snippet-end:[keyspace.java2.scenario.delete.keyspace.main] - public static void checkTableDelete(KeyspacesClient keyClient, String keyspaceName, String tableName)throws InterruptedException { + public static void checkTableDelete(KeyspacesClient keyClient, String keyspaceName, String tableName) + throws InterruptedException { try { String status; GetTableResponse response; GetTableRequest tableRequest = GetTableRequest.builder() - .keyspaceName(keyspaceName) - .tableName(tableName) - .build(); + .keyspaceName(keyspaceName) + .tableName(tableName) + .build(); - // Keep looping until table cannot be found and a ResourceNotFoundException is thrown. + // Keep looping until table cannot be found and a ResourceNotFoundException is + // thrown. while (true) { response = keyClient.getTable(tableRequest); status = response.statusAsString(); - System.out.println(". The table status is "+status); + System.out.println(". The table status is " + status); Thread.sleep(500); } @@ -269,13 +268,13 @@ public static void checkTableDelete(KeyspacesClient keyClient, String keyspaceNa System.out.println("The table is deleted"); } - //snippet-start:[keyspace.java2.scenario.delete.table.main] - public static void deleteTable(KeyspacesClient keyClient, String keyspaceName, String tableName){ + // snippet-start:[keyspace.java2.scenario.delete.table.main] + public static void deleteTable(KeyspacesClient keyClient, String keyspaceName, String tableName) { try { DeleteTableRequest tableRequest = DeleteTableRequest.builder() - .keyspaceName(keyspaceName) - .tableName(tableName) - .build(); + .keyspaceName(keyspaceName) + .tableName(tableName) + .build(); keyClient.deleteTable(tableRequest); @@ -284,33 +283,34 @@ public static void deleteTable(KeyspacesClient keyClient, String keyspaceName, S System.exit(1); } } - //snippet-end:[keyspace.java2.scenario.delete.table.main] + // snippet-end:[keyspace.java2.scenario.delete.table.main] - public static void checkRestoredTable(KeyspacesClient keyClient, String keyspaceName, String tableName)throws InterruptedException { + public static void checkRestoredTable(KeyspacesClient keyClient, String keyspaceName, String tableName) + throws InterruptedException { try { boolean tableStatus = false; String status; GetTableResponse response = null; GetTableRequest tableRequest = GetTableRequest.builder() - .keyspaceName(keyspaceName) - .tableName(tableName) - .build(); + .keyspaceName(keyspaceName) + .tableName(tableName) + .build(); while (!tableStatus) { response = keyClient.getTable(tableRequest); status = response.statusAsString(); - System.out.println("The table status is "+status); + System.out.println("The table status is " + status); - if (status.compareTo("ACTIVE") ==0) { + if (status.compareTo("ACTIVE") == 0) { tableStatus = true; } Thread.sleep(500); } List cols = response.schemaDefinition().allColumns(); - for (ColumnDefinition def: cols) { - System.out.println("The column name is "+def.name()); - System.out.println("The column type is "+def.type()); + for (ColumnDefinition def : cols) { + System.out.println("The column name is " + def.name()); + System.out.println("The column type is " + def.type()); } } catch (KeyspacesException e) { @@ -319,30 +319,31 @@ public static void checkRestoredTable(KeyspacesClient keyClient, String keyspace } } - //snippet-start:[keyspace.java2.scenario.restore.table.main] + // snippet-start:[keyspace.java2.scenario.restore.table.main] public static void restoreTable(KeyspacesClient keyClient, String keyspaceName, ZonedDateTime utc) { try { Instant myTime = utc.toInstant(); RestoreTableRequest restoreTableRequest = RestoreTableRequest.builder() - .restoreTimestamp(myTime) - .sourceTableName("Movie") - .targetKeyspaceName(keyspaceName) - .targetTableName("MovieRestore") - .sourceKeyspaceName(keyspaceName) - .build(); + .restoreTimestamp(myTime) + .sourceTableName("Movie") + .targetKeyspaceName(keyspaceName) + .targetTableName("MovieRestore") + .sourceKeyspaceName(keyspaceName) + .build(); RestoreTableResponse response = keyClient.restoreTable(restoreTableRequest); - System.out.println("The ARN of the restored table is "+response.restoredTableARN()); + System.out.println("The ARN of the restored table is " + response.restoredTableARN()); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } - //snippet-end:[keyspace.java2.scenario.restore.table.main] + // snippet-end:[keyspace.java2.scenario.restore.table.main] public static void getWatchedData(CqlSession session, String keyspaceName) { - ResultSet resultSet = session.execute("SELECT * FROM \""+keyspaceName+"\".\"Movie\" WHERE watched = true ALLOW FILTERING;"); + ResultSet resultSet = session + .execute("SELECT * FROM \"" + keyspaceName + "\".\"Movie\" WHERE watched = true ALLOW FILTERING;"); resultSet.forEach(item -> { System.out.println("The Movie title is " + item.getString("title")); System.out.println("The Movie year is " + item.getInt("year")); @@ -351,32 +352,33 @@ public static void getWatchedData(CqlSession session, String keyspaceName) { } public static void updateRecord(CqlSession session, String keySpace, String titleUpdate, int yearUpdate) { - String sqlStatement = "UPDATE \""+keySpace+"\".\"Movie\" SET watched=true WHERE title = :k0 AND year = :k1;"; + String sqlStatement = "UPDATE \"" + keySpace + + "\".\"Movie\" SET watched=true WHERE title = :k0 AND year = :k1;"; BatchStatementBuilder builder = BatchStatement.builder(DefaultBatchType.UNLOGGED); builder.setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM); PreparedStatement preparedStatement = session.prepare(sqlStatement); builder.addStatement(preparedStatement.boundStatementBuilder() - .setString("k0", titleUpdate) - .setInt("k1", yearUpdate) - .build()); + .setString("k0", titleUpdate) + .setInt("k1", yearUpdate) + .build()); BatchStatement batchStatement = builder.build(); session.execute(batchStatement); } - //snippet-start:[keyspace.java2.scenario.update.table.main] - public static void updateTable(KeyspacesClient keyClient, String keySpace, String tableName){ + // snippet-start:[keyspace.java2.scenario.update.table.main] + public static void updateTable(KeyspacesClient keyClient, String keySpace, String tableName) { try { ColumnDefinition def = ColumnDefinition.builder() - .name("watched") - .type("boolean") - .build(); + .name("watched") + .type("boolean") + .build(); UpdateTableRequest tableRequest = UpdateTableRequest.builder() - .keyspaceName(keySpace) - .tableName(tableName) - .addColumns(def) - .build(); + .keyspaceName(keySpace) + .tableName(tableName) + .addColumns(def) + .build(); keyClient.updateTable(tableRequest); @@ -385,10 +387,11 @@ public static void updateTable(KeyspacesClient keyClient, String keySpace, Strin System.exit(1); } } - //snippet-end:[keyspace.java2.scenario.update.table.main] + // snippet-end:[keyspace.java2.scenario.update.table.main] public static void getSpecificMovie(CqlSession session, String keyspaceName) { - ResultSet resultSet = session.execute("SELECT * FROM \""+keyspaceName+"\".\"Movie\" WHERE title = 'The Family' ALLOW FILTERING ;"); + ResultSet resultSet = session.execute( + "SELECT * FROM \"" + keyspaceName + "\".\"Movie\" WHERE title = 'The Family' ALLOW FILTERING ;"); resultSet.forEach(item -> { System.out.println("The Movie title is " + item.getString("title")); System.out.println("The Movie year is " + item.getInt("year")); @@ -398,7 +401,7 @@ public static void getSpecificMovie(CqlSession session, String keyspaceName) { // Get records from the Movie table. public static void getMovieData(CqlSession session, String keyspaceName) { - ResultSet resultSet = session.execute("SELECT * FROM \""+keyspaceName+"\".\"Movie\";"); + ResultSet resultSet = session.execute("SELECT * FROM \"" + keyspaceName + "\".\"Movie\";"); resultSet.forEach(item -> { System.out.println("The Movie title is " + item.getString("title")); System.out.println("The Movie year is " + item.getInt("year")); @@ -408,17 +411,17 @@ public static void getMovieData(CqlSession session, String keyspaceName) { // Load data into the table. public static void loadData(CqlSession session, String fileName, String keySpace) throws IOException { - String sqlStatement = "INSERT INTO \""+keySpace +"\".\"Movie\" (title, year, plot) values (:k0, :k1, :k2)"; + String sqlStatement = "INSERT INTO \"" + keySpace + "\".\"Movie\" (title, year, plot) values (:k0, :k1, :k2)"; JsonParser parser = new JsonFactory().createParser(new File(fileName)); com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); Iterator iter = rootNode.iterator(); ObjectNode currentNode; - int t = 0 ; + int t = 0; while (iter.hasNext()) { // Add 20 movies to the table. if (t == 20) - break ; + break; currentNode = (ObjectNode) iter.next(); int year = currentNode.path("year").asInt(); @@ -430,65 +433,66 @@ public static void loadData(CqlSession session, String fileName, String keySpace builder.setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM); PreparedStatement preparedStatement = session.prepare(sqlStatement); builder.addStatement(preparedStatement.boundStatementBuilder() - .setString("k0", title) - .setInt("k1", year) - .setString("k2", plot) - .build()); + .setString("k0", title) + .setInt("k1", year) + .setString("k2", plot) + .build()); BatchStatement batchStatement = builder.build(); session.execute(batchStatement); t++; } - System.out.println("You have added " +t +" records successfully!"); + System.out.println("You have added " + t + " records successfully!"); } - //snippet-start:[keyspace.java2.scenario.list.tables.main] + // snippet-start:[keyspace.java2.scenario.list.tables.main] public static void listTables(KeyspacesClient keyClient, String keyspaceName) { try { ListTablesRequest tablesRequest = ListTablesRequest.builder() - .keyspaceName(keyspaceName) - .build(); + .keyspaceName(keyspaceName) + .build(); ListTablesIterable listRes = keyClient.listTablesPaginator(tablesRequest); listRes.stream() - .flatMap(r -> r.tables().stream()) - .forEach(content -> System.out.println(" ARN: " + content.resourceArn() + - " Table name: " + content.tableName())); + .flatMap(r -> r.tables().stream()) + .forEach(content -> System.out.println(" ARN: " + content.resourceArn() + + " Table name: " + content.tableName())); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } - //snippet-end:[keyspace.java2.scenario.list.tables.main] + // snippet-end:[keyspace.java2.scenario.list.tables.main] - //snippet-start:[keyspace.java2.scenario.get.table.main] - public static void checkTable(KeyspacesClient keyClient, String keyspaceName, String tableName)throws InterruptedException { + // snippet-start:[keyspace.java2.scenario.get.table.main] + public static void checkTable(KeyspacesClient keyClient, String keyspaceName, String tableName) + throws InterruptedException { try { boolean tableStatus = false; String status; GetTableResponse response = null; GetTableRequest tableRequest = GetTableRequest.builder() - .keyspaceName(keyspaceName) - .tableName(tableName) - .build(); + .keyspaceName(keyspaceName) + .tableName(tableName) + .build(); while (!tableStatus) { response = keyClient.getTable(tableRequest); status = response.statusAsString(); - System.out.println(". The table status is "+status); + System.out.println(". The table status is " + status); - if (status.compareTo("ACTIVE") ==0) { + if (status.compareTo("ACTIVE") == 0) { tableStatus = true; } Thread.sleep(500); } List cols = response.schemaDefinition().allColumns(); - for (ColumnDefinition def: cols) { - System.out.println("The column name is "+def.name()); - System.out.println("The column type is "+def.type()); + for (ColumnDefinition def : cols) { + System.out.println("The column name is " + def.name()); + System.out.println("The column type is " + def.type()); } } catch (KeyspacesException e) { @@ -496,31 +500,31 @@ public static void checkTable(KeyspacesClient keyClient, String keyspaceName, St System.exit(1); } } - //snippet-end:[keyspace.java2.scenario.get.table.main] + // snippet-end:[keyspace.java2.scenario.get.table.main] - //snippet-start:[keyspace.java2.scenario.create.table.main] + // snippet-start:[keyspace.java2.scenario.create.table.main] public static void createTable(KeyspacesClient keyClient, String keySpace, String tableName) { try { // Set the columns. ColumnDefinition defTitle = ColumnDefinition.builder() - .name("title") - .type("text") - .build(); + .name("title") + .type("text") + .build(); ColumnDefinition defYear = ColumnDefinition.builder() - .name("year") - .type("int") - .build(); + .name("year") + .type("int") + .build(); ColumnDefinition defReleaseDate = ColumnDefinition.builder() - .name("release_date") - .type("timestamp") - .build(); + .name("release_date") + .type("timestamp") + .build(); ColumnDefinition defPlot = ColumnDefinition.builder() - .name("plot") - .type("text") - .build(); + .name("plot") + .type("text") + .build(); List colList = new ArrayList<>(); colList.add(defTitle); @@ -530,95 +534,95 @@ public static void createTable(KeyspacesClient keyClient, String keySpace, Strin // Set the keys. PartitionKey yearKey = PartitionKey.builder() - .name("year") - .build(); + .name("year") + .build(); PartitionKey titleKey = PartitionKey.builder() - .name("title") - .build(); + .name("title") + .build(); List keyList = new ArrayList<>(); keyList.add(yearKey); keyList.add(titleKey); SchemaDefinition schemaDefinition = SchemaDefinition.builder() - .partitionKeys(keyList) - .allColumns(colList) - .build(); + .partitionKeys(keyList) + .allColumns(colList) + .build(); PointInTimeRecovery timeRecovery = PointInTimeRecovery.builder() - .status(PointInTimeRecoveryStatus.ENABLED) - .build(); + .status(PointInTimeRecoveryStatus.ENABLED) + .build(); CreateTableRequest tableRequest = CreateTableRequest.builder() - .keyspaceName(keySpace) - .tableName(tableName) - .schemaDefinition(schemaDefinition) - .pointInTimeRecovery(timeRecovery) - .build(); + .keyspaceName(keySpace) + .tableName(tableName) + .schemaDefinition(schemaDefinition) + .pointInTimeRecovery(timeRecovery) + .build(); CreateTableResponse response = keyClient.createTable(tableRequest); - System.out.println("The table ARN is "+response.resourceArn()); + System.out.println("The table ARN is " + response.resourceArn()); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } - //snippet-end:[keyspace.java2.scenario.create.table.main] + // snippet-end:[keyspace.java2.scenario.create.table.main] - //snippet-start:[keyspace.java2.scenario.list.keyspaces.main] + // snippet-start:[keyspace.java2.scenario.list.keyspaces.main] public static void listKeyspacesPaginator(KeyspacesClient keyClient) { try { ListKeyspacesRequest keyspacesRequest = ListKeyspacesRequest.builder() - .maxResults(10) - .build(); + .maxResults(10) + .build(); ListKeyspacesIterable listRes = keyClient.listKeyspacesPaginator(keyspacesRequest); listRes.stream() - .flatMap(r -> r.keyspaces().stream()) - .forEach(content -> System.out.println(" Name: " + content.keyspaceName())); + .flatMap(r -> r.keyspaces().stream()) + .forEach(content -> System.out.println(" Name: " + content.keyspaceName())); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } - //snippet-end:[keyspace.java2.scenario.list.keyspaces.main] + // snippet-end:[keyspace.java2.scenario.list.keyspaces.main] - //snippet-start:[keyspace.java2.scenario.get.keyspace.main] + // snippet-start:[keyspace.java2.scenario.get.keyspace.main] public static void checkKeyspaceExistence(KeyspacesClient keyClient, String keyspaceName) { try { GetKeyspaceRequest keyspaceRequest = GetKeyspaceRequest.builder() - .keyspaceName(keyspaceName) - .build(); + .keyspaceName(keyspaceName) + .build(); GetKeyspaceResponse response = keyClient.getKeyspace(keyspaceRequest); String name = response.keyspaceName(); - System.out.println("The "+ name+ " KeySpace is ready"); + System.out.println("The " + name + " KeySpace is ready"); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } - //snippet-end:[keyspace.java2.scenario.get.keyspace.main] + // snippet-end:[keyspace.java2.scenario.get.keyspace.main] - //snippet-start:[keyspace.java2.scenario.create.keyspace.main] + // snippet-start:[keyspace.java2.scenario.create.keyspace.main] public static void createKeySpace(KeyspacesClient keyClient, String keyspaceName) { try { CreateKeyspaceRequest keyspaceRequest = CreateKeyspaceRequest.builder() - .keyspaceName(keyspaceName) - .build(); + .keyspaceName(keyspaceName) + .build(); CreateKeyspaceResponse response = keyClient.createKeyspace(keyspaceRequest); - System.out.println("The ARN of the KeySpace is "+response.resourceArn()); + System.out.println("The ARN of the KeySpace is " + response.resourceArn()); } catch (KeyspacesException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } - //snippet-end:[keyspace.java2.scenario.create.keyspace.main] + // snippet-end:[keyspace.java2.scenario.create.keyspace.main] } -//snippet-end:[keyspace.java2.scenario.main] +// snippet-end:[keyspace.java2.scenario.main] diff --git a/javav2/example_code/keyspaces/src/test/java/KeyspaceTest.java b/javav2/example_code/keyspaces/src/test/java/KeyspaceTest.java index 7b427d73901..569601ccebe 100644 --- a/javav2/example_code/keyspaces/src/test/java/KeyspaceTest.java +++ b/javav2/example_code/keyspaces/src/test/java/KeyspaceTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.datastax.oss.driver.api.core.CqlSession; import com.datastax.oss.driver.api.core.config.DriverConfigLoader; @@ -31,13 +29,13 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class KeyspaceTest { - public static final String DASHES = new String(new char[80]).replace("\0", "-") ; - private static String fileName = "" ; + public static final String DASHES = new String(new char[80]).replace("\0", "-"); + private static String fileName = ""; private static String keyspaceName = ""; private static String titleUpdate = "The Family"; - private static int yearUpdate = 2013 ; - private static String tableName = "Movie" ; - private static String tableNameRestore = "MovieRestore" ; + private static int yearUpdate = 2013; + private static String tableName = "Movie"; + private static String tableNameRestore = "MovieRestore"; private static KeyspacesClient keyClient; private static CqlSession session; @@ -45,25 +43,25 @@ public class KeyspaceTest { public static void setUp() { Random rand = new Random(); int randomNum = rand.nextInt((10000 - 1) + 1) + 1; - keyspaceName = "key"+randomNum; + keyspaceName = "key" + randomNum; Region region = Region.US_EAST_1; keyClient = KeyspacesClient.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); DriverConfigLoader loader = DriverConfigLoader.fromClasspath("application.conf"); session = CqlSession.builder() - .withConfigLoader(loader) - .build(); + .withConfigLoader(loader) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); String json = getSecretValues(); SecretValues values = gson.fromJson(json, SecretValues.class); fileName = values.getFileName(); - keyspaceName = values.getKeyspaceName()+randomNum; - } + keyspaceName = values.getKeyspaceName() + randomNum; + } @Test @Tag("IntegrationTest") @@ -163,17 +161,18 @@ public void scenarioTest() throws InterruptedException, IOException { ScenarioKeyspaces.deleteKeyspace(keyClient, keyspaceName); System.out.println(DASHES); } + public static String getSecretValues() { // Get the Amazon RDS creds from Secrets Manager. SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/keyspace"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -194,12 +193,3 @@ public String getKeyspaceName() { } } } - - - - - - - - - diff --git a/javav2/example_code/kinesis/run_example.sh b/javav2/example_code/kinesis/run_example.sh index 614a92fe4b3..308919fecbe 100755 --- a/javav2/example_code/kinesis/run_example.sh +++ b/javav2/example_code/kinesis/run_example.sh @@ -1,13 +1,15 @@ -#!/bin/bash -if [[ -z $* ]] ; then - echo 'Supply the name of one of the example classes as an argument.' - echo 'If there are arguments to the class, put them in quotes after the class name.' - exit 1 -fi -export CLASSPATH=target/sdk-s3-examples-1.0.jar -export className=$1 -echo "## Running $className..." -shift -echo "## arguments $@..." -mvn exec:java -Dexec.mainClass="com.example.kinesis.$className" -Dexec.args="$@" - +#!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +if [[ -z $* ]] ; then + echo 'Supply the name of one of the example classes as an argument.' + echo 'If there are arguments to the class, put them in quotes after the class name.' + exit 1 +fi +export CLASSPATH=target/sdk-s3-examples-1.0.jar +export className=$1 +echo "## Running $className..." +shift +echo "## arguments $@..." +mvn exec:java -Dexec.mainClass="com.example.kinesis.$className" -Dexec.args="$@" + diff --git a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/AddDataShards.java b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/AddDataShards.java index 01b9fedc8a7..49e48a63283 100644 --- a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/AddDataShards.java +++ b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/AddDataShards.java @@ -1,25 +1,20 @@ -//snippet-sourcedescription:[AddDataShards.java demonstrates how to increase shard count in an Amazon Kinesis data stream.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Kinesis] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kinesis; // snippet-start:[kinesis.java2.AddDataShards.main] -//snippet-start:[kinesis.java2.AddDataShards.import] +// snippet-start:[kinesis.java2.AddDataShards.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kinesis.KinesisClient; import software.amazon.awssdk.services.kinesis.model.KinesisException; import software.amazon.awssdk.services.kinesis.model.UpdateShardCountRequest; import software.amazon.awssdk.services.kinesis.model.UpdateShardCountResponse; -//snippet-end:[kinesis.java2.AddDataShards.import] +// snippet-end:[kinesis.java2.AddDataShards.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,12 +24,12 @@ public class AddDataShards { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - streamName - The Amazon Kinesis data stream (for example, StockTradeStream) - """; + Where: + streamName - The Amazon Kinesis data stream (for example, StockTradeStream) + """; if (args.length != 1) { System.out.println(usage); @@ -48,8 +43,8 @@ public static void main(String[] args) { // snippet-start:[kinesis.java2.AddDataShards.client] Region region = Region.US_EAST_1; KinesisClient kinesisClient = KinesisClient.builder() - .region(region) - .build(); + .region(region) + .build(); // snippet-end:[kinesis.java2.AddDataShards.client] addShards(kinesisClient, name, goalShards); @@ -60,10 +55,10 @@ public static void main(String[] args) { public static void addShards(KinesisClient kinesisClient, String name, int goalShards) { try { UpdateShardCountRequest request = UpdateShardCountRequest.builder() - .scalingType("UNIFORM_SCALING") - .streamName(name) - .targetShardCount(goalShards) - .build(); + .scalingType("UNIFORM_SCALING") + .streamName(name) + .targetShardCount(goalShards) + .build(); UpdateShardCountResponse response = kinesisClient.updateShardCount(request); System.out.println(response.streamName() + " has updated shard count to " + response.currentShardCount()); diff --git a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/ClientConfiguration.java b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/ClientConfiguration.java index 47f438c8175..47bc9e566dd 100644 --- a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/ClientConfiguration.java +++ b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/ClientConfiguration.java @@ -1,11 +1,8 @@ -//snippet-sourcedescription:[ClientConfiguration.java demonstrates how to create an Amazon Kinesis asynchronous client.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Kinesis] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.kinesis; + // snippet-start:[kinesis.java2.client_configuration.complete] // snippet-start:[kinesis.java2.client_configuration.import] import software.amazon.awssdk.http.async.SdkAsyncHttpClient; @@ -16,32 +13,34 @@ // snippet-start:[kinesis.java2.client_configuration.main] public class ClientConfiguration { - public static void main(String[] args) { - // If configured with an httpClientBuilder, the SDK will manage the lifecycle of the HTTP client - // and it will be shutdown when the client is shut down. - // snippet-start:[kinesis.java2.client_configuration.client] - KinesisAsyncClient client = KinesisAsyncClient.builder() - .httpClientBuilder(NettyNioAsyncHttpClient.builder() - .maxConcurrency(100) - .maxPendingConnectionAcquires(10_000)) - .build(); - - // snippet-end:[kinesis.java2.client_configuration.client] - // When passing in the httpClient directly, the lifecycle must be managed by the caller and the HTTP client - // will not be shut down when the client is shut down. - // snippet-start:[kinesis.java2.client_configuration.httpclient] - SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder() - .maxConcurrency(100) - .maxPendingConnectionAcquires(10_000) - .build(); - - KinesisAsyncClient kinesisClient = KinesisAsyncClient.builder() - .httpClient(httpClient) - .build(); - - httpClient.close(); - // snippet-end:[kinesis.java2.client_configuration.httpclient] - } + public static void main(String[] args) { + // If configured with an httpClientBuilder, the SDK will manage the lifecycle of + // the HTTP client + // and it will be shutdown when the client is shut down. + // snippet-start:[kinesis.java2.client_configuration.client] + KinesisAsyncClient client = KinesisAsyncClient.builder() + .httpClientBuilder(NettyNioAsyncHttpClient.builder() + .maxConcurrency(100) + .maxPendingConnectionAcquires(10_000)) + .build(); + + // snippet-end:[kinesis.java2.client_configuration.client] + // When passing in the httpClient directly, the lifecycle must be managed by the + // caller and the HTTP client + // will not be shut down when the client is shut down. + // snippet-start:[kinesis.java2.client_configuration.httpclient] + SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder() + .maxConcurrency(100) + .maxPendingConnectionAcquires(10_000) + .build(); + + KinesisAsyncClient kinesisClient = KinesisAsyncClient.builder() + .httpClient(httpClient) + .build(); + + httpClient.close(); + // snippet-end:[kinesis.java2.client_configuration.httpclient] + } } diff --git a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/CreateDataStream.java b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/CreateDataStream.java index 919761acafd..113152c63b7 100644 --- a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/CreateDataStream.java +++ b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/CreateDataStream.java @@ -1,23 +1,19 @@ -//snippet-sourcedescription:[CreateDataStream.java demonstrates how to create an Amazon Kinesis data stream.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Kinesis] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kinesis; // snippet-start:[kinesis.java2.create.main] -//snippet-start:[kinesis.java2.create.import] +// snippet-start:[kinesis.java2.create.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kinesis.KinesisClient; import software.amazon.awssdk.services.kinesis.model.CreateStreamRequest; import software.amazon.awssdk.services.kinesis.model.KinesisException; -//snippet-end:[kinesis.java2.create.import] +// snippet-end:[kinesis.java2.create.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +24,12 @@ public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - streamName - The Amazon Kinesis data stream (for example, StockTradeStream). - """; + Where: + streamName - The Amazon Kinesis data stream (for example, StockTradeStream). + """; if (args.length != 1) { System.out.println(usage); @@ -43,20 +39,19 @@ public static void main(String[] args) { String streamName = args[0]; Region region = Region.US_EAST_1; KinesisClient kinesisClient = KinesisClient.builder() - .region(region) - .build(); + .region(region) + .build(); createStream(kinesisClient, streamName); System.out.println("Done"); kinesisClient.close(); } - public static void createStream(KinesisClient kinesisClient, String streamName) { try { CreateStreamRequest streamReq = CreateStreamRequest.builder() - .streamName(streamName) - .shardCount(1) - .build(); + .streamName(streamName) + .shardCount(1) + .build(); kinesisClient.createStream(streamReq); diff --git a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/DeleteDataStream.java b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/DeleteDataStream.java index a1703e4c196..267a295fd73 100644 --- a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/DeleteDataStream.java +++ b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/DeleteDataStream.java @@ -1,23 +1,19 @@ -//snippet-sourcedescription:[DeleteDataStream.java demonstrates how to delete an Amazon Kinesis data stream.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Kinesis] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kinesis; // snippet-start:[kinesis.java2.delete.main] -//snippet-start:[kinesis.java2.delete.import] +// snippet-start:[kinesis.java2.delete.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kinesis.KinesisClient; import software.amazon.awssdk.services.kinesis.model.DeleteStreamRequest; import software.amazon.awssdk.services.kinesis.model.KinesisException; -//snippet-end:[kinesis.java2.delete.import] +// snippet-end:[kinesis.java2.delete.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +24,12 @@ public class DeleteDataStream { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - streamName - The Amazon Kinesis data stream (for example, StockTradeStream) - """; + Where: + streamName - The Amazon Kinesis data stream (for example, StockTradeStream) + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +39,8 @@ public static void main(String[] args) { String streamName = args[0]; Region region = Region.US_EAST_1; KinesisClient kinesisClient = KinesisClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteStream(kinesisClient, streamName); kinesisClient.close(); @@ -54,8 +50,8 @@ public static void main(String[] args) { public static void deleteStream(KinesisClient kinesisClient, String streamName) { try { DeleteStreamRequest delStream = DeleteStreamRequest.builder() - .streamName(streamName) - .build(); + .streamName(streamName) + .build(); kinesisClient.deleteStream(delStream); diff --git a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/DescribeLimits.java b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/DescribeLimits.java index 9e3623f061e..aba33ed69da 100644 --- a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/DescribeLimits.java +++ b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/DescribeLimits.java @@ -1,23 +1,20 @@ -//snippet-sourcedescription:[DescribeLimits.java demonstrates how to display the shard limit and usage for a given account.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Kinesis] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kinesis; + // snippet-start:[kinesis.java2.DescribeLimits.main] -//snippet-start:[kinesis.java2.DescribeLimits.import] +// snippet-start:[kinesis.java2.DescribeLimits.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kinesis.KinesisClient; import software.amazon.awssdk.services.kinesis.model.DescribeLimitsRequest; import software.amazon.awssdk.services.kinesis.model.DescribeLimitsResponse; import software.amazon.awssdk.services.kinesis.model.KinesisException; -//snippet-end:[kinesis.java2.DescribeLimits.import] +// snippet-end:[kinesis.java2.DescribeLimits.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,8 +25,8 @@ public static void main(String[] args) { // snippet-start:[kinesis.java2.DescribeLimits.client] Region region = Region.US_EAST_1; KinesisClient kinesisClient = KinesisClient.builder() - .region(region) - .build(); + .region(region) + .build(); // snippet-end:[kinesis.java2.DescribeLimits.client] describeKinLimits(kinesisClient); @@ -39,7 +36,7 @@ public static void main(String[] args) { public static void describeKinLimits(KinesisClient kinesisClient) { try { DescribeLimitsRequest request = DescribeLimitsRequest.builder() - .build(); + .build(); DescribeLimitsResponse response = kinesisClient.describeLimits(request); System.out.println("Number of open shards: " + response.openShardCount()); diff --git a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/GetRecords.java b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/GetRecords.java index 58b92e1c112..8998220c0c2 100644 --- a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/GetRecords.java +++ b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/GetRecords.java @@ -1,15 +1,10 @@ -//snippet-sourcedescription:[GetRecords.java demonstrates how to read multiple data records from an Amazon Kinesis data stream.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Kinesis] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kinesis; // snippet-start:[kinesis.java2.getrecord.main] -//snippet-start:[kinesis.java2.getrecord.import] +// snippet-start:[kinesis.java2.getrecord.import] import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kinesis.KinesisClient; @@ -23,10 +18,11 @@ import software.amazon.awssdk.services.kinesis.model.GetRecordsResponse; import java.util.ArrayList; import java.util.List; -//snippet-end:[kinesis.java2.getrecord.import] +// snippet-end:[kinesis.java2.getrecord.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -36,12 +32,12 @@ public class GetRecords { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - streamName - The Amazon Kinesis data stream to read from (for example, StockTradeStream). - """; + Where: + streamName - The Amazon Kinesis data stream to read from (for example, StockTradeStream). + """; if (args.length != 1) { System.out.println(usage); @@ -51,8 +47,8 @@ public static void main(String[] args) { String streamName = args[0]; Region region = Region.US_EAST_1; KinesisClient kinesisClient = KinesisClient.builder() - .region(region) - .build(); + .region(region) + .build(); getStockTrades(kinesisClient, streamName); kinesisClient.close(); @@ -62,8 +58,8 @@ public static void getStockTrades(KinesisClient kinesisClient, String streamName String shardIterator; String lastShardId = null; DescribeStreamRequest describeStreamRequest = DescribeStreamRequest.builder() - .streamName(streamName) - .build(); + .streamName(streamName) + .build(); List shards = new ArrayList<>(); DescribeStreamResponse streamRes; @@ -77,10 +73,10 @@ public static void getStockTrades(KinesisClient kinesisClient, String streamName } while (streamRes.streamDescription().hasMoreShards()); GetShardIteratorRequest itReq = GetShardIteratorRequest.builder() - .streamName(streamName) - .shardIteratorType("TRIM_HORIZON") - .shardId(lastShardId) - .build(); + .streamName(streamName) + .shardIteratorType("TRIM_HORIZON") + .shardId(lastShardId) + .build(); GetShardIteratorResponse shardIteratorResult = kinesisClient.getShardIterator(itReq); shardIterator = shardIteratorResult.shardIterator(); @@ -91,9 +87,9 @@ public static void getStockTrades(KinesisClient kinesisClient, String streamName // Create new GetRecordsRequest with existing shardIterator. // Set maximum records to return to 1000. GetRecordsRequest recordsRequest = GetRecordsRequest.builder() - .shardIterator(shardIterator) - .limit(1000) - .build(); + .shardIterator(shardIterator) + .limit(1000) + .build(); GetRecordsResponse result = kinesisClient.getRecords(recordsRequest); @@ -108,4 +104,3 @@ public static void getStockTrades(KinesisClient kinesisClient, String streamName } } // snippet-end:[kinesis.java2.getrecord.main] - diff --git a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/KinesisStreamEx.java b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/KinesisStreamEx.java index fe2c458d285..a95017e228e 100755 --- a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/KinesisStreamEx.java +++ b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/KinesisStreamEx.java @@ -1,13 +1,9 @@ -//snippet-sourcedescription:[KinesisStreamEx.java demonstrates the various ways to consume and process an Amazon Kinesis stream asynchronously.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Kinesis] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.kinesis; // snippet-start:[kinesis.java2.stream_example.complete] + // snippet-start:[kinesis.java2.stream_example.import] import java.util.concurrent.CompletableFuture; @@ -26,7 +22,8 @@ // snippet-end:[kinesis.java2.stream_example.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -35,7 +32,8 @@ public class KinesisStreamEx { /** - * Creates a SubscribeToShardResponseHandler using the builder which lets you set each lifecycle callback separately + * Creates a SubscribeToShardResponseHandler using the builder which lets you + * set each lifecycle callback separately * rather than implementing the interface. */ @@ -47,86 +45,95 @@ public static void main(String[] args) { // snippet-start:[kinesis.java2.stream_example.setup] Region region = Region.US_EAST_1; KinesisAsyncClient client = KinesisAsyncClient.builder() - .region(region) - .build(); + .region(region) + .build(); SubscribeToShardRequest request = SubscribeToShardRequest.builder() - .consumerARN(CONSUMER_ARN) - .shardId("arn:aws:kinesis:us-east-1:111122223333:stream/StockTradeStream") - .startingPosition(s -> s.type(ShardIteratorType.LATEST)).build(); + .consumerARN(CONSUMER_ARN) + .shardId("arn:aws:kinesis:us-east-1:111122223333:stream/StockTradeStream") + .startingPosition(s -> s.type(ShardIteratorType.LATEST)).build(); // snippet-end:[kinesis.java2.stream_example.setup] SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler - .builder() - .onError(t -> System.err.println("Error during stream - " + t.getMessage())) - .subscriber(MySubscriber::new) - .build(); + .builder() + .onError(t -> System.err.println("Error during stream - " + t.getMessage())) + .subscriber(MySubscriber::new) + .build(); client.subscribeToShard(request, responseHandler); client.close(); } // snippet-start:[kinesis.java2.stream_example.lifecycle_callback] - private static CompletableFuture responseHandlerBuilder(KinesisAsyncClient client, SubscribeToShardRequest request) { + private static CompletableFuture responseHandlerBuilder(KinesisAsyncClient client, + SubscribeToShardRequest request) { SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler.builder() - .onError(t -> System.err.println("Error during stream - " + t.getMessage())) - .onComplete(() -> System.out.println("All records stream successfully")) - // Must supply some type of subscriber - .subscriber(e -> System.out.println("Received event - " + e)) - .build(); + .onError(t -> System.err.println("Error during stream - " + t.getMessage())) + .onComplete(() -> System.out.println("All records stream successfully")) + // Must supply some type of subscriber + .subscriber(e -> System.out.println("Received event - " + e)) + .build(); return client.subscribeToShard(request, responseHandler); } // snippet-end:[kinesis.java2.stream_example.lifecycle_callback] /** - * Using the SubscribeToShardResponseHandler.Builder and a simple Consumer of events to subscribe. + * Using the SubscribeToShardResponseHandler.Builder and a simple Consumer of + * events to subscribe. */ - private static CompletableFuture responseHandlerBuilderConsumer(KinesisAsyncClient client, SubscribeToShardRequest request) { + private static CompletableFuture responseHandlerBuilderConsumer(KinesisAsyncClient client, + SubscribeToShardRequest request) { SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler.builder() - .onError(t -> System.err.println("Error during stream - " + t.getMessage())) - .subscriber(e -> System.out.println("Received event - " + e)) - .build(); + .onError(t -> System.err.println("Error during stream - " + t.getMessage())) + .subscriber(e -> System.out.println("Received event - " + e)) + .build(); return client.subscribeToShard(request, responseHandler); } /** - * Uses the publisherTransformer method to customize the publisher before ultimately subscribing to it. + * Uses the publisherTransformer method to customize the publisher before + * ultimately subscribing to it. */ // snippet-start:[kinesis.java2.stream_example.publish_transformer] - private static CompletableFuture responseHandlerBuilderPublisherTransformer(KinesisAsyncClient client, SubscribeToShardRequest request) { + private static CompletableFuture responseHandlerBuilderPublisherTransformer(KinesisAsyncClient client, + SubscribeToShardRequest request) { SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler.builder() - .onError(t -> System.err.println("Error during stream - " + t.getMessage())) - .publisherTransformer(p -> p.filter(e -> e instanceof SubscribeToShardEvent).limit(100)) - .subscriber(e -> System.out.println("Received event - " + e)) - .build(); + .onError(t -> System.err.println("Error during stream - " + t.getMessage())) + .publisherTransformer(p -> p.filter(e -> e instanceof SubscribeToShardEvent).limit(100)) + .subscriber(e -> System.out.println("Received event - " + e)) + .build(); return client.subscribeToShard(request, responseHandler); } // snippet-end:[kinesis.java2.stream_example.publish_transformer] /** - * Creates a SubscribeToShardResponseHandler.Visitor using the builder which lets you register an event handler for + * Creates a SubscribeToShardResponseHandler.Visitor using the builder which + * lets you register an event handler for * all events you're interested in rather than implementing the interface. */ // snippet-start:[kinesis.java2.stream_example.visitor] - private static CompletableFuture responseHandlerBuilderVisitorBuilder(KinesisAsyncClient client, SubscribeToShardRequest request) { + private static CompletableFuture responseHandlerBuilderVisitorBuilder(KinesisAsyncClient client, + SubscribeToShardRequest request) { SubscribeToShardResponseHandler.Visitor visitor = SubscribeToShardResponseHandler.Visitor - .builder() - .onSubscribeToShardEvent(e -> System.out.println("Received subscribe to shard event " + e)) - .build(); + .builder() + .onSubscribeToShardEvent(e -> System.out.println("Received subscribe to shard event " + e)) + .build(); SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler - .builder() - .onError(t -> System.err.println("Error during stream - " + t.getMessage())) - .subscriber(visitor) - .build(); + .builder() + .onError(t -> System.err.println("Error during stream - " + t.getMessage())) + .subscriber(visitor) + .build(); return client.subscribeToShard(request, responseHandler); } // snippet-end:[kinesis.java2.stream_example.visitor] /** - * Subscribes to the stream of events by implementing the SubscribeToShardResponseHandler.Visitor interface. + * Subscribes to the stream of events by implementing the + * SubscribeToShardResponseHandler.Visitor interface. */ - private static CompletableFuture responseHandlerBuilderVisitor(KinesisAsyncClient client, SubscribeToShardRequest request) { + private static CompletableFuture responseHandlerBuilderVisitor(KinesisAsyncClient client, + SubscribeToShardRequest request) { SubscribeToShardResponseHandler.Visitor visitor = new SubscribeToShardResponseHandler.Visitor() { @Override public void visit(SubscribeToShardEvent event) { @@ -134,18 +141,20 @@ public void visit(SubscribeToShardEvent event) { } }; SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler - .builder() - .onError(t -> System.err.println("Error during stream - " + t.getMessage())) - .subscriber(visitor) - .build(); + .builder() + .onError(t -> System.err.println("Error during stream - " + t.getMessage())) + .subscriber(visitor) + .build(); return client.subscribeToShard(request, responseHandler); } /** - * Creates a SubscribeToShardResponseHandler the classic way by implementing the interface. + * Creates a SubscribeToShardResponseHandler the classic way by implementing the + * interface. */ // snippet-start:[kinesis.java2.stream_example.custom_handler] - private static CompletableFuture responseHandlerBuilderClassic(KinesisAsyncClient client, SubscribeToShardRequest request) { + private static CompletableFuture responseHandlerBuilderClassic(KinesisAsyncClient client, + SubscribeToShardRequest request) { SubscribeToShardResponseHandler responseHandler = new SubscribeToShardResponseHandler() { @Override @@ -183,10 +192,12 @@ public void exceptionOccurred(Throwable throwable) { // snippet-end:[kinesis.java2.stream_example.custom_handler] /** - * Using the SubscribeToShardResponseHandler.Builder and a traditional subscriber. + * Using the SubscribeToShardResponseHandler.Builder and a traditional + * subscriber. */ // snippet-start:[kinesis.java2.stream_example.subscribe] - private static CompletableFuture responseHandlerBuilderSubscriber(KinesisAsyncClient client, SubscribeToShardRequest request) { + private static CompletableFuture responseHandlerBuilderSubscriber(KinesisAsyncClient client, + SubscribeToShardRequest request) { SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler .builder() .onError(t -> System.err.println("Error during stream - " + t.getMessage())) @@ -197,10 +208,13 @@ private static CompletableFuture responseHandlerBuilderSubscriber(KinesisA // snippet-end:[kinesis.java2.stream_example.subscribe] /** - * Subscribes to the publisher using the onEventStream lifecycle callback method. This allows for greater control - * over the publisher and allows for transformation methods on the publisher like map and buffer. + * Subscribes to the publisher using the onEventStream lifecycle callback + * method. This allows for greater control + * over the publisher and allows for transformation methods on the publisher + * like map and buffer. */ - private static CompletableFuture responseHandlerBuilderOnEventStream(KinesisAsyncClient client, SubscribeToShardRequest request) { + private static CompletableFuture responseHandlerBuilderOnEventStream(KinesisAsyncClient client, + SubscribeToShardRequest request) { SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler .builder() .onError(t -> System.err.println("Error during stream - " + t.getMessage())) @@ -210,7 +224,8 @@ private static CompletableFuture responseHandlerBuilderOnEventStream(Kines } /** - * Simple subscriber implementation that prints events and cancels the subscription after 100 events. + * Simple subscriber implementation that prints events and cancels the + * subscription after 100 events. */ // snippet-start:[kinesis.java2.stream_example.custom_subscriber] private static class MySubscriber implements Subscriber { @@ -228,7 +243,8 @@ public void onSubscribe(Subscription subscription) { public void onNext(SubscribeToShardEventStream shardSubscriptionEventStream) { System.out.println("Received event " + shardSubscriptionEventStream); if (eventCount.incrementAndGet() >= 100) { - // You can cancel the subscription at any time if you wish to stop receiving events. + // You can cancel the subscription at any time if you wish to stop receiving + // events. subscription.cancel(); } subscription.request(1); diff --git a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/KinesisStreamReactorEx.java b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/KinesisStreamReactorEx.java index a7fd19be047..ac1c4ce2997 100755 --- a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/KinesisStreamReactorEx.java +++ b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/KinesisStreamReactorEx.java @@ -1,24 +1,5 @@ -//snippet-sourcedescription:[KinesisStreamReactorEx.java demonstrates how to use the Reactor library to simplify processing of Amazon Kinesis streams.] -//snippet-keyword:[SDK for Java 2.0] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon Kinesis] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[3/5/2020] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 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. - * You may obtain a copy of the License at: - * - * http://aws.amazon.com/apache2.0 - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES - * OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and - * limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kinesis; // snippet-start:[kinesis.java2.stream_reactor_example.import] @@ -42,56 +23,59 @@ // snippet-start:[kinesis.java2.stream_reactor_example.main] public class KinesisStreamReactorEx { - private static final String CONSUMER_ARN = "arn:aws:kinesis:us-east-1:1234567890:stream/stream-name/consumer/consumer-name:1234567890"; + private static final String CONSUMER_ARN = "arn:aws:kinesis:us-east-1:1234567890:stream/stream-name/consumer/consumer-name:1234567890"; - /** - * Uses Reactor via the onEventStream lifecycle method. This gives you full access to the publisher, which can be used - * to create a Flux. - */ - private static CompletableFuture responseHandlerBuilder_Reactor(KinesisAsyncClient client, SubscribeToShardRequest request) { + /** + * Uses Reactor via the onEventStream lifecycle method. This gives you full + * access to the publisher, which can be used + * to create a Flux. + */ + private static CompletableFuture responseHandlerBuilder_Reactor(KinesisAsyncClient client, + SubscribeToShardRequest request) { - SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler - .builder() - .onError(t -> System.err.println("Error during stream - " + t.getMessage())) - .onEventStream(p -> Flux.from(p) - .ofType(SubscribeToShardEvent.class) - .flatMapIterable(SubscribeToShardEvent::records) - .limitRate(1000) - .buffer(25) - .subscribe(e -> System.out.println("Record batch = " + e))) - .build(); - return client.subscribeToShard(request, responseHandler); + SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler + .builder() + .onError(t -> System.err.println("Error during stream - " + t.getMessage())) + .onEventStream(p -> Flux.from(p) + .ofType(SubscribeToShardEvent.class) + .flatMapIterable(SubscribeToShardEvent::records) + .limitRate(1000) + .buffer(25) + .subscribe(e -> System.out.println("Record batch = " + e))) + .build(); + return client.subscribeToShard(request, responseHandler); - } + } - /** - * Because a Flux is also a publisher, the publisherTransformer method integrates nicely with Reactor. Notice that - * you must adapt to an SdkPublisher. - */ - private static CompletableFuture responseHandlerBuilder_OnEventStream_Reactor(KinesisAsyncClient client, SubscribeToShardRequest request) { - SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler - .builder() - .onError(t -> System.err.println("Error during stream - " + t.getMessage())) - .publisherTransformer(p -> Flux.from(p).limitRate(100).as(SdkPublisher::adapt)) - .build(); - return client.subscribeToShard(request, responseHandler); - } + /** + * Because a Flux is also a publisher, the publisherTransformer method + * integrates nicely with Reactor. Notice that + * you must adapt to an SdkPublisher. + */ + private static CompletableFuture responseHandlerBuilder_OnEventStream_Reactor(KinesisAsyncClient client, + SubscribeToShardRequest request) { + SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler + .builder() + .onError(t -> System.err.println("Error during stream - " + t.getMessage())) + .publisherTransformer(p -> Flux.from(p).limitRate(100).as(SdkPublisher::adapt)) + .build(); + return client.subscribeToShard(request, responseHandler); + } - public static void main(String[] args) { + public static void main(String[] args) { - KinesisAsyncClient client = KinesisAsyncClient.create(); + KinesisAsyncClient client = KinesisAsyncClient.create(); - SubscribeToShardRequest request = SubscribeToShardRequest.builder() - .consumerARN(CONSUMER_ARN) - .shardId("shardId-000000000000") - .startingPosition(StartingPosition.builder().type(ShardIteratorType.LATEST).build()) - .build(); + SubscribeToShardRequest request = SubscribeToShardRequest.builder() + .consumerARN(CONSUMER_ARN) + .shardId("shardId-000000000000") + .startingPosition(StartingPosition.builder().type(ShardIteratorType.LATEST).build()) + .build(); - responseHandlerBuilder_Reactor(client, request).join(); + responseHandlerBuilder_Reactor(client, request).join(); - client.close(); - } + client.close(); + } } - -// snippet-end:[kinesis.java2.stream_reactor_example.main] +// snippet-end:[kinesis.java2.stream_reactor_example.main] diff --git a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/KinesisStreamRxJavaEx.java b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/KinesisStreamRxJavaEx.java index 4a93ca7f541..520d352d4cd 100755 --- a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/KinesisStreamRxJavaEx.java +++ b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/KinesisStreamRxJavaEx.java @@ -1,24 +1,5 @@ -//snippet-sourcedescription:[KinesisStreamRxJavaEx.java demonstrates how to use the Rx Java library to simplify processing of Amazon Kinesis streams.] -//snippet-keyword:[SDK for Java 2.0] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon Kinesis] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[3/5/2020] -//snippet-sourceauthor:[soo-aws] -/* - * Copyright 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. - * You may obtain a copy of the License at: - * - * http://aws.amazon.com/apache2.0 - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES - * OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and - * limitations under the License. - */ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kinesis; // snippet-start:[kinesis.java2.stream_rx_example.import] @@ -44,59 +25,61 @@ public class KinesisStreamRxJavaEx { - private static final String CONSUMER_ARN = "arn:aws:kinesis:us-east-1:1234567890:stream/stream-name/consumer/consumer-name:1234567890"; + private static final String CONSUMER_ARN = "arn:aws:kinesis:us-east-1:1234567890:stream/stream-name/consumer/consumer-name:1234567890"; - /** - * Uses RxJava via the onEventStream lifecycle method. This gives you full access to the publisher, which can be used - * to create an Rx Flowable. - */ - private static CompletableFuture responseHandlerBuilder_RxJava(KinesisAsyncClient client, SubscribeToShardRequest request) { + /** + * Uses RxJava via the onEventStream lifecycle method. This gives you full + * access to the publisher, which can be used + * to create an Rx Flowable. + */ + private static CompletableFuture responseHandlerBuilder_RxJava(KinesisAsyncClient client, + SubscribeToShardRequest request) { - // snippet-start:[kinesis.java2.stream_rx_example.event_stream] - SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler - .builder() - .onError(t -> System.err.println("Error during stream - " + t.getMessage())) - .onEventStream(p -> Flowable.fromPublisher(p) - .ofType(SubscribeToShardEvent.class) - .flatMapIterable(SubscribeToShardEvent::records) - .limit(1000) - .buffer(25) - .subscribe(e -> System.out.println("Record batch = " + e))) - .build(); - // snippet-end:[kinesis.java2.stream_rx_example.event_stream] - return client.subscribeToShard(request, responseHandler); + // snippet-start:[kinesis.java2.stream_rx_example.event_stream] + SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler + .builder() + .onError(t -> System.err.println("Error during stream - " + t.getMessage())) + .onEventStream(p -> Flowable.fromPublisher(p) + .ofType(SubscribeToShardEvent.class) + .flatMapIterable(SubscribeToShardEvent::records) + .limit(1000) + .buffer(25) + .subscribe(e -> System.out.println("Record batch = " + e))) + .build(); + // snippet-end:[kinesis.java2.stream_rx_example.event_stream] + return client.subscribeToShard(request, responseHandler); - } + } - /** - * Because a Flowable is also a publisher, the publisherTransformer method integrates nicely with RxJava. Notice that - * you must adapt to an SdkPublisher. - */ - private static CompletableFuture responseHandlerBuilder_OnEventStream_RxJava(KinesisAsyncClient client, SubscribeToShardRequest request) { - // snippet-start:[kinesis.java2.stream_rx_example.publish_transform] - SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler - .builder() - .onError(t -> System.err.println("Error during stream - " + t.getMessage())) - .publisherTransformer(p -> SdkPublisher.adapt(Flowable.fromPublisher(p).limit(100))) - .build(); - // snippet-end:[kinesis.java2.stream_rx_example.publish_transform] - return client.subscribeToShard(request, responseHandler); - } + /** + * Because a Flowable is also a publisher, the publisherTransformer method + * integrates nicely with RxJava. Notice that + * you must adapt to an SdkPublisher. + */ + private static CompletableFuture responseHandlerBuilder_OnEventStream_RxJava(KinesisAsyncClient client, + SubscribeToShardRequest request) { + // snippet-start:[kinesis.java2.stream_rx_example.publish_transform] + SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler + .builder() + .onError(t -> System.err.println("Error during stream - " + t.getMessage())) + .publisherTransformer(p -> SdkPublisher.adapt(Flowable.fromPublisher(p).limit(100))) + .build(); + // snippet-end:[kinesis.java2.stream_rx_example.publish_transform] + return client.subscribeToShard(request, responseHandler); + } - public static void main(String[] args) { + public static void main(String[] args) { - KinesisAsyncClient client = KinesisAsyncClient.create(); + KinesisAsyncClient client = KinesisAsyncClient.create(); - SubscribeToShardRequest request = SubscribeToShardRequest.builder() - .consumerARN(CONSUMER_ARN) - .shardId("shardId-000000000000") - .startingPosition(StartingPosition.builder().type(ShardIteratorType.LATEST).build()) - .build(); + SubscribeToShardRequest request = SubscribeToShardRequest.builder() + .consumerARN(CONSUMER_ARN) + .shardId("shardId-000000000000") + .startingPosition(StartingPosition.builder().type(ShardIteratorType.LATEST).build()) + .build(); - responseHandlerBuilder_RxJava(client, request).join(); + responseHandlerBuilder_RxJava(client, request).join(); - client.close(); - } + client.close(); + } } - - diff --git a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/ListShards.java b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/ListShards.java index 10d86d03036..170e7d546c9 100644 --- a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/ListShards.java +++ b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/ListShards.java @@ -1,24 +1,20 @@ -//snippet-sourcedescription:[ListShards.java demonstrates how to list the shards in an Amazon Kinesis data stream.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Kinesis] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kinesis; // snippet-start:[kinesis.java2.ListShards.main] -//snippet-start:[kinesis.java2.ListShards.import] +// snippet-start:[kinesis.java2.ListShards.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kinesis.KinesisClient; import software.amazon.awssdk.services.kinesis.model.KinesisException; import software.amazon.awssdk.services.kinesis.model.ListShardsRequest; import software.amazon.awssdk.services.kinesis.model.ListShardsResponse; -//snippet-end:[kinesis.java2.ListShards.import] +// snippet-end:[kinesis.java2.ListShards.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,13 +25,13 @@ public class ListShards { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - streamName - The Amazon Kinesis data stream (for example, StockTradeStream) + Where: + streamName - The Amazon Kinesis data stream (for example, StockTradeStream) - """; + """; if (args.length != 1) { System.out.println(usage); @@ -46,8 +42,8 @@ public static void main(String[] args) { // snippet-start:[kinesis.java2.ListShards.client] Region region = Region.US_EAST_1; KinesisClient kinesisClient = KinesisClient.builder() - .region(region) - .build(); + .region(region) + .build(); // snippet-end:[kinesis.java2.ListShards.client] listKinShards(kinesisClient, name); @@ -57,8 +53,8 @@ public static void main(String[] args) { public static void listKinShards(KinesisClient kinesisClient, String name) { try { ListShardsRequest request = ListShardsRequest.builder() - .streamName(name) - .build(); + .streamName(name) + .build(); ListShardsResponse response = kinesisClient.listShards(request); System.out.println(request.streamName() + " has " + response.shards()); diff --git a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/RegisterStreamConsumer.java b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/RegisterStreamConsumer.java index fadc48b8e5d..60049ee0077 100644 --- a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/RegisterStreamConsumer.java +++ b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/RegisterStreamConsumer.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[ListShards.java demonstrates how to register a consumer with a Kinesis data stream.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Kinesis] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kinesis; @@ -16,7 +11,8 @@ import software.amazon.awssdk.services.kinesis.model.RegisterStreamConsumerResponse; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -26,12 +22,12 @@ public class RegisterStreamConsumer { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - streamARN - The Amazon Kinesis data stream (for example, arn:aws:kinesis:us-east-1:814548xxxxxx:stream/LamDataStream) - """; + Where: + streamARN - The Amazon Kinesis data stream (for example, arn:aws:kinesis:us-east-1:814548xxxxxx:stream/LamDataStream) + """; if (args.length != 1) { System.out.println(usage); @@ -41,20 +37,20 @@ public static void main(String[] args) { String streamARN = args[0]; Region region = Region.US_EAST_1; KinesisClient kinesisClient = KinesisClient.builder() - .region(region) - .build(); + .region(region) + .build(); - String arnValue = regConsumer(kinesisClient, streamARN); - System.out.println(arnValue); - kinesisClient.close(); + String arnValue = regConsumer(kinesisClient, streamARN); + System.out.println(arnValue); + kinesisClient.close(); } public static String regConsumer(KinesisClient kinesisClient, String streamARN) { try { RegisterStreamConsumerRequest regCon = RegisterStreamConsumerRequest.builder() - .consumerName("MyConsumer") - .streamARN(streamARN) - .build(); + .consumerName("MyConsumer") + .streamARN(streamARN) + .build(); RegisterStreamConsumerResponse resp = kinesisClient.registerStreamConsumer(regCon); return resp.consumer().consumerARN(); diff --git a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/StockTrade.java b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/StockTrade.java index f0603fad6a4..c11f939ccf5 100644 --- a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/StockTrade.java +++ b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/StockTrade.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[StockTrade.java is a helper class.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Kinesis] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kinesis; @@ -14,7 +9,8 @@ /** * Captures the key elements of a stock trade, such as the ticker symbol, price, - * number of shares, the type of the trade (buy or sell), and an id uniquely identifying + * number of shares, the type of the trade (buy or sell), and an id uniquely + * identifying * the trade. */ public class StockTrade { diff --git a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/StockTradeGenerator.java b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/StockTradeGenerator.java index bb335733a5a..8e87e8f6b35 100644 --- a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/StockTradeGenerator.java +++ b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/StockTradeGenerator.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[StockTrade.java is a helper class.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Kinesis] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kinesis; @@ -15,7 +9,8 @@ import java.util.concurrent.atomic.AtomicLong; /** - * Generates random stock trades by picking randomly from a collection of stocks, assigning a + * Generates random stock trades by picking randomly from a collection of + * stocks, assigning a * random price based on the mean, and picking a random quantity for the shares. * */ diff --git a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/StockTradesWriter.java b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/StockTradesWriter.java index af373b169b5..e8aee90d7c1 100644 --- a/javav2/example_code/kinesis/src/main/java/com/example/kinesis/StockTradesWriter.java +++ b/javav2/example_code/kinesis/src/main/java/com/example/kinesis/StockTradesWriter.java @@ -1,16 +1,10 @@ -//snippet-sourcedescription:[StockTradesWriter.java demonstrates how to write multiple data records into an Amazon Kinesis data stream.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Kinesis] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kinesis; // snippet-start:[kinesis.java2.putrecord.main] -//snippet-start:[kinesis.java2.putrecord.import] +// snippet-start:[kinesis.java2.putrecord.import] import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kinesis.KinesisClient; @@ -18,10 +12,11 @@ import software.amazon.awssdk.services.kinesis.model.KinesisException; import software.amazon.awssdk.services.kinesis.model.DescribeStreamRequest; import software.amazon.awssdk.services.kinesis.model.DescribeStreamResponse; -//snippet-end:[kinesis.java2.putrecord.import] +// snippet-end:[kinesis.java2.putrecord.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,12 +26,12 @@ public class StockTradesWriter { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - streamName - The Amazon Kinesis data stream to which records are written (for example, StockTradeStream) - """; + Where: + streamName - The Amazon Kinesis data stream to which records are written (for example, StockTradeStream) + """; if (args.length != 1) { System.out.println(usage); @@ -46,8 +41,8 @@ public static void main(String[] args) { String streamName = args[0]; Region region = Region.US_EAST_1; KinesisClient kinesisClient = KinesisClient.builder() - .region(region) - .build(); + .region(region) + .build(); // Ensure that the Kinesis Stream is valid. validateStream(kinesisClient, streamName); @@ -76,10 +71,11 @@ public static void setStockData(KinesisClient kinesisClient, String streamName) } private static void sendStockTrade(StockTrade trade, KinesisClient kinesisClient, - String streamName) { + String streamName) { byte[] bytes = trade.toJsonAsBytes(); - // The bytes could be null if there is an issue with the JSON serialization by the Jackson JSON library. + // The bytes could be null if there is an issue with the JSON serialization by + // the Jackson JSON library. if (bytes == null) { System.out.println("Could not get JSON bytes for stock trade"); return; @@ -87,10 +83,11 @@ private static void sendStockTrade(StockTrade trade, KinesisClient kinesisClient System.out.println("Putting trade: " + trade); PutRecordRequest request = PutRecordRequest.builder() - .partitionKey(trade.getTickerSymbol()) // We use the ticker symbol as the partition key, explained in the Supplemental Information section below. - .streamName(streamName) - .data(SdkBytes.fromByteArray(bytes)) - .build(); + .partitionKey(trade.getTickerSymbol()) // We use the ticker symbol as the partition key, explained in + // the Supplemental Information section below. + .streamName(streamName) + .data(SdkBytes.fromByteArray(bytes)) + .build(); try { kinesisClient.putRecord(request); @@ -102,8 +99,8 @@ private static void sendStockTrade(StockTrade trade, KinesisClient kinesisClient private static void validateStream(KinesisClient kinesisClient, String streamName) { try { DescribeStreamRequest describeStreamRequest = DescribeStreamRequest.builder() - .streamName(streamName) - .build(); + .streamName(streamName) + .build(); DescribeStreamResponse describeStreamResponse = kinesisClient.describeStream(describeStreamRequest); diff --git a/javav2/example_code/kinesis/src/test/java/KinTest.java b/javav2/example_code/kinesis/src/test/java/KinTest.java index a8b648c0189..906158fd909 100644 --- a/javav2/example_code/kinesis/src/test/java/KinTest.java +++ b/javav2/example_code/kinesis/src/test/java/KinTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.kinesis.CreateDataStream; import com.example.kinesis.DescribeLimits; @@ -22,17 +20,17 @@ public class KinTest { @BeforeAll public static void setUp() { kinesisClient = KinesisClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); - streamName = "streamName"+ java.util.UUID.randomUUID(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); + streamName = "streamName" + java.util.UUID.randomUUID(); } @Test @Tag("IntegrationTest") @Order(1) public void CreateDataStream() { - assertDoesNotThrow(() ->CreateDataStream.createStream(kinesisClient, streamName)); + assertDoesNotThrow(() -> CreateDataStream.createStream(kinesisClient, streamName)); System.out.println("Test 1 passed"); } @@ -40,7 +38,7 @@ public void CreateDataStream() { @Tag("IntegrationTest") @Order(2) public void DescribeLimits() { - assertDoesNotThrow(() ->DescribeLimits.describeKinLimits(kinesisClient)); + assertDoesNotThrow(() -> DescribeLimits.describeKinLimits(kinesisClient)); System.out.println("Test 2 passed"); } @@ -49,9 +47,9 @@ public void DescribeLimits() { @Order(3) public void ListShards() { try { - //Wait 60 secs for table to complete + // Wait 60 secs for table to complete TimeUnit.SECONDS.sleep(60); - assertDoesNotThrow(() ->ListShards.listKinShards(kinesisClient, streamName)); + assertDoesNotThrow(() -> ListShards.listKinShards(kinesisClient, streamName)); } catch (InterruptedException e) { System.err.println(e.getMessage()); System.exit(1); @@ -63,7 +61,7 @@ public void ListShards() { @Tag("IntegrationTest") @Order(4) public void PutRecords() { - assertDoesNotThrow(() ->StockTradesWriter.setStockData(kinesisClient, streamName)); + assertDoesNotThrow(() -> StockTradesWriter.setStockData(kinesisClient, streamName)); System.out.println("Test 4 passed"); } @@ -71,7 +69,7 @@ public void PutRecords() { @Tag("IntegrationTest") @Order(5) public void GetRecords() { - assertDoesNotThrow(() ->GetRecords.getStockTrades(kinesisClient, streamName)); + assertDoesNotThrow(() -> GetRecords.getStockTrades(kinesisClient, streamName)); System.out.println("Test 5 passed"); } @@ -79,7 +77,7 @@ public void GetRecords() { @Tag("IntegrationTest") @Order(6) public void DeleteDataStreem() { - assertDoesNotThrow(() ->DeleteDataStream.deleteStream(kinesisClient, streamName)); + assertDoesNotThrow(() -> DeleteDataStream.deleteStream(kinesisClient, streamName)); System.out.println("Test 6 passed"); } } diff --git a/javav2/example_code/kms/src/main/java/com/example/kms/CreateAlias.java b/javav2/example_code/kms/src/main/java/com/example/kms/CreateAlias.java index d9f83e84c3c..bd7e8e799c3 100644 --- a/javav2/example_code/kms/src/main/java/com/example/kms/CreateAlias.java +++ b/javav2/example_code/kms/src/main/java/com/example/kms/CreateAlias.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[CreateAlias.java demonstrates how to create an AWS Key Management Service (AWS KMS) alias.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Key Management Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kms; @@ -18,7 +12,8 @@ // snippet-end:[kms.java2_create_alias.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,13 +24,13 @@ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - targetKeyId - The key ID or the Amazon Resource Name (ARN) of the customer master key (CMK).\s - aliasName - An alias name (for example, alias/myAlias).\s - """; + Where: + targetKeyId - The key ID or the Amazon Resource Name (ARN) of the customer master key (CMK).\s + aliasName - An alias name (for example, alias/myAlias).\s + """; if (args.length != 2) { System.out.println(usage); @@ -46,8 +41,8 @@ public static void main(String[] args) { String aliasName = args[1]; Region region = Region.US_WEST_2; KmsClient kmsClient = KmsClient.builder() - .region(region) - .build(); + .region(region) + .build(); createCustomAlias(kmsClient, targetKeyId, aliasName); kmsClient.close(); @@ -56,9 +51,9 @@ public static void main(String[] args) { public static void createCustomAlias(KmsClient kmsClient, String targetKeyId, String aliasName) { try { CreateAliasRequest aliasRequest = CreateAliasRequest.builder() - .aliasName(aliasName) - .targetKeyId(targetKeyId) - .build(); + .aliasName(aliasName) + .targetKeyId(targetKeyId) + .build(); kmsClient.createAlias(aliasRequest); diff --git a/javav2/example_code/kms/src/main/java/com/example/kms/CreateCustomerKey.java b/javav2/example_code/kms/src/main/java/com/example/kms/CreateCustomerKey.java index fcbb58474f4..f96b56cbadd 100644 --- a/javav2/example_code/kms/src/main/java/com/example/kms/CreateCustomerKey.java +++ b/javav2/example_code/kms/src/main/java/com/example/kms/CreateCustomerKey.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[CreateCustomerKey.java demonstrates how to create an AWS Key Management Service (AWS KMS) key.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Key Management Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kms; @@ -20,7 +14,8 @@ // snippet-end:[kms.java2_create_key.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,8 +25,8 @@ public class CreateCustomerKey { public static void main(String[] args) { Region region = Region.US_WEST_2; KmsClient kmsClient = KmsClient.builder() - .region(region) - .build(); + .region(region) + .build(); String keyDesc = "Created by the AWS KMS API"; System.out.println("The key id is " + createKey(kmsClient, keyDesc)); @@ -41,10 +36,10 @@ public static void main(String[] args) { public static String createKey(KmsClient kmsClient, String keyDesc) { try { CreateKeyRequest keyRequest = CreateKeyRequest.builder() - .description(keyDesc) - .customerMasterKeySpec(CustomerMasterKeySpec.SYMMETRIC_DEFAULT) - .keyUsage("ENCRYPT_DECRYPT") - .build(); + .description(keyDesc) + .customerMasterKeySpec(CustomerMasterKeySpec.SYMMETRIC_DEFAULT) + .keyUsage("ENCRYPT_DECRYPT") + .build(); CreateKeyResponse result = kmsClient.createKey(keyRequest); System.out.printf("Created a customer key with id \"%s\"%n", result.keyMetadata().arn()); diff --git a/javav2/example_code/kms/src/main/java/com/example/kms/CreateGrant.java b/javav2/example_code/kms/src/main/java/com/example/kms/CreateGrant.java index 6a84ca4c52f..b513ace8994 100644 --- a/javav2/example_code/kms/src/main/java/com/example/kms/CreateGrant.java +++ b/javav2/example_code/kms/src/main/java/com/example/kms/CreateGrant.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[CreateGrant.java demonstrates how to add a grant to a customer master key (CMK).] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Key Management Service] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.kms; // snippet-start:[kms.java2_create_grant.main] @@ -18,7 +13,8 @@ // snippet-end:[kms.java2_create_grant.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,14 +24,14 @@ public class CreateGrant { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - keyId - The unique identifier for the customer master key (CMK) that the grant applies to.\s - granteePrincipal - The principal that is given permission to perform the operations that the grant permits.\s - operation - An operation (for example, Encrypt).\s - """; + Where: + keyId - The unique identifier for the customer master key (CMK) that the grant applies to.\s + granteePrincipal - The principal that is given permission to perform the operations that the grant permits.\s + operation - An operation (for example, Encrypt).\s + """; if (args.length != 3) { System.out.println(usage); @@ -47,8 +43,8 @@ public static void main(String[] args) { String operation = args[2]; Region region = Region.US_WEST_2; KmsClient kmsClient = KmsClient.builder() - .region(region) - .build(); + .region(region) + .build(); String grantId = createGrant(kmsClient, keyId, granteePrincipal, operation); System.out.printf("Successfully created a grant with ID %s%n", grantId); @@ -58,10 +54,10 @@ public static void main(String[] args) { public static String createGrant(KmsClient kmsClient, String keyId, String granteePrincipal, String operation) { try { CreateGrantRequest grantRequest = CreateGrantRequest.builder() - .keyId(keyId) - .granteePrincipal(granteePrincipal) - .operationsWithStrings(operation) - .build(); + .keyId(keyId) + .granteePrincipal(granteePrincipal) + .operationsWithStrings(operation) + .build(); CreateGrantResponse response = kmsClient.createGrant(grantRequest); return response.grantId(); diff --git a/javav2/example_code/kms/src/main/java/com/example/kms/DeleteAlias.java b/javav2/example_code/kms/src/main/java/com/example/kms/DeleteAlias.java index d8906508f9f..1411ac41137 100644 --- a/javav2/example_code/kms/src/main/java/com/example/kms/DeleteAlias.java +++ b/javav2/example_code/kms/src/main/java/com/example/kms/DeleteAlias.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DeleteAlias.java demonstrates how to delete an AWS Key Management Service (AWS KMS) alias.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Key Management Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kms; @@ -18,7 +12,8 @@ // snippet-end:[kms.java2_delete_alias.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +23,12 @@ public class DeleteAlias { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - aliasName - An alias name to delete (for example, alias/myAlias).\s - """; + Where: + aliasName - An alias name to delete (for example, alias/myAlias).\s + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +38,8 @@ public static void main(String[] args) { String aliasName = args[0]; Region region = Region.US_WEST_2; KmsClient kmsClient = KmsClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteSpecificAlias(kmsClient, aliasName); kmsClient.close(); @@ -53,8 +48,8 @@ public static void main(String[] args) { public static void deleteSpecificAlias(KmsClient kmsClient, String aliasName) { try { DeleteAliasRequest deleteAliasRequest = DeleteAliasRequest.builder() - .aliasName(aliasName) - .build(); + .aliasName(aliasName) + .build(); kmsClient.deleteAlias(deleteAliasRequest); diff --git a/javav2/example_code/kms/src/main/java/com/example/kms/DescribeKey.java b/javav2/example_code/kms/src/main/java/com/example/kms/DescribeKey.java index b28976d1e01..e9e1f566f2d 100644 --- a/javav2/example_code/kms/src/main/java/com/example/kms/DescribeKey.java +++ b/javav2/example_code/kms/src/main/java/com/example/kms/DescribeKey.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeKey.java demonstrates how to obtain information about an AWS Key Management Service (AWS KMS) key.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Key Management Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kms; @@ -19,7 +13,8 @@ // snippet-end:[kms.java2_describe_key.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,12 +24,12 @@ public class DescribeKey { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - keyId - A key id value to describe (for example, xxxxxbcd-12ab-34cd-56ef-1234567890ab).\s - """; + Where: + keyId - A key id value to describe (for example, xxxxxbcd-12ab-34cd-56ef-1234567890ab).\s + """; if (args.length != 1) { System.out.println(usage); @@ -44,8 +39,8 @@ public static void main(String[] args) { String keyId = args[0]; Region region = Region.US_WEST_2; KmsClient kmsClient = KmsClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeSpecifcKey(kmsClient, keyId); kmsClient.close(); @@ -54,8 +49,8 @@ public static void main(String[] args) { public static void describeSpecifcKey(KmsClient kmsClient, String keyId) { try { DescribeKeyRequest keyRequest = DescribeKeyRequest.builder() - .keyId(keyId) - .build(); + .keyId(keyId) + .build(); DescribeKeyResponse response = kmsClient.describeKey(keyRequest); System.out.println("The key description is " + response.keyMetadata().description()); diff --git a/javav2/example_code/kms/src/main/java/com/example/kms/DisableCustomerKey.java b/javav2/example_code/kms/src/main/java/com/example/kms/DisableCustomerKey.java index b4ff9185b30..17103efbde5 100644 --- a/javav2/example_code/kms/src/main/java/com/example/kms/DisableCustomerKey.java +++ b/javav2/example_code/kms/src/main/java/com/example/kms/DisableCustomerKey.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DisableCustomerKey.java demonstrates how to disable an AWS Key Management Service (AWS KMS) key.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Key Management Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kms; @@ -18,7 +12,8 @@ // snippet-end:[kms.java2_disable_key.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +23,12 @@ public class DisableCustomerKey { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - keyId - A key id value to disable (for example, xxxxxbcd-12ab-34cd-56ef-1234567890ab).\s - """; + Where: + keyId - A key id value to disable (for example, xxxxxbcd-12ab-34cd-56ef-1234567890ab).\s + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +38,8 @@ public static void main(String[] args) { String keyId = args[0]; Region region = Region.US_WEST_2; KmsClient kmsClient = KmsClient.builder() - .region(region) - .build(); + .region(region) + .build(); disableKey(kmsClient, keyId); kmsClient.close(); @@ -53,8 +48,8 @@ public static void main(String[] args) { public static void disableKey(KmsClient kmsClient, String keyId) { try { DisableKeyRequest keyRequest = DisableKeyRequest.builder() - .keyId(keyId) - .build(); + .keyId(keyId) + .build(); kmsClient.disableKey(keyRequest); diff --git a/javav2/example_code/kms/src/main/java/com/example/kms/EnableCustomerKey.java b/javav2/example_code/kms/src/main/java/com/example/kms/EnableCustomerKey.java index e634214d695..3bcdffd0527 100644 --- a/javav2/example_code/kms/src/main/java/com/example/kms/EnableCustomerKey.java +++ b/javav2/example_code/kms/src/main/java/com/example/kms/EnableCustomerKey.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[EnableCustomerKey.java demonstrates how to enable an AWS Key Management Service (AWS KMS) key.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Key Management Service] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.kms; // snippet-start:[kms.java2_enable_key.main] @@ -17,7 +12,8 @@ // snippet-end:[kms.java2_enable_key.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,12 +23,12 @@ public class EnableCustomerKey { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - keyId - A key id value to enable (for example, xxxxxbcd-12ab-34cd-56ef-1234567890ab).\s - """; + Where: + keyId - A key id value to enable (for example, xxxxxbcd-12ab-34cd-56ef-1234567890ab).\s + """; if (args.length != 1) { System.out.println(usage); @@ -42,8 +38,8 @@ public static void main(String[] args) { String keyId = args[0]; Region region = Region.US_WEST_2; KmsClient kmsClient = KmsClient.builder() - .region(region) - .build(); + .region(region) + .build(); enableKey(kmsClient, keyId); kmsClient.close(); @@ -52,8 +48,8 @@ public static void main(String[] args) { public static void enableKey(KmsClient kmsClient, String keyId) { try { EnableKeyRequest enableKeyRequest = EnableKeyRequest.builder() - .keyId(keyId) - .build(); + .keyId(keyId) + .build(); kmsClient.enableKey(enableKeyRequest); diff --git a/javav2/example_code/kms/src/main/java/com/example/kms/EncryptDataKey.java b/javav2/example_code/kms/src/main/java/com/example/kms/EncryptDataKey.java index 06465844b54..57a03f3a602 100644 --- a/javav2/example_code/kms/src/main/java/com/example/kms/EncryptDataKey.java +++ b/javav2/example_code/kms/src/main/java/com/example/kms/EncryptDataKey.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[EncryptDataKey.java demonstrates how to encrypt and decrypt data by using an AWS Key Management Service (KMS) key.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Key Management Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kms; @@ -22,7 +16,8 @@ // snippet-end:[kms.java2_encrypt_data.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,13 +27,13 @@ public class EncryptDataKey { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - keyId - A key id value to use to encrypt/decrypt the data (for example, xxxxxbcd-12ab-34cd-56ef-1234567890ab).\s + Where: + keyId - A key id value to use to encrypt/decrypt the data (for example, xxxxxbcd-12ab-34cd-56ef-1234567890ab).\s - """; + """; if (args.length != 1) { System.out.println(usage); @@ -48,8 +43,8 @@ public static void main(String[] args) { String keyId = args[0]; Region region = Region.US_WEST_2; KmsClient kmsClient = KmsClient.builder() - .region(region) - .build(); + .region(region) + .build(); SdkBytes encryData = encryptData(kmsClient, keyId); decryptData(kmsClient, encryData, keyId); @@ -57,36 +52,36 @@ public static void main(String[] args) { kmsClient.close(); } - public static SdkBytes encryptData(KmsClient kmsClient, String keyId) { - try { - SdkBytes myBytes = SdkBytes.fromByteArray(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}); - EncryptRequest encryptRequest = EncryptRequest.builder() - .keyId(keyId) - .plaintext(myBytes) - .build(); - - EncryptResponse response = kmsClient.encrypt(encryptRequest); - String algorithm = response.encryptionAlgorithm().toString(); - System.out.println("The encryption algorithm is " + algorithm); - - // Get the encrypted data. - SdkBytes encryptedData = response.ciphertextBlob(); - return encryptedData; - - } catch (KmsException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - return null; - } + public static SdkBytes encryptData(KmsClient kmsClient, String keyId) { + try { + SdkBytes myBytes = SdkBytes.fromByteArray(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }); + EncryptRequest encryptRequest = EncryptRequest.builder() + .keyId(keyId) + .plaintext(myBytes) + .build(); + + EncryptResponse response = kmsClient.encrypt(encryptRequest); + String algorithm = response.encryptionAlgorithm().toString(); + System.out.println("The encryption algorithm is " + algorithm); + + // Get the encrypted data. + SdkBytes encryptedData = response.ciphertextBlob(); + return encryptedData; + + } catch (KmsException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + return null; + } // snippet-start:[kms.java2_decrypt_data.main] public static void decryptData(KmsClient kmsClient, SdkBytes encryptedData, String keyId) { try { - DecryptRequest decryptRequest = DecryptRequest.builder() - .ciphertextBlob(encryptedData) - .keyId(keyId) - .build(); + DecryptRequest decryptRequest = DecryptRequest.builder() + .ciphertextBlob(encryptedData) + .keyId(keyId) + .build(); DecryptResponse decryptResponse = kmsClient.decrypt(decryptRequest); decryptResponse.plaintext(); diff --git a/javav2/example_code/kms/src/main/java/com/example/kms/ListAliases.java b/javav2/example_code/kms/src/main/java/com/example/kms/ListAliases.java index f7d5f3965a9..04147c4955b 100644 --- a/javav2/example_code/kms/src/main/java/com/example/kms/ListAliases.java +++ b/javav2/example_code/kms/src/main/java/com/example/kms/ListAliases.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[ListAliases.java demonstrates how to get a list of AWS Key Management Service (AWS KMS) aliases.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Key Management Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kms; @@ -21,7 +15,8 @@ // snippet-end:[kms.java2_list_aliases.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,8 +26,8 @@ public class ListAliases { public static void main(String[] args) { Region region = Region.US_WEST_2; KmsClient kmsClient = KmsClient.builder() - .region(region) - .build(); + .region(region) + .build(); listAllAliases(kmsClient); kmsClient.close(); @@ -41,8 +36,8 @@ public static void main(String[] args) { public static void listAllAliases(KmsClient kmsClient) { try { ListAliasesRequest aliasesRequest = ListAliasesRequest.builder() - .limit(15) - .build(); + .limit(15) + .build(); ListAliasesResponse aliasesResponse = kmsClient.listAliases(aliasesRequest); List aliases = aliasesResponse.aliases(); diff --git a/javav2/example_code/kms/src/main/java/com/example/kms/ListGrants.java b/javav2/example_code/kms/src/main/java/com/example/kms/ListGrants.java index 0f8c9b46276..7d1bfd36f6f 100644 --- a/javav2/example_code/kms/src/main/java/com/example/kms/ListGrants.java +++ b/javav2/example_code/kms/src/main/java/com/example/kms/ListGrants.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[ListGrants.java demonstrates how to get information about AWS Key Management Service (AWS KMS) grants related to a key.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Key Management Service] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.kms; // snippet-start:[kms.java2_list_grant.main] @@ -20,7 +15,8 @@ // snippet-end:[kms.java2_list_grant.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,12 +26,12 @@ public class ListGrants { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - keyId - a key id value to use (for example, xxxxxbcd-12ab-34cd-56ef-1234567890ab).\s - """; + Where: + keyId - a key id value to use (for example, xxxxxbcd-12ab-34cd-56ef-1234567890ab).\s + """; if (args.length != 1) { System.out.println(usage); @@ -45,8 +41,8 @@ public static void main(String[] args) { String keyId = args[0]; Region region = Region.US_WEST_2; KmsClient kmsClient = KmsClient.builder() - .region(region) - .build(); + .region(region) + .build(); displayGrantIds(kmsClient, keyId); kmsClient.close(); @@ -55,9 +51,9 @@ public static void main(String[] args) { public static void displayGrantIds(KmsClient kmsClient, String keyId) { try { ListGrantsRequest grantsRequest = ListGrantsRequest.builder() - .keyId(keyId) - .limit(15) - .build(); + .keyId(keyId) + .limit(15) + .build(); ListGrantsResponse response = kmsClient.listGrants(grantsRequest); List grants = response.grants(); diff --git a/javav2/example_code/kms/src/main/java/com/example/kms/ListKeys.java b/javav2/example_code/kms/src/main/java/com/example/kms/ListKeys.java index 575a4b94e39..d98808f10a8 100644 --- a/javav2/example_code/kms/src/main/java/com/example/kms/ListKeys.java +++ b/javav2/example_code/kms/src/main/java/com/example/kms/ListKeys.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[ListKeys.java demonstrates how to get a list of AWS Key Management Service (AWS KMS) keys.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Key Management Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kms; @@ -21,7 +15,8 @@ // snippet-end:[kms.java2_list_keys.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,8 +26,8 @@ public class ListKeys { public static void main(String[] args) { Region region = Region.US_WEST_2; KmsClient kmsClient = KmsClient.builder() - .region(region) - .build(); + .region(region) + .build(); listAllKeys(kmsClient); kmsClient.close(); @@ -41,8 +36,8 @@ public static void main(String[] args) { public static void listAllKeys(KmsClient kmsClient) { try { ListKeysRequest listKeysRequest = ListKeysRequest.builder() - .limit(15) - .build(); + .limit(15) + .build(); ListKeysResponse keysResponse = kmsClient.listKeys(listKeysRequest); List keyListEntries = keysResponse.keys(); diff --git a/javav2/example_code/kms/src/main/java/com/example/kms/RevokeGrant.java b/javav2/example_code/kms/src/main/java/com/example/kms/RevokeGrant.java index b90d286b12a..d6b99b4e36a 100644 --- a/javav2/example_code/kms/src/main/java/com/example/kms/RevokeGrant.java +++ b/javav2/example_code/kms/src/main/java/com/example/kms/RevokeGrant.java @@ -1,10 +1,6 @@ -//snippet-sourcedescription:[RevokeGrant.java demonstrates how to revoke a grant for the specified customer master key (CMK).] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Key Management Service] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.kms; // snippet-start:[kms.java2_revoke_grant.main] @@ -16,7 +12,8 @@ // snippet-end:[kms.java2_revoke_grant.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -26,13 +23,13 @@ public class RevokeGrant { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - keyId - A unique identifier for the customer master key associated with the grant (for example, xxxxxbcd-12ab-34cd-56ef-1234567890ab).\s - grantId - A grant id value of the grant revoke.\s - """; + Where: + keyId - A unique identifier for the customer master key associated with the grant (for example, xxxxxbcd-12ab-34cd-56ef-1234567890ab).\s + grantId - A grant id value of the grant revoke.\s + """; if (args.length != 2) { System.out.println(usage); @@ -43,8 +40,8 @@ public static void main(String[] args) { String grantId = args[1]; Region region = Region.US_WEST_2; KmsClient kmsClient = KmsClient.builder() - .region(region) - .build(); + .region(region) + .build(); revokeKeyGrant(kmsClient, keyId, grantId); kmsClient.close(); @@ -53,9 +50,9 @@ public static void main(String[] args) { public static void revokeKeyGrant(KmsClient kmsClient, String keyId, String grantId) { try { RevokeGrantRequest grantRequest = RevokeGrantRequest.builder() - .keyId(keyId) - .grantId(grantId) - .build(); + .keyId(keyId) + .grantId(grantId) + .build(); kmsClient.revokeGrant(grantRequest); @@ -65,4 +62,4 @@ public static void revokeKeyGrant(KmsClient kmsClient, String keyId, String gran } } } - // snippet-end:[kms.java2_revoke_grant.main] +// snippet-end:[kms.java2_revoke_grant.main] diff --git a/javav2/example_code/kms/src/main/java/com/example/kms/SetKeyPolicy.java b/javav2/example_code/kms/src/main/java/com/example/kms/SetKeyPolicy.java index 7b781ec75e5..80a34d3d39e 100644 --- a/javav2/example_code/kms/src/main/java/com/example/kms/SetKeyPolicy.java +++ b/javav2/example_code/kms/src/main/java/com/example/kms/SetKeyPolicy.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[SetKeyPolicy.java demonstrates how to set an AWS Key Management Service (AWS KMS) key policy.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Key Management Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.kms; @@ -18,7 +12,8 @@ // snippet-end:[kms.java2_set_policy.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,15 +24,15 @@ public class SetKeyPolicy { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - keyId - A unique identifier for the customer master key (CMK) (for example, xxxxxbcd-12ab-34cd-56ef-1234567890ab).\s + Where: + keyId - A unique identifier for the customer master key (CMK) (for example, xxxxxbcd-12ab-34cd-56ef-1234567890ab).\s - policyName - The name of the key policy.\s + policyName - The name of the key policy.\s - """; + """; if (args.length != 2) { System.out.println(usage); @@ -48,8 +43,8 @@ public static void main(String[] args) { String policyName = args[1]; Region region = Region.US_WEST_2; KmsClient kmsClient = KmsClient.builder() - .region(region) - .build(); + .region(region) + .build(); createPolicy(kmsClient, keyId, policyName); kmsClient.close(); @@ -57,21 +52,21 @@ public static void main(String[] args) { public static void createPolicy(KmsClient kmsClient, String keyId, String policyName) { String policy = "{" + - " \"Version\": \"2012-10-17\"," + - " \"Statement\": [{" + - " \"Effect\": \"Allow\"," + - // Replace the following user ARN with one for a real user. - " \"Principal\": {\"AWS\": \"arn:aws:iam::814548047983:root\"}," + - " \"Action\": \"kms:*\"," + - " \"Resource\": \"*\"" + - " }]" + - "}"; + " \"Version\": \"2012-10-17\"," + + " \"Statement\": [{" + + " \"Effect\": \"Allow\"," + + // Replace the following user ARN with one for a real user. + " \"Principal\": {\"AWS\": \"arn:aws:iam::814548047983:root\"}," + + " \"Action\": \"kms:*\"," + + " \"Resource\": \"*\"" + + " }]" + + "}"; try { PutKeyPolicyRequest keyPolicyRequest = PutKeyPolicyRequest.builder() - .keyId(keyId) - .policyName(policyName) - .policy(policy) - .build(); + .keyId(keyId) + .policyName(policyName) + .policy(policy) + .build(); kmsClient.putKeyPolicy(keyPolicyRequest); System.out.println("Done"); diff --git a/javav2/example_code/kms/src/test/java/AmazonKMSTest.java b/javav2/example_code/kms/src/test/java/AmazonKMSTest.java index 31795291479..6d2e47f7712 100644 --- a/javav2/example_code/kms/src/test/java/AmazonKMSTest.java +++ b/javav2/example_code/kms/src/test/java/AmazonKMSTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.kms.*; import com.google.gson.Gson; @@ -35,9 +33,9 @@ public class AmazonKMSTest { @BeforeAll public static void setUp() { kmsClient = KmsClient.builder() - .region(Region.US_WEST_2) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_WEST_2) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -48,26 +46,29 @@ public static void setUp() { aliasName = values.getAliasName(); granteePrincipal = values.getGranteePrincipal(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - try (InputStream input = AmazonKMSTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - // Populate the data members required for all tests. - prop.load(input); - keyDesc = prop.getProperty("keyDesc"); - operation = prop.getProperty("operation"); - aliasName = prop.getProperty("aliasName"); - granteePrincipal = prop.getProperty("granteePrincipal"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * try (InputStream input = + * AmazonKMSTest.class.getClassLoader().getResourceAsStream("config.properties") + * ) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * // Populate the data members required for all tests. + * prop.load(input); + * keyDesc = prop.getProperty("keyDesc"); + * operation = prop.getProperty("operation"); + * aliasName = prop.getProperty("aliasName"); + * granteePrincipal = prop.getProperty("granteePrincipal"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @@ -91,7 +92,7 @@ public void EncryptDataKey() { @Tag("IntegrationTest") @Order(3) public void DecryptDataKey() { - assertDoesNotThrow(() ->EncryptDataKey.decryptData(kmsClient, EncryptData, keyId)); + assertDoesNotThrow(() -> EncryptDataKey.decryptData(kmsClient, EncryptData, keyId)); System.out.println("Test 3 passed"); } @@ -99,7 +100,7 @@ public void DecryptDataKey() { @Tag("IntegrationTest") @Order(4) public void DisableCustomerKey() { - assertDoesNotThrow(() ->DisableCustomerKey.disableKey(kmsClient, keyId)); + assertDoesNotThrow(() -> DisableCustomerKey.disableKey(kmsClient, keyId)); System.out.println("Test 4 passed"); } @@ -107,7 +108,7 @@ public void DisableCustomerKey() { @Tag("IntegrationTest") @Order(5) public void EnableCustomerKey() { - assertDoesNotThrow(() ->EnableCustomerKey.enableKey(kmsClient, keyId)); + assertDoesNotThrow(() -> EnableCustomerKey.enableKey(kmsClient, keyId)); System.out.println("Test 5 passed"); } @@ -124,14 +125,14 @@ public void CreateGrant() { @Tag("IntegrationTest") @Order(7) public void ViewGrants() { - assertDoesNotThrow(() ->ListGrants.displayGrantIds(kmsClient, keyId)); + assertDoesNotThrow(() -> ListGrants.displayGrantIds(kmsClient, keyId)); System.out.println("Test 7 passed"); } @Test @Order(8) public void RevokeGrant() { - assertDoesNotThrow(() ->RevokeGrant.revokeKeyGrant(kmsClient, keyId, grantId)); + assertDoesNotThrow(() -> RevokeGrant.revokeKeyGrant(kmsClient, keyId, grantId)); System.out.println("Test 8 passed"); } @@ -139,14 +140,14 @@ public void RevokeGrant() { @Tag("IntegrationTest") @Order(9) public void DescribeKey() { - assertDoesNotThrow(() ->DescribeKey.describeSpecifcKey(kmsClient, keyId)); + assertDoesNotThrow(() -> DescribeKey.describeSpecifcKey(kmsClient, keyId)); System.out.println("Test 9 passed"); } @Test @Order(10) public void CreateAlias() { - assertDoesNotThrow(() ->CreateAlias.createCustomAlias(kmsClient, keyId, aliasName)); + assertDoesNotThrow(() -> CreateAlias.createCustomAlias(kmsClient, keyId, aliasName)); System.out.println("Test 10 passed"); } @@ -154,7 +155,7 @@ public void CreateAlias() { @Tag("IntegrationTest") @Order(11) public void ListAliases() { - assertDoesNotThrow(() ->ListAliases.listAllAliases(kmsClient)); + assertDoesNotThrow(() -> ListAliases.listAllAliases(kmsClient)); System.out.println("Test 11 passed"); } @@ -162,7 +163,7 @@ public void ListAliases() { @Tag("IntegrationTest") @Order(12) public void DeleteAlias() { - assertDoesNotThrow(() ->DeleteAlias.deleteSpecificAlias(kmsClient, aliasName)); + assertDoesNotThrow(() -> DeleteAlias.deleteSpecificAlias(kmsClient, aliasName)); System.out.println("Test 12 passed"); } @@ -170,7 +171,7 @@ public void DeleteAlias() { @Tag("IntegrationTest") @Order(13) public void ListKeys() { - assertDoesNotThrow(() ->ListKeys.listAllKeys(kmsClient)); + assertDoesNotThrow(() -> ListKeys.listAllKeys(kmsClient)); System.out.println("Test 13 passed"); } @@ -178,20 +179,20 @@ public void ListKeys() { @Tag("IntegrationTest") @Order(14) public void SetKeyPolicy() { - assertDoesNotThrow(() ->SetKeyPolicy.createPolicy(kmsClient, keyId, "default")); + assertDoesNotThrow(() -> SetKeyPolicy.createPolicy(kmsClient, keyId, "default")); System.out.println("Test 14 passed"); } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/kms"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -223,4 +224,3 @@ public String getAliasName() { } } } - diff --git a/javav2/example_code/lambda/src/main/java/com/example/lambda/CreateFunction.java b/javav2/example_code/lambda/src/main/java/com/example/lambda/CreateFunction.java index 754dee3d929..b6e3b4eda2f 100644 --- a/javav2/example_code/lambda/src/main/java/com/example/lambda/CreateFunction.java +++ b/javav2/example_code/lambda/src/main/java/com/example/lambda/CreateFunction.java @@ -1,11 +1,5 @@ -// snippet-sourcedescription:[CreateFunction.java demonstrates how to create an AWS Lambda function by using the LambdaClient object.] -//snippet-keyword:[AWS SDK for Java v2] -// snippet-keyword:[AWS Lambda] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.lambda; @@ -29,10 +23,11 @@ // snippet-end:[lambda.java2.create.import] /** - * This code example requires a ZIP or JAR that represents the code of the Lambda function. - * If you do not have a ZIP or JAR, please refer to the following document: + * This code example requires a ZIP or JAR that represents the code of the + * Lambda function. + * If you do not have a ZIP or JAR, please refer to the following document: * - * https://github.com/aws-doc-sdk-examples/tree/master/javav2/usecases/creating_workflows_stepfunctions + * https://github.com/aws-doc-sdk-examples/tree/master/javav2/usecases/creating_workflows_stepfunctions * * Also, set up your development environment, including your credentials. * @@ -46,15 +41,15 @@ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - functionName - The name of the Lambda function.\s - filePath - The path to the ZIP or JAR where the code is located.\s - role - The role ARN that has Lambda permissions.\s - handler - The fully qualified method name (for example, example.Handler::handleRequest). \s - """; + Where: + functionName - The name of the Lambda function.\s + filePath - The path to the ZIP or JAR where the code is located.\s + role - The role ARN that has Lambda permissions.\s + handler - The fully qualified method name (for example, example.Handler::handleRequest). \s + """; if (args.length != 4) { System.out.println(usage); @@ -67,18 +62,18 @@ public static void main(String[] args) { String handler = args[3]; Region region = Region.US_WEST_2; LambdaClient awsLambda = LambdaClient.builder() - .region(region) - .build(); + .region(region) + .build(); createLambdaFunction(awsLambda, functionName, filePath, role, handler); awsLambda.close(); } public static void createLambdaFunction(LambdaClient awsLambda, - String functionName, - String filePath, - String role, - String handler) { + String functionName, + String filePath, + String role, + String handler) { try { LambdaWaiter waiter = awsLambda.waiter(); @@ -86,23 +81,23 @@ public static void createLambdaFunction(LambdaClient awsLambda, SdkBytes fileToUpload = SdkBytes.fromInputStream(is); FunctionCode code = FunctionCode.builder() - .zipFile(fileToUpload) - .build(); + .zipFile(fileToUpload) + .build(); CreateFunctionRequest functionRequest = CreateFunctionRequest.builder() - .functionName(functionName) - .description("Created by the Lambda Java API") - .code(code) - .handler(handler) - .runtime(Runtime.JAVA8) - .role(role) - .build(); + .functionName(functionName) + .description("Created by the Lambda Java API") + .code(code) + .handler(handler) + .runtime(Runtime.JAVA8) + .role(role) + .build(); // Create a Lambda function using a waiter. CreateFunctionResponse functionResponse = awsLambda.createFunction(functionRequest); GetFunctionRequest getFunctionRequest = GetFunctionRequest.builder() - .functionName(functionName) - .build(); + .functionName(functionName) + .build(); WaiterResponse waiterResponse = waiter.waitUntilFunctionExists(getFunctionRequest); waiterResponse.matched().response().ifPresent(System.out::println); System.out.println("The function ARN is " + functionResponse.functionArn()); diff --git a/javav2/example_code/lambda/src/main/java/com/example/lambda/DeleteFunction.java b/javav2/example_code/lambda/src/main/java/com/example/lambda/DeleteFunction.java index 745ad58faa8..8e7686ee2e1 100644 --- a/javav2/example_code/lambda/src/main/java/com/example/lambda/DeleteFunction.java +++ b/javav2/example_code/lambda/src/main/java/com/example/lambda/DeleteFunction.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[DeleteFunction.java demonstrates how to delete an AWS Lambda function by using the LambdaClient object] -//snippet-keyword:[AWS SDK for Java v2] -// snippet-keyword:[AWS Lambda] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lambda.java2.DeleteFunction.complete] package com.example.lambda; @@ -20,7 +13,8 @@ // snippet-end:[lambda.java2.delete.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,12 +24,12 @@ public class DeleteFunction { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - functionName - The name of the Lambda function.\s - """; + Where: + functionName - The name of the Lambda function.\s + """; if (args.length != 1) { System.out.println(usage); @@ -45,26 +39,27 @@ public static void main(String[] args) { String functionName = args[0]; Region region = Region.US_EAST_1; LambdaClient awsLambda = LambdaClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteLambdaFunction(awsLambda, functionName); awsLambda.close(); } + public static void deleteLambdaFunction(LambdaClient awsLambda, String functionName) { try { DeleteFunctionRequest request = DeleteFunctionRequest.builder() - .functionName(functionName) - .build(); + .functionName(functionName) + .build(); awsLambda.deleteFunction(request); - System.out.println("The "+functionName +" function was deleted"); + System.out.println("The " + functionName + " function was deleted"); - } catch(LambdaException e) { + } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } - } +} // snippet-end:[lambda.java2.delete.main] // snippet-end:[lambda.java2.DeleteFunction.complete] diff --git a/javav2/example_code/lambda/src/main/java/com/example/lambda/GetAccountSettings.java b/javav2/example_code/lambda/src/main/java/com/example/lambda/GetAccountSettings.java index aea4296f27a..025da946e59 100644 --- a/javav2/example_code/lambda/src/main/java/com/example/lambda/GetAccountSettings.java +++ b/javav2/example_code/lambda/src/main/java/com/example/lambda/GetAccountSettings.java @@ -1,11 +1,5 @@ -// snippet-sourcedescription:[GetAccountSettings.java demonstrates how to obtain information about your account.] -//snippet-keyword:[AWS SDK for Java v2] -// snippet-keyword:[AWS Lambda] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.lambda; @@ -18,7 +12,8 @@ // snippet-end:[lambda.java2.account.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,8 +23,8 @@ public class GetAccountSettings { public static void main(String[] args) { Region region = Region.US_EAST_1; LambdaClient awsLambda = LambdaClient.builder() - .region(region) - .build(); + .region(region) + .build(); getSettings(awsLambda); awsLambda.close(); @@ -38,7 +33,8 @@ public static void main(String[] args) { public static void getSettings(LambdaClient awsLambda) { try { GetAccountSettingsResponse response = awsLambda.getAccountSettings(); - System.out.println("Total code size for your account is " + response.accountLimit().totalCodeSize() + " bytes"); + System.out.println( + "Total code size for your account is " + response.accountLimit().totalCodeSize() + " bytes"); } catch (LambdaException e) { System.err.println(e.getMessage()); diff --git a/javav2/example_code/lambda/src/main/java/com/example/lambda/LambdaInvoke.java b/javav2/example_code/lambda/src/main/java/com/example/lambda/LambdaInvoke.java index a1fd2dcc9e7..691cc952556 100644 --- a/javav2/example_code/lambda/src/main/java/com/example/lambda/LambdaInvoke.java +++ b/javav2/example_code/lambda/src/main/java/com/example/lambda/LambdaInvoke.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[LambdaInvoke.java demonstrates how to invoke an AWS Lambda function by using the LambdaClient object] -//snippet-keyword:[AWS SDK for Java v2] -// snippet-keyword:[AWS Lambda] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lambda.java2.LambdaInvoke.complete] package com.example.lambda; @@ -25,26 +18,28 @@ public class LambdaInvoke { - /* - * Function names appear as arn:aws:lambda:us-west-2:335556666777:function:HelloFunction - * you can retrieve the value by looking at the function in the AWS Console - * - * Also, set up your development environment, including your credentials. - * - * For information, see this documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ + /* + * Function names appear as + * arn:aws:lambda:us-west-2:335556666777:function:HelloFunction + * you can retrieve the value by looking at the function in the AWS Console + * + * Also, set up your development environment, including your credentials. + * + * For information, see this documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started. + * html + */ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - functionName - The name of the Lambda function\s - """; + Where: + functionName - The name of the Lambda function\s + """; if (args.length != 1) { System.out.println(usage); @@ -54,8 +49,8 @@ public static void main(String[] args) { String functionName = args[0]; Region region = Region.US_WEST_2; LambdaClient awsLambda = LambdaClient.builder() - .region(region) - .build(); + .region(region) + .build(); invokeFunction(awsLambda, functionName); awsLambda.close(); @@ -63,25 +58,25 @@ public static void main(String[] args) { public static void invokeFunction(LambdaClient awsLambda, String functionName) { - InvokeResponse res = null ; + InvokeResponse res = null; try { // Need a SdkBytes instance for the payload. JSONObject jsonObj = new JSONObject(); jsonObj.put("inputValue", "2000"); String json = jsonObj.toString(); - SdkBytes payload = SdkBytes.fromUtf8String(json) ; + SdkBytes payload = SdkBytes.fromUtf8String(json); // Setup an InvokeRequest. InvokeRequest request = InvokeRequest.builder() - .functionName(functionName) - .payload(payload) - .build(); + .functionName(functionName) + .payload(payload) + .build(); res = awsLambda.invoke(request); - String value = res.payload().asUtf8String() ; + String value = res.payload().asUtf8String(); System.out.println(value); - } catch(LambdaException e) { + } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } diff --git a/javav2/example_code/lambda/src/main/java/com/example/lambda/LambdaScenario.java b/javav2/example_code/lambda/src/main/java/com/example/lambda/LambdaScenario.java index 4ba901ca4d0..3129603e7dd 100644 --- a/javav2/example_code/lambda/src/main/java/com/example/lambda/LambdaScenario.java +++ b/javav2/example_code/lambda/src/main/java/com/example/lambda/LambdaScenario.java @@ -1,11 +1,5 @@ -// snippet-sourcedescription:[LambdaScenario.java demonstrates how to perform various operations by using the LambdaClient object.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-keyword:[AWS Lambda] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.lambda; @@ -66,20 +60,21 @@ public class LambdaScenario { public static final String DASHES = new String(new char[80]).replace("\0", "-"); + public static void main(String[] args) throws InterruptedException { final String usage = """ - Usage: - \s + Usage: + \s - Where: - functionName - The name of the Lambda function.\s - filePath - The path to the .zip or .jar where the code is located.\s - role - The AWS Identity and Access Management (IAM) service role that has Lambda permissions.\s - handler - The fully qualified method name (for example, example.Handler::handleRequest).\s - bucketName - The Amazon Simple Storage Service (Amazon S3) bucket name that contains the .zip or .jar used to update the Lambda function's code.\s - key - The Amazon S3 key name that represents the .zip or .jar (for example, LambdaHello-1.0-SNAPSHOT.jar). - """; + Where: + functionName - The name of the Lambda function.\s + filePath - The path to the .zip or .jar where the code is located.\s + role - The AWS Identity and Access Management (IAM) service role that has Lambda permissions.\s + handler - The fully qualified method name (for example, example.Handler::handleRequest).\s + bucketName - The Amazon Simple Storage Service (Amazon S3) bucket name that contains the .zip or .jar used to update the Lambda function's code.\s + key - The Amazon S3 key name that represents the .zip or .jar (for example, LambdaHello-1.0-SNAPSHOT.jar). + """; if (args.length != 6) { System.out.println(usage); @@ -95,8 +90,8 @@ public static void main(String[] args) throws InterruptedException { Region region = Region.US_WEST_2; LambdaClient awsLambda = LambdaClient.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.println(DASHES); System.out.println("Welcome to the AWS Lambda example scenario."); @@ -105,11 +100,11 @@ public static void main(String[] args) throws InterruptedException { System.out.println(DASHES); System.out.println("1. Create an AWS Lambda function."); String funArn = createLambdaFunction(awsLambda, functionName, filePath, role, handler); - System.out.println("The AWS Lambda ARN is "+funArn); + System.out.println("The AWS Lambda ARN is " + funArn); System.out.println(DASHES); System.out.println(DASHES); - System.out.println("2. Get the "+functionName + " AWS Lambda function."); + System.out.println("2. Get the " + functionName + " AWS Lambda function."); getFunction(awsLambda, functionName); System.out.println(DASHES); @@ -150,10 +145,10 @@ public static void main(String[] args) throws InterruptedException { } public static String createLambdaFunction(LambdaClient awsLambda, - String functionName, - String filePath, - String role, - String handler) { + String functionName, + String filePath, + String role, + String handler) { try { LambdaWaiter waiter = awsLambda.waiter(); @@ -161,28 +156,28 @@ public static String createLambdaFunction(LambdaClient awsLambda, SdkBytes fileToUpload = SdkBytes.fromInputStream(is); FunctionCode code = FunctionCode.builder() - .zipFile(fileToUpload) - .build(); + .zipFile(fileToUpload) + .build(); CreateFunctionRequest functionRequest = CreateFunctionRequest.builder() - .functionName(functionName) - .description("Created by the Lambda Java API") - .code(code) - .handler(handler) - .runtime(Runtime.JAVA8) - .role(role) - .build(); + .functionName(functionName) + .description("Created by the Lambda Java API") + .code(code) + .handler(handler) + .runtime(Runtime.JAVA8) + .role(role) + .build(); // Create a Lambda function using a waiter CreateFunctionResponse functionResponse = awsLambda.createFunction(functionRequest); GetFunctionRequest getFunctionRequest = GetFunctionRequest.builder() - .functionName(functionName) - .build(); + .functionName(functionName) + .build(); WaiterResponse waiterResponse = waiter.waitUntilFunctionExists(getFunctionRequest); waiterResponse.matched().response().ifPresent(System.out::println); return functionResponse.functionArn(); - } catch(LambdaException | FileNotFoundException e) { + } catch (LambdaException | FileNotFoundException e) { System.err.println(e.getMessage()); System.exit(1); } @@ -192,13 +187,13 @@ public static String createLambdaFunction(LambdaClient awsLambda, public static void getFunction(LambdaClient awsLambda, String functionName) { try { GetFunctionRequest functionRequest = GetFunctionRequest.builder() - .functionName(functionName) - .build(); + .functionName(functionName) + .build(); GetFunctionResponse response = awsLambda.getFunction(functionRequest); - System.out.println("The runtime of this Lambda function is " +response.configuration().runtime()); + System.out.println("The runtime of this Lambda function is " + response.configuration().runtime()); - } catch(LambdaException e) { + } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } @@ -208,11 +203,11 @@ public static void listFunctions(LambdaClient awsLambda) { try { ListFunctionsResponse functionResult = awsLambda.listFunctions(); List list = functionResult.functions(); - for (FunctionConfiguration config: list) { - System.out.println("The function name is "+config.functionName()); + for (FunctionConfiguration config : list) { + System.out.println("The function name is " + config.functionName()); } - } catch(LambdaException e) { + } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } @@ -226,18 +221,18 @@ public static void invokeFunction(LambdaClient awsLambda, String functionName) { JSONObject jsonObj = new JSONObject(); jsonObj.put("inputValue", "2000"); String json = jsonObj.toString(); - SdkBytes payload = SdkBytes.fromUtf8String(json) ; + SdkBytes payload = SdkBytes.fromUtf8String(json); InvokeRequest request = InvokeRequest.builder() - .functionName(functionName) - .payload(payload) - .build(); + .functionName(functionName) + .payload(payload) + .build(); res = awsLambda.invoke(request); - String value = res.payload().asUtf8String() ; + String value = res.payload().asUtf8String(); System.out.println(value); - } catch(LambdaException e) { + } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } @@ -247,53 +242,54 @@ public static void updateFunctionCode(LambdaClient awsLambda, String functionNam try { LambdaWaiter waiter = awsLambda.waiter(); UpdateFunctionCodeRequest functionCodeRequest = UpdateFunctionCodeRequest.builder() - .functionName(functionName) - .publish(true) - .s3Bucket(bucketName) - .s3Key(key) - .build(); + .functionName(functionName) + .publish(true) + .s3Bucket(bucketName) + .s3Key(key) + .build(); - UpdateFunctionCodeResponse response = awsLambda.updateFunctionCode(functionCodeRequest) ; + UpdateFunctionCodeResponse response = awsLambda.updateFunctionCode(functionCodeRequest); GetFunctionConfigurationRequest getFunctionConfigRequest = GetFunctionConfigurationRequest.builder() - .functionName(functionName) - .build(); + .functionName(functionName) + .build(); - WaiterResponse waiterResponse = waiter.waitUntilFunctionUpdated(getFunctionConfigRequest); + WaiterResponse waiterResponse = waiter + .waitUntilFunctionUpdated(getFunctionConfigRequest); waiterResponse.matched().response().ifPresent(System.out::println); - System.out.println("The last modified value is " +response.lastModified()); + System.out.println("The last modified value is " + response.lastModified()); - } catch(LambdaException e) { + } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } - public static void updateFunctionConfiguration(LambdaClient awsLambda, String functionName, String handler ){ + public static void updateFunctionConfiguration(LambdaClient awsLambda, String functionName, String handler) { try { UpdateFunctionConfigurationRequest configurationRequest = UpdateFunctionConfigurationRequest.builder() - .functionName(functionName) - .handler(handler) - .runtime(Runtime.JAVA11 ) - .build(); + .functionName(functionName) + .handler(handler) + .runtime(Runtime.JAVA11) + .build(); awsLambda.updateFunctionConfiguration(configurationRequest); - } catch(LambdaException e) { + } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } - public static void deleteLambdaFunction(LambdaClient awsLambda, String functionName ) { + public static void deleteLambdaFunction(LambdaClient awsLambda, String functionName) { try { DeleteFunctionRequest request = DeleteFunctionRequest.builder() - .functionName(functionName) - .build(); + .functionName(functionName) + .build(); awsLambda.deleteFunction(request); - System.out.println("The "+functionName +" function was deleted"); + System.out.println("The " + functionName + " function was deleted"); - } catch(LambdaException e) { + } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } diff --git a/javav2/example_code/lambda/src/main/java/com/example/lambda/ListLambdaFunctions.java b/javav2/example_code/lambda/src/main/java/com/example/lambda/ListLambdaFunctions.java index 77b83c87939..9d0ff876cbc 100644 --- a/javav2/example_code/lambda/src/main/java/com/example/lambda/ListLambdaFunctions.java +++ b/javav2/example_code/lambda/src/main/java/com/example/lambda/ListLambdaFunctions.java @@ -1,11 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-keyword:[AWS Lambda] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lambda.java2.ListLambdaFunctions.complete] package com.example.lambda; @@ -21,7 +15,8 @@ // snippet-end:[lambda.java2.list.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,8 +26,8 @@ public class ListLambdaFunctions { public static void main(String[] args) { Region region = Region.US_WEST_2; LambdaClient awsLambda = LambdaClient.builder() - .region(region) - .build(); + .region(region) + .build(); listFunctions(awsLambda); awsLambda.close(); diff --git a/javav2/example_code/lambda/src/test/java/LambdaTest.java b/javav2/example_code/lambda/src/test/java/LambdaTest.java index 60ea879fbd5..4b07221fe9f 100644 --- a/javav2/example_code/lambda/src/test/java/LambdaTest.java +++ b/javav2/example_code/lambda/src/test/java/LambdaTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.lambda.CreateFunction; import com.example.lambda.DeleteFunction; @@ -37,63 +35,67 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class LambdaTest { private static LambdaClient awsLambda; - private static String functionName=""; - private static String functionNameSc=""; - private static String filePath=""; - private static String role=""; - private static String handler=""; - private static String bucketName=""; - private static String key=""; + private static String functionName = ""; + private static String functionNameSc = ""; + private static String filePath = ""; + private static String role = ""; + private static String handler = ""; + private static String bucketName = ""; + private static String key = ""; @BeforeAll - public static void setUp() { + public static void setUp() { Region region = Region.US_WEST_2; awsLambda = LambdaClient.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); String json = getSecretValues(); SecretValues values = gson.fromJson(json, SecretValues.class); - functionName = values.getFunctionNameSc()+ java.util.UUID.randomUUID(); + functionName = values.getFunctionNameSc() + java.util.UUID.randomUUID(); filePath = values.getFilePath(); role = values.getRole(); handler = values.getHandler(); - functionNameSc =values.getFunctionNameSc()+ java.util.UUID.randomUUID(); + functionNameSc = values.getFunctionNameSc() + java.util.UUID.randomUUID(); bucketName = values.getBucketName(); key = values.getKey(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. -/* - - try (InputStream input = LambdaTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - prop.load(input); - functionName = prop.getProperty("functionNameSc")+ java.util.UUID.randomUUID(); - filePath = prop.getProperty("filePath"); - role = prop.getProperty("role"); - handler = prop.getProperty("handler"); - functionNameSc = prop.getProperty("functionNameSc")+ java.util.UUID.randomUUID(); - bucketName = prop.getProperty("bucketName"); - key = prop.getProperty("key"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * + * try (InputStream input = + * LambdaTest.class.getClassLoader().getResourceAsStream("config.properties")) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * prop.load(input); + * functionName = prop.getProperty("functionNameSc")+ + * java.util.UUID.randomUUID(); + * filePath = prop.getProperty("filePath"); + * role = prop.getProperty("role"); + * handler = prop.getProperty("handler"); + * functionNameSc = prop.getProperty("functionNameSc")+ + * java.util.UUID.randomUUID(); + * bucketName = prop.getProperty("bucketName"); + * key = prop.getProperty("key"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @Tag("IntegrationTest") @Order(1) public void CreateFunction() { - assertDoesNotThrow(() ->CreateFunction.createLambdaFunction(awsLambda, functionName, filePath, role, handler)); + assertDoesNotThrow(() -> CreateFunction.createLambdaFunction(awsLambda, functionName, filePath, role, handler)); System.out.println("Test 1 passed"); } @@ -101,7 +103,7 @@ public void CreateFunction() { @Tag("IntegrationTest") @Order(2) public void GetAccountSettings() { - assertDoesNotThrow(() ->GetAccountSettings.getSettings(awsLambda)); + assertDoesNotThrow(() -> GetAccountSettings.getSettings(awsLambda)); System.out.println("Test 2 passed"); } @@ -109,7 +111,7 @@ public void GetAccountSettings() { @Tag("IntegrationTest") @Order(3) public void ListLambdaFunctions() { - assertDoesNotThrow(() ->ListLambdaFunctions.listFunctions(awsLambda)); + assertDoesNotThrow(() -> ListLambdaFunctions.listFunctions(awsLambda)); System.out.println("Test 3 passed"); } @@ -119,7 +121,7 @@ public void ListLambdaFunctions() { public void LambdaInvoke() throws InterruptedException { System.out.println("*** Wait for 5 MIN so the resource is available"); TimeUnit.MINUTES.sleep(5); - assertDoesNotThrow(() ->LambdaInvoke.invokeFunction(awsLambda, functionName)); + assertDoesNotThrow(() -> LambdaInvoke.invokeFunction(awsLambda, functionName)); System.out.println("Test 4 passed"); } @@ -127,7 +129,7 @@ public void LambdaInvoke() throws InterruptedException { @Tag("IntegrationTest") @Order(5) public void DeleteFunction() { - assertDoesNotThrow(() ->DeleteFunction.deleteLambdaFunction(awsLambda, functionName)); + assertDoesNotThrow(() -> DeleteFunction.deleteLambdaFunction(awsLambda, functionName)); System.out.println("Test 5 passed"); } @@ -137,42 +139,43 @@ public void DeleteFunction() { public void LambdaScenario() throws InterruptedException { String funArn = LambdaScenario.createLambdaFunction(awsLambda, functionNameSc, filePath, role, handler); assertFalse(funArn.isEmpty()); - System.out.println("The function ARN is "+funArn); + System.out.println("The function ARN is " + funArn); // Get the Lambda function. - System.out.println("Getting the " +functionNameSc +" Lambda function."); - assertDoesNotThrow(() ->LambdaScenario.getFunction(awsLambda, functionNameSc)); + System.out.println("Getting the " + functionNameSc + " Lambda function."); + assertDoesNotThrow(() -> LambdaScenario.getFunction(awsLambda, functionNameSc)); // List the Lambda functions. System.out.println("Listing all functions."); - assertDoesNotThrow(() ->LambdaScenario.listFunctions(awsLambda)); + assertDoesNotThrow(() -> LambdaScenario.listFunctions(awsLambda)); System.out.println("*** Invoke the Lambda function."); System.out.println("*** Wait for 5 MIN so the resource is available"); TimeUnit.MINUTES.sleep(5); - assertDoesNotThrow(() ->LambdaScenario.invokeFunction(awsLambda, functionNameSc)); + assertDoesNotThrow(() -> LambdaScenario.invokeFunction(awsLambda, functionNameSc)); System.out.println("*** Update the Lambda function code."); - assertDoesNotThrow(() ->LambdaScenario.updateFunctionCode(awsLambda, functionNameSc, bucketName, key)); + assertDoesNotThrow(() -> LambdaScenario.updateFunctionCode(awsLambda, functionNameSc, bucketName, key)); System.out.println("*** Invoke the Lambda function again with the updated code."); System.out.println("*** Wait for 5 MIN so the resource is available"); TimeUnit.MINUTES.sleep(5); - assertDoesNotThrow(() ->LambdaScenario.invokeFunction(awsLambda, functionNameSc)); + assertDoesNotThrow(() -> LambdaScenario.invokeFunction(awsLambda, functionNameSc)); System.out.println("Delete the AWS Lambda function."); - assertDoesNotThrow(() ->LambdaScenario.deleteLambdaFunction(awsLambda, functionNameSc)); + assertDoesNotThrow(() -> LambdaScenario.deleteLambdaFunction(awsLambda, functionNameSc)); } + private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/lambda"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -215,6 +218,7 @@ public String getKey() { public String getBucketName() { return bucketName; } + public String getFunctionName() { return functionName; } @@ -222,4 +226,3 @@ public String getFunctionName() { } } - diff --git a/javav2/example_code/lex/src/main/java/com/example/lex/DeleteBot.java b/javav2/example_code/lex/src/main/java/com/example/lex/DeleteBot.java index 5db0b300c66..0fcd05835be 100644 --- a/javav2/example_code/lex/src/main/java/com/example/lex/DeleteBot.java +++ b/javav2/example_code/lex/src/main/java/com/example/lex/DeleteBot.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DeleteBot.java demonstrates how to delete an Amazon Lex conversational bot.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Lex] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.lex; @@ -18,7 +12,8 @@ // snippet-end:[lex.java2.delete_bot.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,11 +23,11 @@ public class DeleteBot { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - botName - The name of an existing bot to delete (for example, BookHotel). - """; + Where: + botName - The name of an existing bot to delete (for example, BookHotel). + """; if (args.length != 1) { System.out.println(usage); @@ -42,8 +37,8 @@ public static void main(String[] args) { String botName = args[0]; Region region = Region.US_WEST_2; LexModelBuildingClient lexClient = LexModelBuildingClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteSpecificBot(lexClient, botName); lexClient.close(); @@ -52,8 +47,8 @@ public static void main(String[] args) { public static void deleteSpecificBot(LexModelBuildingClient lexClient, String botName) { try { DeleteBotRequest botRequest = DeleteBotRequest.builder() - .name(botName) - .build(); + .name(botName) + .build(); lexClient.deleteBot(botRequest); System.out.println(botName + " was deleted!"); diff --git a/javav2/example_code/lex/src/main/java/com/example/lex/GetBotStatus.java b/javav2/example_code/lex/src/main/java/com/example/lex/GetBotStatus.java index 70a0f040948..0033dc87784 100644 --- a/javav2/example_code/lex/src/main/java/com/example/lex/GetBotStatus.java +++ b/javav2/example_code/lex/src/main/java/com/example/lex/GetBotStatus.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[GetBotStatus.java demonstrates how to get the status of an Amazon Lex bot.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Lex] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.lex; @@ -16,7 +10,8 @@ import software.amazon.awssdk.services.lexmodelbuilding.model.LexModelBuildingException; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,11 +22,11 @@ public class GetBotStatus { public static void main(String[] args) { final String usage = """ - Usage: \s + Usage: \s - Where: - botName - The name of an existing bot (for example, BookHotel). - """; + Where: + botName - The name of an existing bot (for example, BookHotel). + """; if (args.length != 1) { System.out.println(usage); @@ -41,18 +36,18 @@ public static void main(String[] args) { String botName = args[0]; Region region = Region.US_WEST_2; LexModelBuildingClient lexClient = LexModelBuildingClient.builder() - .region(region) - .build(); + .region(region) + .build(); - getStatus(lexClient, botName ); + getStatus(lexClient, botName); lexClient.close(); } - public static void getStatus(LexModelBuildingClient lexClient, String botName ) { + public static void getStatus(LexModelBuildingClient lexClient, String botName) { GetBotRequest botRequest = GetBotRequest.builder() - .name(botName) - .versionOrAlias("$LATEST") - .build(); + .name(botName) + .versionOrAlias("$LATEST") + .build(); try { String status = ""; do { diff --git a/javav2/example_code/lex/src/main/java/com/example/lex/GetBots.java b/javav2/example_code/lex/src/main/java/com/example/lex/GetBots.java index f5506ac53eb..09f7246e098 100644 --- a/javav2/example_code/lex/src/main/java/com/example/lex/GetBots.java +++ b/javav2/example_code/lex/src/main/java/com/example/lex/GetBots.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[GetBots.java demonstrates how to return information about Amazon Lex chatbots.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Lex] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.lex; @@ -20,7 +14,8 @@ // snippet-end:[lex.java2.get_bots.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,8 +25,8 @@ public class GetBots { public static void main(String[] args) { Region region = Region.US_WEST_2; LexModelBuildingClient lexClient = LexModelBuildingClient.builder() - .region(region) - .build(); + .region(region) + .build(); getAllBots(lexClient); lexClient.close(); diff --git a/javav2/example_code/lex/src/main/java/com/example/lex/GetIntent.java b/javav2/example_code/lex/src/main/java/com/example/lex/GetIntent.java index a5401bad32e..a1e22393f01 100644 --- a/javav2/example_code/lex/src/main/java/com/example/lex/GetIntent.java +++ b/javav2/example_code/lex/src/main/java/com/example/lex/GetIntent.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[GetIntent.java demonstrates how to return information about an intent.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Lex] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.lex; @@ -19,7 +13,8 @@ // snippet-end:[lex.java2.get_intent.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,13 +24,13 @@ public class GetIntent { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - intentName - The name of the intent (for example, BookHotel). + Where: + intentName - The name of the intent (for example, BookHotel). - intentVersion - The version of the intent (for example, 1). - """; + intentVersion - The version of the intent (for example, 1). + """; if (args.length != 2) { System.out.println(usage); @@ -46,8 +41,8 @@ public static void main(String[] args) { String intentVersion = args[1]; Region region = Region.US_WEST_2; LexModelBuildingClient lexClient = LexModelBuildingClient.builder() - .region(region) - .build(); + .region(region) + .build(); getSpecificIntent(lexClient, intentName, intentVersion); lexClient.close(); @@ -56,9 +51,9 @@ public static void main(String[] args) { public static void getSpecificIntent(LexModelBuildingClient lexClient, String intentName, String intentVersion) { try { GetIntentRequest intentRequest = GetIntentRequest.builder() - .name(intentName) - .version(intentVersion) - .build(); + .name(intentName) + .version(intentVersion) + .build(); GetIntentResponse intentResponse = lexClient.getIntent(intentRequest); System.out.println("The description is " + intentResponse.description()); diff --git a/javav2/example_code/lex/src/main/java/com/example/lex/GetSlotTypes.java b/javav2/example_code/lex/src/main/java/com/example/lex/GetSlotTypes.java index 8ae02a93548..d6dfa393949 100644 --- a/javav2/example_code/lex/src/main/java/com/example/lex/GetSlotTypes.java +++ b/javav2/example_code/lex/src/main/java/com/example/lex/GetSlotTypes.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[GetSlotTypes.java demonstrates how to returns slot type information.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Lex] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.lex; @@ -21,7 +15,8 @@ // snippet-end:[lex.java2.get_slot_types.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,9 +26,9 @@ public class GetSlotTypes { public static void main(String[] args) { Region region = Region.US_EAST_1; LexModelBuildingClient lexClient = LexModelBuildingClient.builder() - .region(region) - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(ProfileCredentialsProvider.create()) + .build(); getSlotsInfo(lexClient); lexClient.close(); diff --git a/javav2/example_code/lex/src/main/java/com/example/lex/PutBot.java b/javav2/example_code/lex/src/main/java/com/example/lex/PutBot.java index 37e8ceb20b1..fd31dc5947c 100644 --- a/javav2/example_code/lex/src/main/java/com/example/lex/PutBot.java +++ b/javav2/example_code/lex/src/main/java/com/example/lex/PutBot.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[PutBot.java demonstrates how to creates an Amazon Lex conversational bot.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Lex] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.lex; @@ -23,84 +17,85 @@ // snippet-end:[lex.java2.create_bot.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class PutBot { - public static void main(String[] args) { - final String usage = """ - - Usage: \s - - Where: - botName - The name of bot (for example, BookHotel). - intentName - The name of an existing intent (for example, BookHotel). - intentVersion - The version of the intent (for example, 1). - """; - - if (args.length != 3) { - System.out.println(usage); - System.exit(1); + public static void main(String[] args) { + final String usage = """ + + Usage: \s + + Where: + botName - The name of bot (for example, BookHotel). + intentName - The name of an existing intent (for example, BookHotel). + intentVersion - The version of the intent (for example, 1). + """; + + if (args.length != 3) { + System.out.println(usage); + System.exit(1); + } + + String botName = args[0]; + String intentName = args[1]; + String intentVersion = args[2]; + Region region = Region.US_WEST_2; + LexModelBuildingClient lexClient = LexModelBuildingClient.builder() + .region(region) + .build(); + + createBot(lexClient, botName, intentName, intentVersion); + lexClient.close(); } - String botName = args[0]; - String intentName = args[1]; - String intentVersion = args[2]; - Region region = Region.US_WEST_2; - LexModelBuildingClient lexClient = LexModelBuildingClient.builder() - .region(region) - .build(); - - createBot(lexClient, botName, intentName, intentVersion); - lexClient.close(); - } - - public static void createBot(LexModelBuildingClient lexClient, - String botName, - String intentName, - String intentVersion) { - - try { - // Create an Intent object for the bot. - Intent weatherIntent = Intent.builder() - .intentName(intentName) - .intentVersion(intentVersion) - .build(); - - ArrayList intents = new ArrayList<>(); - intents.add(weatherIntent); - - // Create an abort statement. - Message msg = Message.builder() - .content("I do not understand you!") - .contentType(ContentType.PLAIN_TEXT) - .build(); - - ArrayList abortMsg = new ArrayList<>(); - abortMsg.add(msg); - Statement statement = Statement.builder() - .messages(abortMsg) - .build(); - - PutBotRequest botRequest = PutBotRequest.builder() - .abortStatement(statement) - .description("Created by using the Amazon Lex Java API") - .childDirected(true) - .locale("en-US") - .name(botName) - .intents(intents) - .build(); - - lexClient.putBot(botRequest); - System.out.println("The Amazon Lex bot was successfully created"); - - } catch (LexModelBuildingException e) { - System.out.println(e.getLocalizedMessage()); - System.exit(1); + public static void createBot(LexModelBuildingClient lexClient, + String botName, + String intentName, + String intentVersion) { + + try { + // Create an Intent object for the bot. + Intent weatherIntent = Intent.builder() + .intentName(intentName) + .intentVersion(intentVersion) + .build(); + + ArrayList intents = new ArrayList<>(); + intents.add(weatherIntent); + + // Create an abort statement. + Message msg = Message.builder() + .content("I do not understand you!") + .contentType(ContentType.PLAIN_TEXT) + .build(); + + ArrayList abortMsg = new ArrayList<>(); + abortMsg.add(msg); + Statement statement = Statement.builder() + .messages(abortMsg) + .build(); + + PutBotRequest botRequest = PutBotRequest.builder() + .abortStatement(statement) + .description("Created by using the Amazon Lex Java API") + .childDirected(true) + .locale("en-US") + .name(botName) + .intents(intents) + .build(); + + lexClient.putBot(botRequest); + System.out.println("The Amazon Lex bot was successfully created"); + + } catch (LexModelBuildingException e) { + System.out.println(e.getLocalizedMessage()); + System.exit(1); + } } - } } // snippet-end:[lex.java2.create_bot.main] \ No newline at end of file diff --git a/javav2/example_code/lex/src/test/java/AmazonLexTest.java b/javav2/example_code/lex/src/test/java/AmazonLexTest.java index f83b0818ccc..b4edc9e5b80 100644 --- a/javav2/example_code/lex/src/test/java/AmazonLexTest.java +++ b/javav2/example_code/lex/src/test/java/AmazonLexTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.lex.*; import com.google.gson.Gson; @@ -31,9 +29,9 @@ public class AmazonLexTest { @BeforeAll public static void setUp() { lexClient = LexModelBuildingClient.builder() - .region(Region.US_WEST_2) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_WEST_2) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -43,85 +41,89 @@ public static void setUp() { intentName = values.getIntentName(); intentVersion = values.getIntentVersion(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * + * try (InputStream input = + * AmazonLexTest.class.getClassLoader().getResourceAsStream("config.properties") + * ) { + * Properties prop = new Properties(); + * + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * prop.load(input); + * botName = prop.getProperty("botName"); + * intentName = prop.getProperty("intentName"); + * intentVersion = prop.getProperty("intentVersion"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ + } - try (InputStream input = AmazonLexTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); + @Test + @Tag("IntegrationTest") + @Order(1) + public void PutBot() { + assertDoesNotThrow(() -> PutBot.createBot(lexClient, botName, intentName, intentVersion)); + System.out.println("Test 1 passed"); + } - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } + @Test + @Tag("IntegrationTest") + @Order(2) + public void GetBots() { + assertDoesNotThrow(() -> GetBots.getAllBots(lexClient)); + System.out.println("Test 2 passed"); + } - prop.load(input); - botName = prop.getProperty("botName"); - intentName = prop.getProperty("intentName"); - intentVersion = prop.getProperty("intentVersion"); + @Test + @Tag("IntegrationTest") + @Order(3) + public void GetIntent() { + assertDoesNotThrow(() -> GetIntent.getSpecificIntent(lexClient, intentName, intentVersion)); + System.out.println("Test 3 passed"); + } - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + @Test + @Tag("IntegrationTest") + @Order(4) + public void GetSlotTypes() { + assertDoesNotThrow(() -> GetSlotTypes.getSlotsInfo(lexClient)); + System.out.println("Test 4 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(5) + public void GetBotStatus() { + assertDoesNotThrow(() -> GetBotStatus.getStatus(lexClient, botName)); + System.out.println("Test 5 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(6) + public void DeleteBot() { + assertDoesNotThrow(() -> DeleteBot.deleteSpecificBot(lexClient, botName)); + System.out.println("Test 6 passed"); } - @Test - @Tag("IntegrationTest") - @Order(1) - public void PutBot() { - assertDoesNotThrow(() ->PutBot.createBot(lexClient, botName, intentName, intentVersion)); - System.out.println("Test 1 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(2) - public void GetBots() { - assertDoesNotThrow(() -> GetBots.getAllBots(lexClient)); - System.out.println("Test 2 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(3) - public void GetIntent() { - assertDoesNotThrow(() ->GetIntent.getSpecificIntent(lexClient, intentName, intentVersion)); - System.out.println("Test 3 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(4) - public void GetSlotTypes() { - assertDoesNotThrow(() ->GetSlotTypes.getSlotsInfo(lexClient)); - System.out.println("Test 4 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(5) - public void GetBotStatus() { - assertDoesNotThrow(() ->GetBotStatus.getStatus(lexClient,botName)); - System.out.println("Test 5 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(6) - public void DeleteBot() { - assertDoesNotThrow(() ->DeleteBot.deleteSpecificBot(lexClient, botName)); - System.out.println("Test 6 passed"); - } private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/lex"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -148,4 +150,3 @@ public String getIntentVersion() { } } - diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/CreateDataset.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/CreateDataset.java index 6863b5eabb4..958efee2ddc 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/CreateDataset.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/CreateDataset.java @@ -1,7 +1,5 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.create_dataset.complete] diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/CreateModel.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/CreateModel.java index 43c22c8731f..174b97e8486 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/CreateModel.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/CreateModel.java @@ -1,7 +1,5 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.create_model.complete] @@ -76,13 +74,11 @@ public static void main(String[] args) { System.out.println(String.format("Could not create model: %s", lfvError.getMessage())); System.exit(1); - } catch (InterruptedException intError) { logger.log(Level.SEVERE, "Interrupt exception occurred: {0}", intError.getMessage()); Thread.currentThread().interrupt(); - } + } - } } diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/CreateProject.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/CreateProject.java index 024c446f3e6..754b6b63523 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/CreateProject.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/CreateProject.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.create_project.complete] diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/Datasets.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/Datasets.java index b547de3b1b7..d0df0cb5d9f 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/Datasets.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/Datasets.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.datasets.complete] @@ -267,7 +265,7 @@ public static DatasetDescription describeDataset(LookoutVisionClient lfvClient, } - /** + /** * Updates an Amazon Lookout for Vision dataset from a manifest file. * Returns after Lookout for Vision updates the dataset. * @@ -276,8 +274,9 @@ public static DatasetDescription describeDataset(LookoutVisionClient lfvClient, * dataset. * @param datasetType The type of the dataset that you want to update (train or * test). - * @param manifestFile The name and location of a local manifest file that you want to - * use to update the dataset. + * @param manifestFile The name and location of a local manifest file that you + * want to + * use to update the dataset. * @return DatasetStatus The status of the updated dataset. */ diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DeleteDataset.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DeleteDataset.java index 9373b7b0f31..7db4ac3b35d 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DeleteDataset.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DeleteDataset.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.delete_dataset.complete] diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DeleteModel.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DeleteModel.java index ccbe94a44c9..715d2e9186c 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DeleteModel.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DeleteModel.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.lookoutvision; @@ -42,8 +40,8 @@ public static void main(String args[]) throws Exception { System.out.printf( "You are charged each time you successfully train a model.%n" - +"Are you sure you want to delete model version %s in project %s?%n" - +"Enter YES to delete the model.%n", + + "Are you sure you want to delete model version %s in project %s?%n" + + "Enter YES to delete the model.%n", modelVersion, projectName); BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); @@ -59,9 +57,9 @@ public static void main(String args[]) throws Exception { System.out.printf("Deleting model version %s in project %s%n", modelVersion, projectName); Models.deleteModel(lfvClient, projectName, modelVersion); System.out.printf("Deleted model version %s in project %s%n", modelVersion, projectName); - } - else{ - System.out.printf("Request cancelled. Not deleting model version %s in project %s%n", modelVersion, projectName); + } else { + System.out.printf("Request cancelled. Not deleting model version %s in project %s%n", modelVersion, + projectName); } } catch (LookoutVisionException lfvError) { @@ -73,4 +71,3 @@ public static void main(String args[]) throws Exception { } } } - diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DeleteProject.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DeleteProject.java index cc503bea0fd..b9a1c22a620 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DeleteProject.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DeleteProject.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.delete_project.complete] diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DescribeDataset.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DescribeDataset.java index 57286286c5f..e0851fb90e3 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DescribeDataset.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DescribeDataset.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.describe_dataset.complete] diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DescribeModel.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DescribeModel.java index c7b6f2bfe94..fb813e54465 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DescribeModel.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DescribeModel.java @@ -1,7 +1,5 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.describe_model.complete] diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DescribeModelPackagingJob.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DescribeModelPackagingJob.java index 40fab73b8b8..0a62249d9b2 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DescribeModelPackagingJob.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DescribeModelPackagingJob.java @@ -1,7 +1,5 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.describe_model_packaging_job.complete] diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DescribeProject.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DescribeProject.java index bc2c05ea5d3..3a068eda05d 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DescribeProject.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DescribeProject.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.describe_project.complete] diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DetectAnomalies.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DetectAnomalies.java index 84cd4e1614e..c3ea2c62ed5 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DetectAnomalies.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/DetectAnomalies.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.detect_anomalies.complete] @@ -208,12 +206,13 @@ public static Boolean rejectOnAnomalyTypeCount(String image, DetectAnomalyResult /** * Rejects an image based on a maximum allowable number of anomaly types. * - * @param image The file name of the analyzed image. - * @param prediction The prediction for an image analyzed with - * DetectAnomalies. - * @param minConfidence The minimum acceptable confidence for the predictio - * (0-1). - * @param maxAnomalyLabels The maximum allowable number of anomaly labels (types). + * @param image The file name of the analyzed image. + * @param prediction The prediction for an image analyzed with + * DetectAnomalies. + * @param minConfidence The minimum acceptable confidence for the predictio + * (0-1). + * @param maxAnomalyLabels The maximum allowable number of anomaly labels + * (types). * * @return boolean True if the image contains more than the maximum allowed * anomaly types, otherwise False. @@ -306,7 +305,6 @@ public static void main(String[] args) { "Where:\n" + " image - The image file to analyze.\n\n" + " config - The configuration JSON file to use. See resources/analysis-config.json\n\n"; - try { @@ -327,7 +325,6 @@ public static void main(String[] args) { anomalyLabelsLimit = config.getInt("anomaly_labels_limit"); anomalyType = config.getString("anomaly_label"); - // Get the Lookout for Vision client. LookoutVisionClient lfvClient = LookoutVisionClient.builder().build(); diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/EdgePackages.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/EdgePackages.java index 464c4ad464b..3c62bc96ad6 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/EdgePackages.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/EdgePackages.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.edge_packages.complete] @@ -124,7 +122,8 @@ public static ModelPackagingDescription describeModelPackagingJob(LookoutVisionC * * @param projectName The name of the project that contains the model * packaging job that you want to start. - * @param fileName The name and path of the JSON file that matches the request + * @param fileName The name and path of the JSON file that matches the + * request * syntax for StartModelPackagingJob. * * @return StartModelPackagingJobRequest A StartModelPackagingJobRequest object diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/Hosting.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/Hosting.java index c51434e0a9c..64c287e2c20 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/Hosting.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/Hosting.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.hosting.complete] diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ListDatasetEntries.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ListDatasetEntries.java index db0ae412c39..6b6c7ddeabe 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ListDatasetEntries.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ListDatasetEntries.java @@ -1,7 +1,5 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.list_dataset_entries.complete] diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ListModelPackagingJobs.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ListModelPackagingJobs.java index b1acb18bd2b..0c9ee314a5a 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ListModelPackagingJobs.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ListModelPackagingJobs.java @@ -1,7 +1,5 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.list_model_packaging_jobs.complete] @@ -41,7 +39,8 @@ public static void main(String[] args) { LookoutVisionClient lfvClient = LookoutVisionClient.builder().build(); // Get a list of model packaging jobs in the supplied project. - List modelPackagingJobs = EdgePackages.listModelPackagingJobs(lfvClient, projectName); + List modelPackagingJobs = EdgePackages.listModelPackagingJobs(lfvClient, + projectName); System.out.println(String.format("Project: %s", projectName)); diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ListModelTags.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ListModelTags.java index 4a10badab22..aacacebd518 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ListModelTags.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ListModelTags.java @@ -1,7 +1,5 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.list_tags_for_model.complete] diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ListModels.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ListModels.java index 0d557033808..ff8b9ac14dc 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ListModels.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ListModels.java @@ -1,7 +1,5 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.list_models.complete] diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ListProjects.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ListProjects.java index 67900b0d450..274ea97e4e0 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ListProjects.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ListProjects.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.list_projects.complete] diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/Models.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/Models.java index 5f9da1f1a55..5ecb4e52d8f 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/Models.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/Models.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.models.complete] @@ -41,7 +39,8 @@ public class Models { /** * Creates an Amazon Lookout for Vision model. The function returns after model * training completes. Model training can take multiple hours to complete. - * You are charged for the amount of time it takes to successfully train a model. + * You are charged for the amount of time it takes to successfully train a + * model. * Returns after Lookout for Vision creates the dataset. * * @param lfvClient An Amazon Lookout for Vision client. @@ -196,7 +195,6 @@ public static List listModels(LookoutVisionClient lfvClient, Stri } - /** * Lists the tags attached to an Amazon Lookout for Vision model. * @@ -240,15 +238,17 @@ public static List listTagsForModel(LookoutVisionClient lfvClient, return response.tags(); } + /** - * Unattaches a tag from an Amazon Lookout for Vision model. - * - * @param lfvClient An Amazon Lookout for Vision client. - * @param projectName The name of the project that contains the model for which - * you want to unattach a tag. - * @param modelVersion The version of the model for which you want to unattach a tag. - * @return void - */ + * Unattaches a tag from an Amazon Lookout for Vision model. + * + * @param lfvClient An Amazon Lookout for Vision client. + * @param projectName The name of the project that contains the model for which + * you want to unattach a tag. + * @param modelVersion The version of the model for which you want to unattach a + * tag. + * @return void + */ public static void untagModel(LookoutVisionClient lfvClient, String projectName, String modelVersion, String key) throws LookoutVisionException { @@ -282,14 +282,15 @@ public static void untagModel(LookoutVisionClient lfvClient, String projectName, } /** - * Attaches a tag to an Amazon Lookout for Vision model. - * - * @param lfvClient An Amazon Lookout for Vision client. - * @param projectName The name of the project that contains the model for which - * you want to attach a tag. - * @param modelVersion The version of the model for which you want to attach a tag. - * @return void - */ + * Attaches a tag to an Amazon Lookout for Vision model. + * + * @param lfvClient An Amazon Lookout for Vision client. + * @param projectName The name of the project that contains the model for which + * you want to attach a tag. + * @param modelVersion The version of the model for which you want to attach a + * tag. + * @return void + */ public static void tagModel(LookoutVisionClient lfvClient, String projectName, String modelVersion, String key, String value) throws LookoutVisionException { @@ -329,13 +330,15 @@ public static void tagModel(LookoutVisionClient lfvClient, String projectName, S } /** - * Deletes an Amazon Lookout for Vision model. - * - * @param lfvClient An Amazon Lookout for Vision client. Returns after the model is deleted. - * @param projectName The name of the project that contains the model that you want to delete. - * @param modelVersion The version of the model that you want to delete. - * @return void - */ + * Deletes an Amazon Lookout for Vision model. + * + * @param lfvClient An Amazon Lookout for Vision client. Returns after the + * model is deleted. + * @param projectName The name of the project that contains the model that you + * want to delete. + * @param modelVersion The version of the model that you want to delete. + * @return void + */ public static void deleteModel(LookoutVisionClient lfvClient, String projectName, String modelVersion) throws LookoutVisionException, InterruptedException { diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/Projects.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/Projects.java index e3e89ccdfb0..ee2745dbd8e 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/Projects.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/Projects.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.projects.complete] @@ -53,7 +51,8 @@ public static ProjectMetadata createProject(LookoutVisionClient lfvClient, Strin } /** - * Lists the Amazon Lookoutfor Vision projects in the current AWS account and AWS + * Lists the Amazon Lookoutfor Vision projects in the current AWS account and + * AWS * Region. * * @param lfvClient An Amazon Lookout for Vision client. diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ShowAnomalies.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ShowAnomalies.java index 42e673f0eee..432c2284991 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ShowAnomalies.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/ShowAnomalies.java @@ -1,8 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.lookoutvision; @@ -36,9 +33,9 @@ // Finds anomalies on a supplied image. public class ShowAnomalies extends JPanel { -/** - * Finds and displays anomalies on a supplied image. - */ + /** + * Finds and displays anomalies on a supplied image. + */ private static final long serialVersionUID = 1L; private transient BufferedImage image; @@ -81,8 +78,7 @@ public ShowAnomalies(LookoutVisionClient lfvClient, String projectName, String m */ DetectAnomalyResult result = response.detectAnomalyResult(); - - if (result.anomalyMask() != null){ + if (result.anomalyMask() != null) { SdkBytes maskSDKBytes = result.anomalyMask(); ByteArrayInputStream maskInputStream = new ByteArrayInputStream(maskSDKBytes.asByteArray()); @@ -109,17 +105,17 @@ public void setWindowDimensions() { } private int drawLine(Graphics2D g2d, String line, FontMetrics metrics, int yPos, Color color) { - /** - * Draws a line of text at the spsecified y position and color. - * confidence - * - * @param g2D The Graphics2D object for the image. - * @param line The line of text to draw. - * @param metrics The font information to use. - * @param yPos The y position for the line of text. - * - * @return The yPos for the next line of text. - */ + /** + * Draws a line of text at the spsecified y position and color. + * confidence + * + * @param g2D The Graphics2D object for the image. + * @param line The line of text to draw. + * @param metrics The font information to use. + * @param yPos The y position for the line of text. + * + * @return The yPos for the next line of text. + */ int indent = 10; @@ -146,18 +142,18 @@ private int drawLine(Graphics2D g2d, String line, FontMetrics metrics, int yPos, } public void drawImageInfo(DetectAnomalyResult result) { - /** - * Draws the results from DetectAnomalies onto the output image. - * - * @param result The response from a call to - * DetectAnomalies. - * - */ + /** + * Draws the results from DetectAnomalies onto the output image. + * + * @param result The response from a call to + * DetectAnomalies. + * + */ // Set up drawing. Graphics2D g2d = image.createGraphics(); - - if (result.anomalyMask() != null){ + + if (result.anomalyMask() != null) { Composite composite = g2d.getComposite(); g2d.setComposite(AlphaComposite.SrcOver.derive(0.5f)); int x = (image.getWidth() - maskImage.getWidth()) / 2; @@ -167,9 +163,8 @@ public void drawImageInfo(DetectAnomalyResult result) { g2d.setComposite(composite); } - //Calculate font size based on arbitary 32 pixel image width. + // Calculate font size based on arbitary 32 pixel image width. int fontSize = (image.getWidth() / 32); - g2d.setFont(new Font("Tahoma", Font.PLAIN, fontSize)); Font font = g2d.getFont(); @@ -302,7 +297,6 @@ public static void main(String[] args) throws Exception { frame.pack(); frame.setVisible(true); - } catch (LookoutVisionException lfvError) { logger.log(Level.SEVERE, "Lookout for Vision client error: {0}: {1}", new Object[] { lfvError.awsErrorDetails().errorCode(), @@ -323,4 +317,3 @@ public static void main(String[] args) throws Exception { } } - diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/StartModel.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/StartModel.java index de9e44f2394..ddc0d5e633c 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/StartModel.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/StartModel.java @@ -1,7 +1,5 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.start_model.complete] diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/StartModelPackagingJob.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/StartModelPackagingJob.java index 85f69954391..dd1855e9a29 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/StartModelPackagingJob.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/StartModelPackagingJob.java @@ -1,7 +1,5 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.start_model_packaging_job.complete] diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/StopModel.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/StopModel.java index 71cdef18659..287e23a57bc 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/StopModel.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/StopModel.java @@ -1,7 +1,5 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.stop_model.complete] diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/TagModel.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/TagModel.java index 89ab6f4d6b3..28dde84360e 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/TagModel.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/TagModel.java @@ -1,7 +1,5 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.tag_model.complete] diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/UntagModel.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/UntagModel.java index d95b41314be..efa69e4ff26 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/UntagModel.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/UntagModel.java @@ -1,7 +1,5 @@ -/* -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.untag_model.complete] diff --git a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/UpdateDatasetEntries.java b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/UpdateDatasetEntries.java index dfe671e9bde..8e46adaa085 100644 --- a/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/UpdateDatasetEntries.java +++ b/javav2/example_code/lookoutvision/src/main/java/com/example/lookoutvision/UpdateDatasetEntries.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[lookoutvision.java2.update_dataset_entries.complete] diff --git a/javav2/example_code/lookoutvision/src/test/java/LookoutVisionTest.java b/javav2/example_code/lookoutvision/src/test/java/LookoutVisionTest.java index 164a9cebef6..be523d30810 100644 --- a/javav2/example_code/lookoutvision/src/test/java/LookoutVisionTest.java +++ b/javav2/example_code/lookoutvision/src/test/java/LookoutVisionTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 /* Unit tests for Amazon Lookout for Vision API examples */ @@ -312,7 +310,7 @@ public void startModel_thenNotEquals() throws IOException, LookoutVisionExceptio public void detectAnomaliesPanel_thenNotNull() throws IOException, LookoutVisionException { float minConfidence = (float) 0.5; - + // Check normal classification DetectAnomalyResult prediction = DetectAnomalies.detectAnomalies(lfvClient, projectName, modelVersion, photo); boolean reject = DetectAnomalies.rejectOnClassification(photo, prediction, minConfidence); diff --git a/javav2/example_code/mediaconvert/run_example.sh b/javav2/example_code/mediaconvert/run_example.sh index 447a688ae0b..892f400bc11 100755 --- a/javav2/example_code/mediaconvert/run_example.sh +++ b/javav2/example_code/mediaconvert/run_example.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 if [[ -z $* ]] ; then echo 'Supply the name of one of the example classes as an argument.' echo 'If there are arguments to the class, put them in quotes after the class name.' diff --git a/javav2/example_code/mediaconvert/src/main/java/com/example/mediaconvert/CreateJob.java b/javav2/example_code/mediaconvert/src/main/java/com/example/mediaconvert/CreateJob.java index 9d3d55adbdf..cdc159ee579 100644 --- a/javav2/example_code/mediaconvert/src/main/java/com/example/mediaconvert/CreateJob.java +++ b/javav2/example_code/mediaconvert/src/main/java/com/example/mediaconvert/CreateJob.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[CreateJob.java demonstrates how to create AWS Elemental MediaConvert jobs.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Elemental MediaConvert] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ // snippet-start:[mediaconvert.java.createjob.complete] package com.example.mediaconvert; @@ -110,7 +105,8 @@ // snippet-end:[mediaconvert.java.createjob.import] /** - * Create a MediaConvert job. Must supply MediaConvert access role Amazon Resource Name (ARN), and a + * Create a MediaConvert job. Must supply MediaConvert access role Amazon + * Resource Name (ARN), and a * valid video input file via Amazon S3 URL. * * Also, set up your development environment, including your credentials. @@ -121,280 +117,399 @@ * */ public class CreateJob { - public static void main(String[] args) { - final String usage = """ + public static void main(String[] args) { + final String usage = """ - Usage: - \s + Usage: + \s - Where: - mcRoleARN - The MediaConvert Role ARN.\s - fileInput - The URL of an Amazon S3 bucket where the input file is located.\s - """; + Where: + mcRoleARN - The MediaConvert Role ARN.\s + fileInput - The URL of an Amazon S3 bucket where the input file is located.\s + """; - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } - String mcRoleARN = args[0]; - String fileInput = args[1]; - Region region = Region.US_WEST_2; - MediaConvertClient mc = MediaConvertClient.builder() - .region(region) - .build(); + String mcRoleARN = args[0]; + String fileInput = args[1]; + Region region = Region.US_WEST_2; + MediaConvertClient mc = MediaConvertClient.builder() + .region(region) + .build(); - String id = createMediaJob(mc, mcRoleARN, fileInput); - System.out.println("MediaConvert job created. Job Id = " +id ); - mc.close(); - } + String id = createMediaJob(mc, mcRoleARN, fileInput); + System.out.println("MediaConvert job created. Job Id = " + id); + mc.close(); + } - public static String createMediaJob(MediaConvertClient mc, String mcRoleARN, String fileInput) { + public static String createMediaJob(MediaConvertClient mc, String mcRoleARN, String fileInput) { - String s3path = fileInput.substring(0, fileInput.lastIndexOf('/') + 1) + "javasdk/out/"; - String fileOutput = s3path + "index"; - String thumbsOutput = s3path + "thumbs/"; - String mp4Output = s3path + "mp4/"; + String s3path = fileInput.substring(0, fileInput.lastIndexOf('/') + 1) + "javasdk/out/"; + String fileOutput = s3path + "index"; + String thumbsOutput = s3path + "thumbs/"; + String mp4Output = s3path + "mp4/"; - try { - // snippet-start:[mediaconvert.java.createjob.getendpointurl] - DescribeEndpointsResponse res = mc - .describeEndpoints(DescribeEndpointsRequest.builder().maxResults(20).build()); + try { + // snippet-start:[mediaconvert.java.createjob.getendpointurl] + DescribeEndpointsResponse res = mc + .describeEndpoints(DescribeEndpointsRequest.builder().maxResults(20).build()); - if (res.endpoints().size() <= 0) { - System.out.println("Cannot find MediaConvert service endpoint URL!"); - System.exit(1); - } - String endpointURL = res.endpoints().get(0).url(); - System.out.println("MediaConvert service URL: " + endpointURL); - System.out.println("MediaConvert role arn: " + mcRoleARN); - System.out.println("MediaConvert input file: " + fileInput); - System.out.println("MediaConvert output path: " + s3path); - // snippet-end:[mediaconvert.java.createjob.getendpointurl] + if (res.endpoints().size() <= 0) { + System.out.println("Cannot find MediaConvert service endpoint URL!"); + System.exit(1); + } + String endpointURL = res.endpoints().get(0).url(); + System.out.println("MediaConvert service URL: " + endpointURL); + System.out.println("MediaConvert role arn: " + mcRoleARN); + System.out.println("MediaConvert input file: " + fileInput); + System.out.println("MediaConvert output path: " + s3path); + // snippet-end:[mediaconvert.java.createjob.getendpointurl] - MediaConvertClient emc = MediaConvertClient.builder() - .region(Region.US_WEST_2) - .endpointOverride(URI.create(endpointURL)) - .build(); + MediaConvertClient emc = MediaConvertClient.builder() + .region(Region.US_WEST_2) + .endpointOverride(URI.create(endpointURL)) + .build(); - // output group Preset HLS low profile - Output hlsLow = createOutput("hls_low", "_low", "_$dt$", 750000, 7, 1920, 1080, 640); - // output group Preset HLS media profile - Output hlsMedium = createOutput("hls_medium", "_medium", "_$dt$", 1200000, 7, 1920, 1080, 1280); - // output group Preset HLS high profole - Output hlsHigh = createOutput("hls_high", "_high", "_$dt$", 3500000, 8, 1920, 1080, 1920); - // snippet-start:[mediaconvert.java.createjob.create_hls_output] + // output group Preset HLS low profile + Output hlsLow = createOutput("hls_low", "_low", "_$dt$", 750000, 7, 1920, 1080, 640); + // output group Preset HLS media profile + Output hlsMedium = createOutput("hls_medium", "_medium", "_$dt$", 1200000, 7, 1920, 1080, 1280); + // output group Preset HLS high profole + Output hlsHigh = createOutput("hls_high", "_high", "_$dt$", 3500000, 8, 1920, 1080, 1920); + // snippet-start:[mediaconvert.java.createjob.create_hls_output] - OutputGroup appleHLS = OutputGroup.builder().name("Apple HLS").customName("Example") - .outputGroupSettings(OutputGroupSettings.builder().type(OutputGroupType.HLS_GROUP_SETTINGS) - .hlsGroupSettings(HlsGroupSettings.builder() - .directoryStructure(HlsDirectoryStructure.SINGLE_DIRECTORY) - .manifestDurationFormat(HlsManifestDurationFormat.INTEGER) - .streamInfResolution(HlsStreamInfResolution.INCLUDE) - .clientCache(HlsClientCache.ENABLED) - .captionLanguageSetting(HlsCaptionLanguageSetting.OMIT) - .manifestCompression(HlsManifestCompression.NONE) - .codecSpecification(HlsCodecSpecification.RFC_4281) - .outputSelection(HlsOutputSelection.MANIFESTS_AND_SEGMENTS) - .programDateTime(HlsProgramDateTime.EXCLUDE).programDateTimePeriod(600) - .timedMetadataId3Frame(HlsTimedMetadataId3Frame.PRIV).timedMetadataId3Period(10) - .destination(fileOutput).segmentControl(HlsSegmentControl.SEGMENTED_FILES) - .minFinalSegmentLength((double) 0).segmentLength(4).minSegmentLength(0).build()) - .build()) - .outputs(hlsLow, hlsMedium, hlsHigh).build(); - // snippet-end:[mediaconvert.java.createjob.create_hls_output] - // snippet-start:[mediaconvert.java.createjob.create_file_output] + OutputGroup appleHLS = OutputGroup.builder().name("Apple HLS").customName("Example") + .outputGroupSettings(OutputGroupSettings.builder() + .type(OutputGroupType.HLS_GROUP_SETTINGS) + .hlsGroupSettings(HlsGroupSettings.builder() + .directoryStructure( + HlsDirectoryStructure.SINGLE_DIRECTORY) + .manifestDurationFormat( + HlsManifestDurationFormat.INTEGER) + .streamInfResolution( + HlsStreamInfResolution.INCLUDE) + .clientCache(HlsClientCache.ENABLED) + .captionLanguageSetting( + HlsCaptionLanguageSetting.OMIT) + .manifestCompression( + HlsManifestCompression.NONE) + .codecSpecification( + HlsCodecSpecification.RFC_4281) + .outputSelection( + HlsOutputSelection.MANIFESTS_AND_SEGMENTS) + .programDateTime(HlsProgramDateTime.EXCLUDE) + .programDateTimePeriod(600) + .timedMetadataId3Frame( + HlsTimedMetadataId3Frame.PRIV) + .timedMetadataId3Period(10) + .destination(fileOutput) + .segmentControl(HlsSegmentControl.SEGMENTED_FILES) + .minFinalSegmentLength((double) 0) + .segmentLength(4).minSegmentLength(0).build()) + .build()) + .outputs(hlsLow, hlsMedium, hlsHigh).build(); + // snippet-end:[mediaconvert.java.createjob.create_hls_output] + // snippet-start:[mediaconvert.java.createjob.create_file_output] - OutputGroup fileMp4 = OutputGroup.builder().name("File Group").customName("mp4") - .outputGroupSettings(OutputGroupSettings.builder().type(OutputGroupType.FILE_GROUP_SETTINGS) - .fileGroupSettings(FileGroupSettings.builder().destination(mp4Output).build()).build()) - .outputs(Output.builder().extension("mp4") - .containerSettings(ContainerSettings.builder().container(ContainerType.MP4).build()) - .videoDescription(VideoDescription.builder().width(1280).height(720) - .scalingBehavior(ScalingBehavior.DEFAULT).sharpness(50).antiAlias(AntiAlias.ENABLED) - .timecodeInsertion(VideoTimecodeInsertion.DISABLED) - .colorMetadata(ColorMetadata.INSERT).respondToAfd(RespondToAfd.NONE) - .afdSignaling(AfdSignaling.NONE).dropFrameTimecode(DropFrameTimecode.ENABLED) - .codecSettings(VideoCodecSettings.builder().codec(VideoCodec.H_264) - .h264Settings(H264Settings.builder() - .rateControlMode(H264RateControlMode.QVBR) - .parControl(H264ParControl.INITIALIZE_FROM_SOURCE) - .qualityTuningLevel(H264QualityTuningLevel.SINGLE_PASS) - .qvbrSettings( - H264QvbrSettings.builder().qvbrQualityLevel(8).build()) - .codecLevel(H264CodecLevel.AUTO).codecProfile(H264CodecProfile.MAIN) - .maxBitrate(2400000) - .framerateControl(H264FramerateControl.INITIALIZE_FROM_SOURCE) - .gopSize(2.0).gopSizeUnits(H264GopSizeUnits.SECONDS) - .numberBFramesBetweenReferenceFrames(2).gopClosedCadence(1) - .gopBReference(H264GopBReference.DISABLED) - .slowPal(H264SlowPal.DISABLED).syntax(H264Syntax.DEFAULT) - .numberReferenceFrames(3).dynamicSubGop(H264DynamicSubGop.STATIC) - .fieldEncoding(H264FieldEncoding.PAFF) - .sceneChangeDetect(H264SceneChangeDetect.ENABLED).minIInterval(0) - .telecine(H264Telecine.NONE) - .framerateConversionAlgorithm( - H264FramerateConversionAlgorithm.DUPLICATE_DROP) - .entropyEncoding(H264EntropyEncoding.CABAC).slices(1) - .unregisteredSeiTimecode(H264UnregisteredSeiTimecode.DISABLED) - .repeatPps(H264RepeatPps.DISABLED) - .adaptiveQuantization(H264AdaptiveQuantization.HIGH) - .spatialAdaptiveQuantization( - H264SpatialAdaptiveQuantization.ENABLED) - .temporalAdaptiveQuantization( - H264TemporalAdaptiveQuantization.ENABLED) - .flickerAdaptiveQuantization( - H264FlickerAdaptiveQuantization.DISABLED) - .softness(0).interlaceMode(H264InterlaceMode.PROGRESSIVE).build()) - .build()) - .build()) - .audioDescriptions(AudioDescription.builder() - .audioTypeControl(AudioTypeControl.FOLLOW_INPUT) - .languageCodeControl(AudioLanguageCodeControl.FOLLOW_INPUT) - .codecSettings(AudioCodecSettings.builder().codec(AudioCodec.AAC) - .aacSettings(AacSettings.builder().codecProfile(AacCodecProfile.LC) - .rateControlMode(AacRateControlMode.CBR) - .codingMode(AacCodingMode.CODING_MODE_2_0).sampleRate(44100) - .bitrate(160000).rawFormat(AacRawFormat.NONE) - .specification(AacSpecification.MPEG4) - .audioDescriptionBroadcasterMix( - AacAudioDescriptionBroadcasterMix.NORMAL) - .build()) - .build()) - .build()) - .build()) - .build(); - // snippet-end:[mediaconvert.java.createjob.create_file_output] - // snippet-start:[mediaconvert.java.createjob.create_thumbnail_output] - OutputGroup thumbs = OutputGroup.builder().name("File Group").customName("thumbs") - .outputGroupSettings(OutputGroupSettings.builder().type(OutputGroupType.FILE_GROUP_SETTINGS) - .fileGroupSettings(FileGroupSettings.builder().destination(thumbsOutput).build()).build()) - .outputs(Output.builder().extension("jpg") - .containerSettings(ContainerSettings.builder().container(ContainerType.RAW).build()) - .videoDescription(VideoDescription.builder().scalingBehavior(ScalingBehavior.DEFAULT) - .sharpness(50).antiAlias(AntiAlias.ENABLED) - .timecodeInsertion(VideoTimecodeInsertion.DISABLED) - .colorMetadata(ColorMetadata.INSERT).dropFrameTimecode(DropFrameTimecode.ENABLED) - .codecSettings(VideoCodecSettings.builder().codec(VideoCodec.FRAME_CAPTURE) - .frameCaptureSettings(FrameCaptureSettings.builder().framerateNumerator(1) - .framerateDenominator(1).maxCaptures(10000000).quality(80).build()) - .build()) - .build()) - .build()) - .build(); + OutputGroup fileMp4 = OutputGroup.builder().name("File Group").customName("mp4") + .outputGroupSettings(OutputGroupSettings.builder() + .type(OutputGroupType.FILE_GROUP_SETTINGS) + .fileGroupSettings(FileGroupSettings.builder() + .destination(mp4Output).build()) + .build()) + .outputs(Output.builder().extension("mp4") + .containerSettings(ContainerSettings.builder() + .container(ContainerType.MP4).build()) + .videoDescription(VideoDescription.builder().width(1280) + .height(720) + .scalingBehavior(ScalingBehavior.DEFAULT) + .sharpness(50).antiAlias(AntiAlias.ENABLED) + .timecodeInsertion( + VideoTimecodeInsertion.DISABLED) + .colorMetadata(ColorMetadata.INSERT) + .respondToAfd(RespondToAfd.NONE) + .afdSignaling(AfdSignaling.NONE) + .dropFrameTimecode(DropFrameTimecode.ENABLED) + .codecSettings(VideoCodecSettings.builder() + .codec(VideoCodec.H_264) + .h264Settings(H264Settings + .builder() + .rateControlMode( + H264RateControlMode.QVBR) + .parControl(H264ParControl.INITIALIZE_FROM_SOURCE) + .qualityTuningLevel( + H264QualityTuningLevel.SINGLE_PASS) + .qvbrSettings( + H264QvbrSettings.builder() + .qvbrQualityLevel( + 8) + .build()) + .codecLevel(H264CodecLevel.AUTO) + .codecProfile(H264CodecProfile.MAIN) + .maxBitrate(2400000) + .framerateControl( + H264FramerateControl.INITIALIZE_FROM_SOURCE) + .gopSize(2.0) + .gopSizeUnits(H264GopSizeUnits.SECONDS) + .numberBFramesBetweenReferenceFrames( + 2) + .gopClosedCadence( + 1) + .gopBReference(H264GopBReference.DISABLED) + .slowPal(H264SlowPal.DISABLED) + .syntax(H264Syntax.DEFAULT) + .numberReferenceFrames( + 3) + .dynamicSubGop(H264DynamicSubGop.STATIC) + .fieldEncoding(H264FieldEncoding.PAFF) + .sceneChangeDetect( + H264SceneChangeDetect.ENABLED) + .minIInterval(0) + .telecine(H264Telecine.NONE) + .framerateConversionAlgorithm( + H264FramerateConversionAlgorithm.DUPLICATE_DROP) + .entropyEncoding( + H264EntropyEncoding.CABAC) + .slices(1) + .unregisteredSeiTimecode( + H264UnregisteredSeiTimecode.DISABLED) + .repeatPps(H264RepeatPps.DISABLED) + .adaptiveQuantization( + H264AdaptiveQuantization.HIGH) + .spatialAdaptiveQuantization( + H264SpatialAdaptiveQuantization.ENABLED) + .temporalAdaptiveQuantization( + H264TemporalAdaptiveQuantization.ENABLED) + .flickerAdaptiveQuantization( + H264FlickerAdaptiveQuantization.DISABLED) + .softness(0) + .interlaceMode(H264InterlaceMode.PROGRESSIVE) + .build()) + .build()) + .build()) + .audioDescriptions(AudioDescription.builder() + .audioTypeControl(AudioTypeControl.FOLLOW_INPUT) + .languageCodeControl( + AudioLanguageCodeControl.FOLLOW_INPUT) + .codecSettings(AudioCodecSettings.builder() + .codec(AudioCodec.AAC) + .aacSettings(AacSettings + .builder() + .codecProfile(AacCodecProfile.LC) + .rateControlMode( + AacRateControlMode.CBR) + .codingMode(AacCodingMode.CODING_MODE_2_0) + .sampleRate(44100) + .bitrate(160000) + .rawFormat(AacRawFormat.NONE) + .specification(AacSpecification.MPEG4) + .audioDescriptionBroadcasterMix( + AacAudioDescriptionBroadcasterMix.NORMAL) + .build()) + .build()) + .build()) + .build()) + .build(); + // snippet-end:[mediaconvert.java.createjob.create_file_output] + // snippet-start:[mediaconvert.java.createjob.create_thumbnail_output] + OutputGroup thumbs = OutputGroup.builder().name("File Group").customName("thumbs") + .outputGroupSettings(OutputGroupSettings.builder() + .type(OutputGroupType.FILE_GROUP_SETTINGS) + .fileGroupSettings(FileGroupSettings.builder() + .destination(thumbsOutput).build()) + .build()) + .outputs(Output.builder().extension("jpg") + .containerSettings(ContainerSettings.builder() + .container(ContainerType.RAW).build()) + .videoDescription(VideoDescription.builder() + .scalingBehavior(ScalingBehavior.DEFAULT) + .sharpness(50).antiAlias(AntiAlias.ENABLED) + .timecodeInsertion( + VideoTimecodeInsertion.DISABLED) + .colorMetadata(ColorMetadata.INSERT) + .dropFrameTimecode(DropFrameTimecode.ENABLED) + .codecSettings(VideoCodecSettings.builder() + .codec(VideoCodec.FRAME_CAPTURE) + .frameCaptureSettings( + FrameCaptureSettings + .builder() + .framerateNumerator( + 1) + .framerateDenominator( + 1) + .maxCaptures(10000000) + .quality(80) + .build()) + .build()) + .build()) + .build()) + .build(); - // snippet-end:[mediaconvert.java.createjob.create_thumbnail_output] - Map audioSelectors = new HashMap<>(); - audioSelectors.put("Audio Selector 1", - AudioSelector.builder().defaultSelection(AudioDefaultSelection.DEFAULT).offset(0).build()); + // snippet-end:[mediaconvert.java.createjob.create_thumbnail_output] + Map audioSelectors = new HashMap<>(); + audioSelectors.put("Audio Selector 1", + AudioSelector.builder().defaultSelection(AudioDefaultSelection.DEFAULT) + .offset(0).build()); - JobSettings jobSettings = JobSettings.builder().inputs(Input.builder().audioSelectors(audioSelectors) - .videoSelector( - VideoSelector.builder().colorSpace(ColorSpace.FOLLOW).rotate(InputRotate.DEGREE_0).build()) - .filterEnable(InputFilterEnable.AUTO).filterStrength(0).deblockFilter(InputDeblockFilter.DISABLED) - .denoiseFilter(InputDenoiseFilter.DISABLED).psiControl(InputPsiControl.USE_PSI) - .timecodeSource(InputTimecodeSource.EMBEDDED).fileInput(fileInput).build()) - .outputGroups(appleHLS, thumbs, fileMp4).build(); + JobSettings jobSettings = JobSettings.builder().inputs(Input.builder() + .audioSelectors(audioSelectors) + .videoSelector( + VideoSelector.builder().colorSpace(ColorSpace.FOLLOW) + .rotate(InputRotate.DEGREE_0).build()) + .filterEnable(InputFilterEnable.AUTO).filterStrength(0) + .deblockFilter(InputDeblockFilter.DISABLED) + .denoiseFilter(InputDenoiseFilter.DISABLED).psiControl(InputPsiControl.USE_PSI) + .timecodeSource(InputTimecodeSource.EMBEDDED).fileInput(fileInput).build()) + .outputGroups(appleHLS, thumbs, fileMp4).build(); - CreateJobRequest createJobRequest = CreateJobRequest.builder().role(mcRoleARN).settings(jobSettings) - .build(); + CreateJobRequest createJobRequest = CreateJobRequest.builder().role(mcRoleARN) + .settings(jobSettings) + .build(); - CreateJobResponse createJobResponse = emc.createJob(createJobRequest); - return createJobResponse.job().id(); + CreateJobResponse createJobResponse = emc.createJob(createJobRequest); + return createJobResponse.job().id(); - } catch (MediaConvertException e) { - System.out.println(e.toString()); - System.exit(0); + } catch (MediaConvertException e) { + System.out.println(e.toString()); + System.exit(0); + } + return ""; } - return ""; - } - // snippet-start:[mediaconvert.java.createjob.create_output] - private final static Output createOutput(String customName, - String nameModifier, - String segmentModifier, - int qvbrMaxBitrate, - int qvbrQualityLevel, - int originWidth, - int originHeight, - int targetWidth) { + // snippet-start:[mediaconvert.java.createjob.create_output] + private final static Output createOutput(String customName, + String nameModifier, + String segmentModifier, + int qvbrMaxBitrate, + int qvbrQualityLevel, + int originWidth, + int originHeight, + int targetWidth) { - int targetHeight = Math.round(originHeight * targetWidth / originWidth) - - (Math.round(originHeight * targetWidth / originWidth) % 4); - Output output = null; - try { - output = Output.builder().nameModifier(nameModifier).outputSettings(OutputSettings.builder() - .hlsSettings(HlsSettings.builder().segmentModifier(segmentModifier).audioGroupId("program_audio") - .iFrameOnlyManifest(HlsIFrameOnlyManifest.EXCLUDE).build()) - .build()) - .containerSettings(ContainerSettings.builder().container(ContainerType.M3_U8) - .m3u8Settings(M3u8Settings.builder().audioFramesPerPes(4) - .pcrControl(M3u8PcrControl.PCR_EVERY_PES_PACKET).pmtPid(480).privateMetadataPid(503) - .programNumber(1).patInterval(0).pmtInterval(0).scte35Source(M3u8Scte35Source.NONE) - .scte35Pid(500).nielsenId3(M3u8NielsenId3.NONE).timedMetadata(TimedMetadata.NONE) - .timedMetadataPid(502).videoPid(481) - .audioPids(482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492).build()) - .build()) - .videoDescription( - VideoDescription.builder().width(targetWidth).height(targetHeight) - .scalingBehavior(ScalingBehavior.DEFAULT).sharpness(50).antiAlias(AntiAlias.ENABLED) - .timecodeInsertion(VideoTimecodeInsertion.DISABLED) - .colorMetadata(ColorMetadata.INSERT).respondToAfd(RespondToAfd.NONE) - .afdSignaling(AfdSignaling.NONE).dropFrameTimecode(DropFrameTimecode.ENABLED) - .codecSettings(VideoCodecSettings.builder().codec(VideoCodec.H_264) - .h264Settings(H264Settings.builder() - .rateControlMode(H264RateControlMode.QVBR) - .parControl(H264ParControl.INITIALIZE_FROM_SOURCE) - .qualityTuningLevel(H264QualityTuningLevel.SINGLE_PASS) - .qvbrSettings(H264QvbrSettings.builder() - .qvbrQualityLevel(qvbrQualityLevel).build()) - .codecLevel(H264CodecLevel.AUTO) - .codecProfile((targetHeight > 720 && targetWidth > 1280) - ? H264CodecProfile.HIGH - : H264CodecProfile.MAIN) - .maxBitrate(qvbrMaxBitrate) - .framerateControl(H264FramerateControl.INITIALIZE_FROM_SOURCE) - .gopSize(2.0).gopSizeUnits(H264GopSizeUnits.SECONDS) - .numberBFramesBetweenReferenceFrames(2).gopClosedCadence(1) - .gopBReference(H264GopBReference.DISABLED) - .slowPal(H264SlowPal.DISABLED).syntax(H264Syntax.DEFAULT) - .numberReferenceFrames(3).dynamicSubGop(H264DynamicSubGop.STATIC) - .fieldEncoding(H264FieldEncoding.PAFF) - .sceneChangeDetect(H264SceneChangeDetect.ENABLED).minIInterval(0) - .telecine(H264Telecine.NONE) - .framerateConversionAlgorithm( - H264FramerateConversionAlgorithm.DUPLICATE_DROP) - .entropyEncoding(H264EntropyEncoding.CABAC).slices(1) - .unregisteredSeiTimecode(H264UnregisteredSeiTimecode.DISABLED) - .repeatPps(H264RepeatPps.DISABLED) - .adaptiveQuantization(H264AdaptiveQuantization.HIGH) - .spatialAdaptiveQuantization( - H264SpatialAdaptiveQuantization.ENABLED) - .temporalAdaptiveQuantization( - H264TemporalAdaptiveQuantization.ENABLED) - .flickerAdaptiveQuantization( - H264FlickerAdaptiveQuantization.DISABLED) - .softness(0).interlaceMode(H264InterlaceMode.PROGRESSIVE).build()) - .build()) - .build()) - .audioDescriptions(AudioDescription.builder().audioTypeControl(AudioTypeControl.FOLLOW_INPUT) - .languageCodeControl(AudioLanguageCodeControl.FOLLOW_INPUT) - .codecSettings(AudioCodecSettings.builder().codec(AudioCodec.AAC).aacSettings(AacSettings - .builder().codecProfile(AacCodecProfile.LC).rateControlMode(AacRateControlMode.CBR) - .codingMode(AacCodingMode.CODING_MODE_2_0).sampleRate(44100).bitrate(96000) - .rawFormat(AacRawFormat.NONE).specification(AacSpecification.MPEG4) - .audioDescriptionBroadcasterMix(AacAudioDescriptionBroadcasterMix.NORMAL).build()) - .build()) - .build()) - .build(); - } catch (MediaConvertException e) { - e.printStackTrace(); - System.exit(0); + int targetHeight = Math.round(originHeight * targetWidth / originWidth) + - (Math.round(originHeight * targetWidth / originWidth) % 4); + Output output = null; + try { + output = Output.builder().nameModifier(nameModifier).outputSettings(OutputSettings.builder() + .hlsSettings(HlsSettings.builder().segmentModifier(segmentModifier) + .audioGroupId("program_audio") + .iFrameOnlyManifest(HlsIFrameOnlyManifest.EXCLUDE).build()) + .build()) + .containerSettings(ContainerSettings.builder().container(ContainerType.M3_U8) + .m3u8Settings(M3u8Settings.builder().audioFramesPerPes(4) + .pcrControl(M3u8PcrControl.PCR_EVERY_PES_PACKET) + .pmtPid(480).privateMetadataPid(503) + .programNumber(1).patInterval(0).pmtInterval(0) + .scte35Source(M3u8Scte35Source.NONE) + .scte35Pid(500).nielsenId3(M3u8NielsenId3.NONE) + .timedMetadata(TimedMetadata.NONE) + .timedMetadataPid(502).videoPid(481) + .audioPids(482, 483, 484, 485, 486, 487, 488, + 489, 490, 491, 492) + .build()) + .build()) + .videoDescription( + VideoDescription.builder().width(targetWidth) + .height(targetHeight) + .scalingBehavior(ScalingBehavior.DEFAULT) + .sharpness(50).antiAlias(AntiAlias.ENABLED) + .timecodeInsertion( + VideoTimecodeInsertion.DISABLED) + .colorMetadata(ColorMetadata.INSERT) + .respondToAfd(RespondToAfd.NONE) + .afdSignaling(AfdSignaling.NONE) + .dropFrameTimecode(DropFrameTimecode.ENABLED) + .codecSettings(VideoCodecSettings.builder() + .codec(VideoCodec.H_264) + .h264Settings(H264Settings + .builder() + .rateControlMode( + H264RateControlMode.QVBR) + .parControl(H264ParControl.INITIALIZE_FROM_SOURCE) + .qualityTuningLevel( + H264QualityTuningLevel.SINGLE_PASS) + .qvbrSettings(H264QvbrSettings + .builder() + .qvbrQualityLevel( + qvbrQualityLevel) + .build()) + .codecLevel(H264CodecLevel.AUTO) + .codecProfile((targetHeight > 720 + && targetWidth > 1280) + ? H264CodecProfile.HIGH + : H264CodecProfile.MAIN) + .maxBitrate(qvbrMaxBitrate) + .framerateControl( + H264FramerateControl.INITIALIZE_FROM_SOURCE) + .gopSize(2.0) + .gopSizeUnits(H264GopSizeUnits.SECONDS) + .numberBFramesBetweenReferenceFrames( + 2) + .gopClosedCadence( + 1) + .gopBReference(H264GopBReference.DISABLED) + .slowPal(H264SlowPal.DISABLED) + .syntax(H264Syntax.DEFAULT) + .numberReferenceFrames( + 3) + .dynamicSubGop(H264DynamicSubGop.STATIC) + .fieldEncoding(H264FieldEncoding.PAFF) + .sceneChangeDetect( + H264SceneChangeDetect.ENABLED) + .minIInterval(0) + .telecine(H264Telecine.NONE) + .framerateConversionAlgorithm( + H264FramerateConversionAlgorithm.DUPLICATE_DROP) + .entropyEncoding( + H264EntropyEncoding.CABAC) + .slices(1) + .unregisteredSeiTimecode( + H264UnregisteredSeiTimecode.DISABLED) + .repeatPps(H264RepeatPps.DISABLED) + .adaptiveQuantization( + H264AdaptiveQuantization.HIGH) + .spatialAdaptiveQuantization( + H264SpatialAdaptiveQuantization.ENABLED) + .temporalAdaptiveQuantization( + H264TemporalAdaptiveQuantization.ENABLED) + .flickerAdaptiveQuantization( + H264FlickerAdaptiveQuantization.DISABLED) + .softness(0) + .interlaceMode(H264InterlaceMode.PROGRESSIVE) + .build()) + .build()) + .build()) + .audioDescriptions(AudioDescription.builder() + .audioTypeControl(AudioTypeControl.FOLLOW_INPUT) + .languageCodeControl(AudioLanguageCodeControl.FOLLOW_INPUT) + .codecSettings(AudioCodecSettings.builder() + .codec(AudioCodec.AAC).aacSettings(AacSettings + .builder() + .codecProfile(AacCodecProfile.LC) + .rateControlMode( + AacRateControlMode.CBR) + .codingMode(AacCodingMode.CODING_MODE_2_0) + .sampleRate(44100) + .bitrate(96000) + .rawFormat(AacRawFormat.NONE) + .specification(AacSpecification.MPEG4) + .audioDescriptionBroadcasterMix( + AacAudioDescriptionBroadcasterMix.NORMAL) + .build()) + .build()) + .build()) + .build(); + } catch (MediaConvertException e) { + e.printStackTrace(); + System.exit(0); + } + return output; } - return output; - } - // snippet-end:[mediaconvert.java.createjob.create_output] - // snippet-start:[mediaconvert.java.createjob.main] + // snippet-end:[mediaconvert.java.createjob.create_output] + // snippet-start:[mediaconvert.java.createjob.main] } // snippet-end:[mediaconvert.java.createjob.main] // snippet-end:[mediaconvert.java.createjob.complete] \ No newline at end of file diff --git a/javav2/example_code/mediaconvert/src/main/java/com/example/mediaconvert/GetEndpointURL.java b/javav2/example_code/mediaconvert/src/main/java/com/example/mediaconvert/GetEndpointURL.java index 485afdeab82..27064ac9b7e 100644 --- a/javav2/example_code/mediaconvert/src/main/java/com/example/mediaconvert/GetEndpointURL.java +++ b/javav2/example_code/mediaconvert/src/main/java/com/example/mediaconvert/GetEndpointURL.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[getEndpointURL.java demonstrates how to get an endpoint URL for an AWS Elemental MediaConvert account.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Elemental MediaConvert] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.mediaconvert; @@ -23,7 +17,8 @@ // snippet-start:[mediaconvert.java.getendpointurl.main] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -34,11 +29,11 @@ public static void main(String[] args) { // snippet-start:[mediaconvert.java.getendpointurl.build_mediaconvertclient] Region region = Region.US_WEST_2; MediaConvertClient mc = MediaConvertClient.builder() - .region(region) - .build(); + .region(region) + .build(); // snippet-end:[mediaconvert.java.getendpointurl.build_mediaconvertclient] - getEndpoint(mc) ; + getEndpoint(mc); mc.close(); } @@ -46,8 +41,8 @@ public static void main(String[] args) { public static void getEndpoint(MediaConvertClient mc) { try { DescribeEndpointsRequest request = DescribeEndpointsRequest.builder() - .maxResults(20) - .build(); + .maxResults(20) + .build(); DescribeEndpointsResponse res = mc.describeEndpoints(request); Iterator endpoints = res.endpoints().iterator(); diff --git a/javav2/example_code/mediaconvert/src/main/java/com/example/mediaconvert/GetJob.java b/javav2/example_code/mediaconvert/src/main/java/com/example/mediaconvert/GetJob.java index f3380cab197..7701090d667 100644 --- a/javav2/example_code/mediaconvert/src/main/java/com/example/mediaconvert/GetJob.java +++ b/javav2/example_code/mediaconvert/src/main/java/com/example/mediaconvert/GetJob.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[GetJob.java demonstrates how to get information about a specific AWS Elemental MediaConvert job.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Elemental MediaConvert] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.mediaconvert; @@ -22,7 +16,8 @@ // snippet-end:[mediaconvert.java.get_job.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -33,9 +28,9 @@ public class GetJob { public static void main(String[] args) { final String usage = "\n" + - " \n\n" + - "Where:\n" + - " jobId - The job id value.\n\n"; + " \n\n" + + "Where:\n" + + " jobId - The job id value.\n\n"; if (args.length != 1) { System.out.println(usage); @@ -45,8 +40,8 @@ public static void main(String[] args) { String jobId = args[0]; Region region = Region.US_WEST_2; MediaConvertClient mc = MediaConvertClient.builder() - .region(region) - .build(); + .region(region) + .build(); getSpecificJob(mc, jobId); mc.close(); @@ -55,8 +50,8 @@ public static void main(String[] args) { public static void getSpecificJob(MediaConvertClient mc, String jobId) { try { DescribeEndpointsResponse res = mc.describeEndpoints(DescribeEndpointsRequest.builder() - .maxResults(20) - .build()); + .maxResults(20) + .build()); if (res.endpoints().size() <= 0) { System.out.println("Cannot find MediaConvert service endpoint URL!"); @@ -64,13 +59,13 @@ public static void getSpecificJob(MediaConvertClient mc, String jobId) { } String endpointURL = res.endpoints().get(0).url(); MediaConvertClient emc = MediaConvertClient.builder() - .region(Region.US_WEST_2) - .endpointOverride(URI.create(endpointURL)) - .build(); + .region(Region.US_WEST_2) + .endpointOverride(URI.create(endpointURL)) + .build(); GetJobRequest jobRequest = GetJobRequest.builder() - .id(jobId) - .build(); + .id(jobId) + .build(); GetJobResponse response = emc.getJob(jobRequest); System.out.println("The ARN of the job is " + response.job().arn()); diff --git a/javav2/example_code/mediaconvert/src/main/java/com/example/mediaconvert/ListJobs.java b/javav2/example_code/mediaconvert/src/main/java/com/example/mediaconvert/ListJobs.java index de8db6dcd87..4174bee76a4 100644 --- a/javav2/example_code/mediaconvert/src/main/java/com/example/mediaconvert/ListJobs.java +++ b/javav2/example_code/mediaconvert/src/main/java/com/example/mediaconvert/ListJobs.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[ListJobs.java demonstrates how to get information about all completed AWS Elemental MediaConvert jobs.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Elemental MediaConvert] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.mediaconvert; @@ -24,7 +18,8 @@ // snippet-end:[mediaconvert.java.list_jobs.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -34,17 +29,18 @@ public class ListJobs { public static void main(String[] args) { Region region = Region.US_WEST_2; MediaConvertClient mc = MediaConvertClient.builder() - .region(region) - .build(); + .region(region) + .build(); listCompleteJobs(mc); mc.close(); } + public static void listCompleteJobs(MediaConvertClient mc) { try { DescribeEndpointsResponse res = mc.describeEndpoints(DescribeEndpointsRequest.builder() - .maxResults(20) - .build()); + .maxResults(20) + .build()); if (res.endpoints().size() <= 0) { System.out.println("Cannot find MediaConvert service endpoint URL!"); @@ -53,14 +49,14 @@ public static void listCompleteJobs(MediaConvertClient mc) { String endpointURL = res.endpoints().get(0).url(); MediaConvertClient emc = MediaConvertClient.builder() - .region(Region.US_WEST_2) - .endpointOverride(URI.create(endpointURL)) - .build(); + .region(Region.US_WEST_2) + .endpointOverride(URI.create(endpointURL)) + .build(); ListJobsRequest jobsRequest = ListJobsRequest.builder() - .maxResults(10) - .status("COMPLETE") - .build(); + .maxResults(10) + .status("COMPLETE") + .build(); ListJobsResponse jobsResponse = emc.listJobs(jobsRequest); List jobs = jobsResponse.jobs(); diff --git a/javav2/example_code/mediaconvert/src/test/java/AmazonMediaConvertTest.java b/javav2/example_code/mediaconvert/src/test/java/AmazonMediaConvertTest.java index f081c984b35..1672241d505 100644 --- a/javav2/example_code/mediaconvert/src/test/java/AmazonMediaConvertTest.java +++ b/javav2/example_code/mediaconvert/src/test/java/AmazonMediaConvertTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.mediaconvert.CreateJob; import com.example.mediaconvert.GetEndpointURL; @@ -27,8 +25,8 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AmazonMediaConvertTest { - private static MediaConvertClient mc ; - private static Region region ; + private static MediaConvertClient mc; + private static Region region; private static String mcRoleARN = ""; private static String fileInput = ""; private static String jobId = ""; @@ -37,9 +35,9 @@ public class AmazonMediaConvertTest { public static void setUp() throws IOException { region = Region.US_WEST_2; mc = MediaConvertClient.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -48,23 +46,26 @@ public static void setUp() throws IOException { mcRoleARN = values.getMcRoleARN(); fileInput = values.getFileInput(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - try (InputStream input = AmazonMediaConvertTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - prop.load(input); - mcRoleARN = prop.getProperty("mcRoleARN"); - fileInput = prop.getProperty("fileInput"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * try (InputStream input = + * AmazonMediaConvertTest.class.getClassLoader().getResourceAsStream( + * "config.properties")) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * prop.load(input); + * mcRoleARN = prop.getProperty("mcRoleARN"); + * fileInput = prop.getProperty("fileInput"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @@ -80,7 +81,7 @@ public void CreateJob() { @Tag("IntegrationTest") @Order(2) public void GetEndpointURL() { - assertDoesNotThrow(() ->GetEndpointURL.getEndpoint(mc)); + assertDoesNotThrow(() -> GetEndpointURL.getEndpoint(mc)); System.out.println("Test 2 passed"); } @@ -88,7 +89,7 @@ public void GetEndpointURL() { @Tag("IntegrationTest") @Order(3) public void ListJobs() { - assertDoesNotThrow(() ->ListJobs.listCompleteJobs(mc)); + assertDoesNotThrow(() -> ListJobs.listCompleteJobs(mc)); System.out.println("Test 3 passed"); } @@ -99,16 +100,17 @@ public void GetJob() { assertDoesNotThrow(() -> GetJob.getSpecificJob(mc, jobId)); System.out.println("Test 4 passed"); } + private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/mediaconvert"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -131,4 +133,3 @@ public String getFileInput() { } } - diff --git a/javav2/example_code/mediastore/src/main/java/com/example/mediastore/CreateContainer.java b/javav2/example_code/mediastore/src/main/java/com/example/mediastore/CreateContainer.java index 04050bbf2ca..82924fce8b6 100644 --- a/javav2/example_code/mediastore/src/main/java/com/example/mediastore/CreateContainer.java +++ b/javav2/example_code/mediastore/src/main/java/com/example/mediastore/CreateContainer.java @@ -1,25 +1,20 @@ -//snippet-sourcedescription:[CreateContainer.java demonstrates how to create an AWS Elemental MediaStore container.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Elemental MediaStore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.mediastore; -//snippet-start:[mediastore.java2.create_container.main] -//snippet-start:[mediastore.java2.create_container.import] +// snippet-start:[mediastore.java2.create_container.main] +// snippet-start:[mediastore.java2.create_container.import] import software.amazon.awssdk.services.mediastore.MediaStoreClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.mediastore.model.CreateContainerRequest; import software.amazon.awssdk.services.mediastore.model.CreateContainerResponse; import software.amazon.awssdk.services.mediastore.model.MediaStoreException; -//snippet-end:[mediastore.java2.create_container.import] +// snippet-end:[mediastore.java2.create_container.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,11 +26,11 @@ public class CreateContainer { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - containerName - The name of the container to create. - """; + Where: + containerName - The name of the container to create. + """; if (args.length != 1) { System.out.println(usage); @@ -45,8 +40,8 @@ public static void main(String[] args) { String containerName = args[0]; Region region = Region.US_EAST_1; MediaStoreClient mediaStoreClient = MediaStoreClient.builder() - .region(region) - .build(); + .region(region) + .build(); createMediaContainer(mediaStoreClient, containerName); mediaStoreClient.close(); @@ -55,8 +50,8 @@ public static void main(String[] args) { public static void createMediaContainer(MediaStoreClient mediaStoreClient, String containerName) { try { CreateContainerRequest containerRequest = CreateContainerRequest.builder() - .containerName(containerName) - .build(); + .containerName(containerName) + .build(); CreateContainerResponse containerResponse = mediaStoreClient.createContainer(containerRequest); String status = containerResponse.container().status().toString(); @@ -75,4 +70,4 @@ public static void createMediaContainer(MediaStoreClient mediaStoreClient, Strin } } } -//snippet-end:[mediastore.java2.create_container.main] +// snippet-end:[mediastore.java2.create_container.main] diff --git a/javav2/example_code/mediastore/src/main/java/com/example/mediastore/DeleteContainer.java b/javav2/example_code/mediastore/src/main/java/com/example/mediastore/DeleteContainer.java index 810aadf9026..67e1e38ff26 100644 --- a/javav2/example_code/mediastore/src/main/java/com/example/mediastore/DeleteContainer.java +++ b/javav2/example_code/mediastore/src/main/java/com/example/mediastore/DeleteContainer.java @@ -1,24 +1,19 @@ -//snippet-sourcedescription:[DeleteContainer.java demonstrates how to delete a given AWS Elemental MediaStore container.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Elemental MediaStore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.mediastore; -//snippet-start:[mediastore.java2.delete_container.main] -//snippet-start:[mediastore.java2.delete_container.import] +// snippet-start:[mediastore.java2.delete_container.main] +// snippet-start:[mediastore.java2.delete_container.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.mediastore.MediaStoreClient; import software.amazon.awssdk.services.mediastore.model.DeleteContainerRequest; import software.amazon.awssdk.services.mediastore.model.MediaStoreException; -//snippet-end:[mediastore.java2.delete_container.import] +// snippet-end:[mediastore.java2.delete_container.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,11 +23,11 @@ public class DeleteContainer { public static void main(String[] args) { final String usage = """ - Usage: DeleteContainer + Usage: DeleteContainer - Where: - containerName - The name of the container to delete. - """; + Where: + containerName - The name of the container to delete. + """; if (args.length != 1) { System.out.println(usage); @@ -42,8 +37,8 @@ public static void main(String[] args) { String containerName = args[0]; Region region = Region.US_EAST_1; MediaStoreClient mediaStoreClient = MediaStoreClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteMediaContainer(mediaStoreClient, containerName); mediaStoreClient.close(); @@ -52,8 +47,8 @@ public static void main(String[] args) { public static void deleteMediaContainer(MediaStoreClient mediaStoreClient, String containerName) { try { DeleteContainerRequest deleteContainerRequest = DeleteContainerRequest.builder() - .containerName(containerName) - .build(); + .containerName(containerName) + .build(); mediaStoreClient.deleteContainer(deleteContainerRequest); @@ -63,4 +58,4 @@ public static void deleteMediaContainer(MediaStoreClient mediaStoreClient, Strin } } } -//snippet-end:[mediastore.java2.delete_container.main] +// snippet-end:[mediastore.java2.delete_container.main] diff --git a/javav2/example_code/mediastore/src/main/java/com/example/mediastore/DeleteObject.java b/javav2/example_code/mediastore/src/main/java/com/example/mediastore/DeleteObject.java index 443405f1a8a..aa83cc14695 100644 --- a/javav2/example_code/mediastore/src/main/java/com/example/mediastore/DeleteObject.java +++ b/javav2/example_code/mediastore/src/main/java/com/example/mediastore/DeleteObject.java @@ -1,16 +1,10 @@ -//snippet-sourcedescription:[DeleteObject.java demonstrates how to delete an object within an AWS Elemental MediaStore container.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Elemental MediaStore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.mediastore; -//snippet-start:[mediastore.java2.delete_object.main] -//snippet-start:[mediastore.java2.delete_object.import] +// snippet-start:[mediastore.java2.delete_object.main] +// snippet-start:[mediastore.java2.delete_object.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.mediastore.MediaStoreClient; import software.amazon.awssdk.services.mediastore.model.DescribeContainerRequest; @@ -20,10 +14,11 @@ import software.amazon.awssdk.services.mediastoredata.model.MediaStoreDataException; import java.net.URI; import java.net.URISyntaxException; -//snippet-end:[mediastore.java2.delete_object.import] +// snippet-end:[mediastore.java2.delete_object.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -33,12 +28,12 @@ public class DeleteObject { public static void main(String[] args) throws URISyntaxException { final String usage = """ - Usage: + Usage: - Where: - completePath - The path (including the container) of the item to delete. - containerName - The name of the container. - """; + Where: + completePath - The path (including the container) of the item to delete. + containerName - The name of the container. + """; if (args.length != 2) { System.out.println(usage); @@ -51,9 +46,9 @@ public static void main(String[] args) throws URISyntaxException { URI uri = new URI(getEndpoint(containerName)); MediaStoreDataClient mediaStoreData = MediaStoreDataClient.builder() - .endpointOverride(uri) - .region(region) - .build(); + .endpointOverride(uri) + .region(region) + .build(); deleteMediaObject(mediaStoreData, completePath); mediaStoreData.close(); @@ -62,8 +57,8 @@ public static void main(String[] args) throws URISyntaxException { public static void deleteMediaObject(MediaStoreDataClient mediaStoreData, String completePath) { try { DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder() - .path(completePath) - .build(); + .path(completePath) + .build(); mediaStoreData.deleteObject(deleteObjectRequest); @@ -76,16 +71,16 @@ public static void deleteMediaObject(MediaStoreDataClient mediaStoreData, String private static String getEndpoint(String containerName) { Region region = Region.US_EAST_1; MediaStoreClient mediaStoreClient = MediaStoreClient.builder() - .region(region) - .build(); + .region(region) + .build(); DescribeContainerRequest containerRequest = DescribeContainerRequest.builder() - .containerName(containerName) - .build(); + .containerName(containerName) + .build(); DescribeContainerResponse response = mediaStoreClient.describeContainer(containerRequest); mediaStoreClient.close(); return response.container().endpoint(); } } -//snippet-end:[mediastore.java2.delete_object.main] +// snippet-end:[mediastore.java2.delete_object.main] diff --git a/javav2/example_code/mediastore/src/main/java/com/example/mediastore/DescribeContainer.java b/javav2/example_code/mediastore/src/main/java/com/example/mediastore/DescribeContainer.java index 4800abb61dc..0d5bbf83a88 100644 --- a/javav2/example_code/mediastore/src/main/java/com/example/mediastore/DescribeContainer.java +++ b/javav2/example_code/mediastore/src/main/java/com/example/mediastore/DescribeContainer.java @@ -1,25 +1,20 @@ -//snippet-sourcedescription:[DescribeContainer.java demonstrates how to describe a given AWS Elemental MediaStore container.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Elemental MediaStore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.mediastore; -//snippet-start:[mediastore.java2.describe_container.main] -//snippet-start:[mediastore.java2.describe_container.import] +// snippet-start:[mediastore.java2.describe_container.main] +// snippet-start:[mediastore.java2.describe_container.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.mediastore.MediaStoreClient; import software.amazon.awssdk.services.mediastore.model.DescribeContainerRequest; import software.amazon.awssdk.services.mediastore.model.DescribeContainerResponse; import software.amazon.awssdk.services.mediastore.model.MediaStoreException; -//snippet-end:[mediastore.java2.describe_container.import] +// snippet-end:[mediastore.java2.describe_container.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,11 +25,11 @@ public class DescribeContainer { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - containerName - The name of the container to describe. - """; + Where: + containerName - The name of the container to describe. + """; if (args.length != 1) { System.out.println(usage); @@ -44,8 +39,8 @@ public static void main(String[] args) { String containerName = args[0]; Region region = Region.US_EAST_1; MediaStoreClient mediaStoreClient = MediaStoreClient.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.println("Status is " + checkContainer(mediaStoreClient, containerName)); mediaStoreClient.close(); @@ -54,8 +49,8 @@ public static void main(String[] args) { public static String checkContainer(MediaStoreClient mediaStoreClient, String containerName) { try { DescribeContainerRequest describeContainerRequest = DescribeContainerRequest.builder() - .containerName(containerName) - .build(); + .containerName(containerName) + .build(); DescribeContainerResponse containerResponse = mediaStoreClient.describeContainer(describeContainerRequest); System.out.println("The container name is " + containerResponse.container().name()); @@ -69,4 +64,4 @@ public static String checkContainer(MediaStoreClient mediaStoreClient, String co return ""; } } -//snippet-end:[mediastore.java2.describe_container.main] +// snippet-end:[mediastore.java2.describe_container.main] diff --git a/javav2/example_code/mediastore/src/main/java/com/example/mediastore/GetObject.java b/javav2/example_code/mediastore/src/main/java/com/example/mediastore/GetObject.java index 5ccfed265c2..1396d90fc6a 100644 --- a/javav2/example_code/mediastore/src/main/java/com/example/mediastore/GetObject.java +++ b/javav2/example_code/mediastore/src/main/java/com/example/mediastore/GetObject.java @@ -1,16 +1,10 @@ -//snippet-sourcedescription:[GetObject.java demonstrates how to download a file from an AWS Elemental MediaStore container.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Elemental MediaStore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.mediastore; -//snippet-start:[mediastore.java2.get_object.main] -//snippet-start:[mediastore.java2.get_object.import] +// snippet-start:[mediastore.java2.get_object.main] +// snippet-start:[mediastore.java2.get_object.import] import software.amazon.awssdk.core.ResponseInputStream; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.mediastore.MediaStoreClient; @@ -26,10 +20,11 @@ import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; -//snippet-end:[mediastore.java2.get_object.import] +// snippet-end:[mediastore.java2.get_object.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -39,13 +34,13 @@ public class GetObject { public static void main(String[] args) throws URISyntaxException { final String usage = """ - Usage: + Usage: - Where: - completePath - The path of the object in the container (for example, Videos5/sampleVideo.mp4). - containerName - The name of the container. - savePath - The path on the local drive where the file is saved, including the file name (for example, C:/AWS/myvid.mp4). - """; + Where: + completePath - The path of the object in the container (for example, Videos5/sampleVideo.mp4). + containerName - The name of the container. + savePath - The path on the local drive where the file is saved, including the file name (for example, C:/AWS/myvid.mp4). + """; if (args.length != 3) { System.out.println(usage); @@ -59,9 +54,9 @@ public static void main(String[] args) throws URISyntaxException { Region region = Region.US_EAST_1; URI uri = new URI(getEndpoint(containerName)); MediaStoreDataClient mediaStoreData = MediaStoreDataClient.builder() - .endpointOverride(uri) - .region(region) - .build(); + .endpointOverride(uri) + .region(region) + .build(); getMediaObject(mediaStoreData, completePath, savePath); mediaStoreData.close(); @@ -71,8 +66,8 @@ public static void getMediaObject(MediaStoreDataClient mediaStoreData, String co try { GetObjectRequest objectRequest = GetObjectRequest.builder() - .path(completePath) - .build(); + .path(completePath) + .build(); // Write out the data to a file. ResponseInputStream data = mediaStoreData.getObject(objectRequest); @@ -93,15 +88,15 @@ public static void getMediaObject(MediaStoreDataClient mediaStoreData, String co private static String getEndpoint(String containerName) { Region region = Region.US_EAST_1; MediaStoreClient mediaStoreClient = MediaStoreClient.builder() - .region(region) - .build(); + .region(region) + .build(); DescribeContainerRequest containerRequest = DescribeContainerRequest.builder() - .containerName(containerName) - .build(); + .containerName(containerName) + .build(); DescribeContainerResponse response = mediaStoreClient.describeContainer(containerRequest); return response.container().endpoint(); } } -//snippet-end:[mediastore.java2.get_object.main] +// snippet-end:[mediastore.java2.get_object.main] diff --git a/javav2/example_code/mediastore/src/main/java/com/example/mediastore/ListContainers.java b/javav2/example_code/mediastore/src/main/java/com/example/mediastore/ListContainers.java index a144c6b93f9..3b655a20ff1 100644 --- a/javav2/example_code/mediastore/src/main/java/com/example/mediastore/ListContainers.java +++ b/javav2/example_code/mediastore/src/main/java/com/example/mediastore/ListContainers.java @@ -1,16 +1,10 @@ -//snippet-sourcedescription:[ListContainers.java demonstrates how to list your AWS Elemental MediaStore containers.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Elemental MediaStore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.mediastore; -//snippet-start:[mediastore.java2.list_containers.main] -//snippet-start:[mediastore.java2.list_containers.import] +// snippet-start:[mediastore.java2.list_containers.main] +// snippet-start:[mediastore.java2.list_containers.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.mediastore.MediaStoreClient; @@ -18,10 +12,11 @@ import software.amazon.awssdk.services.mediastore.model.ListContainersResponse; import software.amazon.awssdk.services.mediastore.model.MediaStoreException; import java.util.List; -//snippet-end:[mediastore.java2.list_containers.import] +// snippet-end:[mediastore.java2.list_containers.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -33,8 +28,8 @@ public static void main(String[] args) { Region region = Region.US_EAST_1; MediaStoreClient mediaStoreClient = MediaStoreClient.builder() - .region(region) - .build(); + .region(region) + .build(); listAllContainers(mediaStoreClient); mediaStoreClient.close(); @@ -54,4 +49,4 @@ public static void listAllContainers(MediaStoreClient mediaStoreClient) { } } } -//snippet-end:[mediastore.java2.list_containers.main] +// snippet-end:[mediastore.java2.list_containers.main] diff --git a/javav2/example_code/mediastore/src/main/java/com/example/mediastore/ListItems.java b/javav2/example_code/mediastore/src/main/java/com/example/mediastore/ListItems.java index 220fe1c5719..c654f08cb5a 100644 --- a/javav2/example_code/mediastore/src/main/java/com/example/mediastore/ListItems.java +++ b/javav2/example_code/mediastore/src/main/java/com/example/mediastore/ListItems.java @@ -1,35 +1,27 @@ -//snippet-sourcedescription:[ListItems.java demonstrates how to list objects and folders within an AWS Elemental MediaStore container.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[AWS Elemental MediaStore] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[05/18/2022] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.mediastore; -//snippet-start:[mediastore.java2.list_items.main] -//snippet-start:[mediastore.java2.list_items.import] +// snippet-start:[mediastore.java2.list_items.main] +// snippet-start:[mediastore.java2.list_items.import] import java.net.URI; import java.net.URISyntaxException; import java.util.List; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.mediastore.MediaStoreClient; -import software.amazon.awssdk.services.mediastoredata.MediaStoreDataClient ; +import software.amazon.awssdk.services.mediastoredata.MediaStoreDataClient; import software.amazon.awssdk.services.mediastoredata.model.ListItemsResponse; import software.amazon.awssdk.services.mediastoredata.model.ListItemsRequest; import software.amazon.awssdk.services.mediastoredata.model.Item; import software.amazon.awssdk.services.mediastoredata.model.MediaStoreDataException; import software.amazon.awssdk.services.mediastore.model.DescribeContainerRequest; import software.amazon.awssdk.services.mediastore.model.DescribeContainerResponse; -//snippet-end:[mediastore.java2.list_items.import] +// snippet-end:[mediastore.java2.list_items.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -40,11 +32,11 @@ public class ListItems { public static void main(String[] args) throws URISyntaxException { final String usage = """ - Usage: ListItems + Usage: ListItems - Where: - containerName - The name of the container. - completePath - The path in the container where the objects are located (for example, /Videos5)."""; + Where: + containerName - The name of the container. + completePath - The path in the container where the objects are located (for example, /Videos5)."""; if (args.length != 1) { System.out.println(usage); @@ -57,9 +49,9 @@ public static void main(String[] args) throws URISyntaxException { URI uri = new URI(getEndpoint(containerName)); MediaStoreDataClient mediaStoreData = MediaStoreDataClient.builder() - .endpointOverride(uri) - .region(region) - .build(); + .endpointOverride(uri) + .region(region) + .build(); listAllItems(mediaStoreData, completePath); mediaStoreData.close(); @@ -68,8 +60,8 @@ public static void main(String[] args) throws URISyntaxException { public static void listAllItems(MediaStoreDataClient mediaStoreData, String completePath) { try { ListItemsRequest itemsRequest = ListItemsRequest.builder() - .path(completePath) - .build(); + .path(completePath) + .build(); ListItemsResponse itemsResponse = mediaStoreData.listItems(itemsRequest); boolean hasItems = itemsResponse.hasItems(); @@ -92,15 +84,15 @@ public static void listAllItems(MediaStoreDataClient mediaStoreData, String comp private static String getEndpoint(String containerName) { Region region = Region.US_EAST_1; MediaStoreClient mediaStoreClient = MediaStoreClient.builder() - .region(region) - .build(); + .region(region) + .build(); DescribeContainerRequest containerRequest = DescribeContainerRequest.builder() - .containerName(containerName) - .build(); + .containerName(containerName) + .build(); DescribeContainerResponse response = mediaStoreClient.describeContainer(containerRequest); return response.container().endpoint(); } } -//snippet-end:[mediastore.java2.list_items.main] +// snippet-end:[mediastore.java2.list_items.main] diff --git a/javav2/example_code/mediastore/src/main/java/com/example/mediastore/PutObject.java b/javav2/example_code/mediastore/src/main/java/com/example/mediastore/PutObject.java index 75cc612529c..0f96efc421c 100644 --- a/javav2/example_code/mediastore/src/main/java/com/example/mediastore/PutObject.java +++ b/javav2/example_code/mediastore/src/main/java/com/example/mediastore/PutObject.java @@ -1,19 +1,13 @@ -//snippet-sourcedescription:[PutObject.java demonstrates how to upload a MP4 file to an AWS Elemental MediaStore container.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Elemental MediaStore] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.mediastore; -//snippet-start:[mediastore.java2.put_object.main] -//snippet-start:[mediastore.java2.put_object.import] +// snippet-start:[mediastore.java2.put_object.main] +// snippet-start:[mediastore.java2.put_object.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.mediastore.MediaStoreClient; -import software.amazon.awssdk.services.mediastoredata.MediaStoreDataClient ; +import software.amazon.awssdk.services.mediastoredata.MediaStoreDataClient; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.services.mediastoredata.model.PutObjectRequest; import software.amazon.awssdk.services.mediastoredata.model.MediaStoreDataException; @@ -23,10 +17,11 @@ import java.io.File; import java.net.URI; import java.net.URISyntaxException; -//snippet-end:[mediastore.java2.put_object.import] +// snippet-end:[mediastore.java2.put_object.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -36,10 +31,10 @@ public class PutObject { public static void main(String[] args) throws URISyntaxException { final String USAGE = """ - To run this example, supply the name of a container, a file location to use, and path in the container\s + To run this example, supply the name of a container, a file location to use, and path in the container\s - Ex: - """; + Ex: + """; if (args.length < 3) { System.out.println(USAGE); @@ -53,9 +48,9 @@ public static void main(String[] args) throws URISyntaxException { Region region = Region.US_EAST_1; URI uri = new URI(getEndpoint(containerName)); MediaStoreDataClient mediaStoreData = MediaStoreDataClient.builder() - .endpointOverride(uri) - .region(region) - .build(); + .endpointOverride(uri) + .region(region) + .build(); putMediaObject(mediaStoreData, filePath, completePath); mediaStoreData.close(); @@ -67,9 +62,9 @@ public static void putMediaObject(MediaStoreDataClient mediaStoreData, String fi RequestBody requestBody = RequestBody.fromFile(myFile); PutObjectRequest objectRequest = PutObjectRequest.builder() - .path(completePath) - .contentType("video/mp4") - .build(); + .path(completePath) + .contentType("video/mp4") + .build(); PutObjectResponse response = mediaStoreData.putObject(objectRequest, requestBody); System.out.println("The saved object is " + response.storageClass().toString()); @@ -84,15 +79,15 @@ public static String getEndpoint(String containerName) { Region region = Region.US_EAST_1; MediaStoreClient mediaStoreClient = MediaStoreClient.builder() - .region(region) - .build(); + .region(region) + .build(); DescribeContainerRequest containerRequest = DescribeContainerRequest.builder() - .containerName(containerName) - .build(); + .containerName(containerName) + .build(); DescribeContainerResponse response = mediaStoreClient.describeContainer(containerRequest); return response.container().endpoint(); } } -//snippet-end:[mediastore.java2.put_object.main] +// snippet-end:[mediastore.java2.put_object.main] diff --git a/javav2/example_code/mediastore/src/test/java/MediaStoreTest.java b/javav2/example_code/mediastore/src/test/java/MediaStoreTest.java index f768e26d295..a64ef2958c2 100644 --- a/javav2/example_code/mediastore/src/test/java/MediaStoreTest.java +++ b/javav2/example_code/mediastore/src/test/java/MediaStoreTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.mediastore.*; import com.google.gson.Gson; @@ -9,7 +7,7 @@ import software.amazon.awssdk.services.mediastore.MediaStoreClient; import software.amazon.awssdk.services.mediastore.model.DescribeContainerRequest; import software.amazon.awssdk.services.mediastore.model.DescribeContainerResponse; -import software.amazon.awssdk.services.mediastoredata.MediaStoreDataClient ; +import software.amazon.awssdk.services.mediastoredata.MediaStoreDataClient; import org.junit.jupiter.api.*; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; @@ -29,52 +27,56 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class MediaStoreTest { private static MediaStoreClient mediaStoreClient; - private static MediaStoreDataClient mediaStoreData; - private static String containerName =""; - private static String filePath =""; - private static String completePath =""; - private static String existingContainer =""; - private static String savePath =""; + private static MediaStoreDataClient mediaStoreData; + private static String containerName = ""; + private static String filePath = ""; + private static String completePath = ""; + private static String existingContainer = ""; + private static String savePath = ""; @BeforeAll public static void setUp() throws URISyntaxException { Region region = Region.US_EAST_1; mediaStoreClient = MediaStoreClient.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); String json = getSecretValues(); SecretValues values = gson.fromJson(json, SecretValues.class); - containerName = values.getContainerName()+ java.util.UUID.randomUUID(); + containerName = values.getContainerName() + java.util.UUID.randomUUID(); filePath = values.getFilePath(); completePath = values.getCompletePath(); existingContainer = values.getExistingContainer(); savePath = values.getSavePath(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - try (InputStream input = MediaStoreTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - // Populate the data members required for all tests - prop.load(input); - containerName = prop.getProperty("containerName")+ java.util.UUID.randomUUID(); - filePath = prop.getProperty("filePath"); - completePath = prop.getProperty("completePath"); - existingContainer = prop.getProperty("existingContainer"); - savePath = prop.getProperty("savePath"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * try (InputStream input = + * MediaStoreTest.class.getClassLoader().getResourceAsStream("config.properties" + * )) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * // Populate the data members required for all tests + * prop.load(input); + * containerName = prop.getProperty("containerName")+ + * java.util.UUID.randomUUID(); + * filePath = prop.getProperty("filePath"); + * completePath = prop.getProperty("completePath"); + * existingContainer = prop.getProperty("existingContainer"); + * savePath = prop.getProperty("savePath"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ URI uri = new URI(PutObject.getEndpoint(existingContainer)); mediaStoreData = MediaStoreDataClient.builder() @@ -87,7 +89,7 @@ public static void setUp() throws URISyntaxException { @Tag("IntegrationTest") @Order(1) public void CreateContainer() { - assertDoesNotThrow(() ->CreateContainer.createMediaContainer(mediaStoreClient, containerName)); + assertDoesNotThrow(() -> CreateContainer.createMediaContainer(mediaStoreClient, containerName)); System.out.println("Test 1 passed"); } @@ -95,7 +97,7 @@ public void CreateContainer() { @Tag("IntegrationTest") @Order(2) public void DescribeContainer() { - assertDoesNotThrow(() ->DescribeContainer.checkContainer(mediaStoreClient, containerName)); + assertDoesNotThrow(() -> DescribeContainer.checkContainer(mediaStoreClient, containerName)); System.out.println("Test 2 passed"); } @@ -103,32 +105,31 @@ public void DescribeContainer() { @Tag("IntegrationTest") @Order(3) public void ListContainers() { - assertDoesNotThrow(() ->ListContainers.listAllContainers(mediaStoreClient)); + assertDoesNotThrow(() -> ListContainers.listAllContainers(mediaStoreClient)); System.out.println("Test 3 passed"); } @Test @Tag("IntegrationTest") @Order(4) - public void PutObject() throws URISyntaxException { - Region region = Region.US_EAST_1; - URI uri = new URI(getEndpoint(containerName)); - MediaStoreDataClient mediaStoreDataOb = MediaStoreDataClient.builder() - .endpointOverride(uri) - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); - - - assertDoesNotThrow(() -> PutObject.putMediaObject(mediaStoreDataOb, filePath, completePath)); - System.out.println("Test 4 passed"); + public void PutObject() throws URISyntaxException { + Region region = Region.US_EAST_1; + URI uri = new URI(getEndpoint(containerName)); + MediaStoreDataClient mediaStoreDataOb = MediaStoreDataClient.builder() + .endpointOverride(uri) + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); + + assertDoesNotThrow(() -> PutObject.putMediaObject(mediaStoreDataOb, filePath, completePath)); + System.out.println("Test 4 passed"); } @Test @Tag("IntegrationTest") @Order(5) public void ListItems() { - assertDoesNotThrow(() ->ListItems.listAllItems(mediaStoreData, containerName)); + assertDoesNotThrow(() -> ListItems.listAllItems(mediaStoreData, containerName)); System.out.println("Test 5 passed"); } @@ -139,12 +140,12 @@ public void GetObject() throws URISyntaxException { URI uri = new URI(getEndpoint(containerName)); Region region = Region.US_EAST_1; MediaStoreDataClient mediaStoreDataOb = MediaStoreDataClient.builder() - .endpointOverride(uri) - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .endpointOverride(uri) + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); - assertDoesNotThrow(() ->GetObject.getMediaObject(mediaStoreDataOb, completePath, savePath)); + assertDoesNotThrow(() -> GetObject.getMediaObject(mediaStoreDataOb, completePath, savePath)); System.out.println("Test 4 passed"); } @@ -155,12 +156,12 @@ public void DeleteObject() throws URISyntaxException { URI uri = new URI(getEndpoint(containerName)); Region region = Region.US_EAST_1; MediaStoreDataClient mediaStoreDataOb = MediaStoreDataClient.builder() - .endpointOverride(uri) - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .endpointOverride(uri) + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); - assertDoesNotThrow(() ->DeleteObject.deleteMediaObject(mediaStoreDataOb, completePath)); + assertDoesNotThrow(() -> DeleteObject.deleteMediaObject(mediaStoreDataOb, completePath)); System.out.println("Test 6 passed"); } @@ -170,19 +171,20 @@ public void DeleteObject() throws URISyntaxException { public void DeleteContainer() throws InterruptedException { System.out.println("Wait 1 min to delete container"); TimeUnit.MINUTES.sleep(1); - assertDoesNotThrow(() ->assertDoesNotThrow(() ->DeleteContainer.deleteMediaContainer(mediaStoreClient, containerName))); + assertDoesNotThrow( + () -> assertDoesNotThrow(() -> DeleteContainer.deleteMediaContainer(mediaStoreClient, containerName))); System.out.println("Test 7 passed"); } - private static String getEndpoint(String containerName){ + private static String getEndpoint(String containerName) { Region region = Region.US_EAST_1; MediaStoreClient mediaStoreClient = MediaStoreClient.builder() - .region(region) - .build(); + .region(region) + .build(); DescribeContainerRequest containerRequest = DescribeContainerRequest.builder() - .containerName(containerName) - .build(); + .containerName(containerName) + .build(); DescribeContainerResponse response = mediaStoreClient.describeContainer(containerRequest); return response.container().endpoint(); @@ -190,14 +192,14 @@ private static String getEndpoint(String containerName){ private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/mediastore"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -235,4 +237,3 @@ public String getCompletePath() { } } } - diff --git a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/CopyImageSet.java b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/CopyImageSet.java index 32e032a2756..c8aad5f2626 100644 --- a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/CopyImageSet.java +++ b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/CopyImageSet.java @@ -1,25 +1,20 @@ -//snippet-sourcedescription:[GetImageSet.java demonstrates how to copy an image set.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS HealthImaging] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.medicalimaging; -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - -//snippet-start:[medicalimaging.java2.copy_imageset.import] +// snippet-start:[medicalimaging.java2.copy_imageset.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.medicalimaging.MedicalImagingClient; import software.amazon.awssdk.services.medicalimaging.model.*; -//snippet-end:[medicalimaging.java2.copy_imageset.import] +// snippet-end:[medicalimaging.java2.copy_imageset.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. *

    * For more information, see the following documentation topic: *

    @@ -67,13 +62,13 @@ public static void main(String[] args) { medicalImagingClient.close(); } - //snippet-start:[medicalimaging.java2.copy_imageset.main] + // snippet-start:[medicalimaging.java2.copy_imageset.main] public static String copyMedicalImageSet(MedicalImagingClient medicalImagingClient, - String datastoreId, - String imageSetId, - String latestVersionId, - String destinationImageSetId, - String destinationVersionId) { + String datastoreId, + String imageSetId, + String latestVersionId, + String destinationImageSetId, + String destinationVersionId) { try { CopySourceImageSetInformation copySourceImageSetInformation = CopySourceImageSetInformation.builder() @@ -85,9 +80,9 @@ public static String copyMedicalImageSet(MedicalImagingClient medicalImagingClie if (destinationImageSetId != null) { copyImageSetBuilder = copyImageSetBuilder.destinationImageSet(CopyDestinationImageSet.builder() - .imageSetId(destinationImageSetId) - .latestVersionId(destinationVersionId) - .build()); + .imageSetId(destinationImageSetId) + .latestVersionId(destinationVersionId) + .build()); } CopyImageSetRequest copyImageSetRequest = CopyImageSetRequest.builder() @@ -106,5 +101,5 @@ public static String copyMedicalImageSet(MedicalImagingClient medicalImagingClie return ""; } -//snippet-end:[medicalimaging.java2.copy_imageset.main] + // snippet-end:[medicalimaging.java2.copy_imageset.main] } diff --git a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/CreateDatastore.java b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/CreateDatastore.java index 6ab7ff5381b..cad2b37002d 100644 --- a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/CreateDatastore.java +++ b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/CreateDatastore.java @@ -1,15 +1,9 @@ -//snippet-sourcedescription:[CreateDataStore.java demonstrates how to create a data store in AWS HealthImaging.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS HealthImaging] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.medicalimaging; -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - -//snippet-start:[medicalimaging.java2.create_datastore.import] +// snippet-start:[medicalimaging.java2.create_datastore.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; @@ -17,10 +11,11 @@ import software.amazon.awssdk.services.medicalimaging.model.CreateDatastoreRequest; import software.amazon.awssdk.services.medicalimaging.model.CreateDatastoreResponse; import software.amazon.awssdk.services.medicalimaging.model.MedicalImagingException; -//snippet-end:[medicalimaging.java2.create_datastore.import] +// snippet-end:[medicalimaging.java2.create_datastore.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. *

    * For more information, see the following documentation topic: *

    @@ -54,9 +49,9 @@ public static void main(String[] args) { medicalImagingClient.close(); } - //snippet-start:[medicalimaging.java2.create_datastore.main] + // snippet-start:[medicalimaging.java2.create_datastore.main] public static String createMedicalImageDatastore(MedicalImagingClient medicalImagingClient, - String datastoreName) { + String datastoreName) { try { CreateDatastoreRequest datastoreRequest = CreateDatastoreRequest.builder() .datastoreName(datastoreName) @@ -70,5 +65,5 @@ public static String createMedicalImageDatastore(MedicalImagingClient medicalIma return ""; } - //snippet-end:[medicalimaging.java2.create_datastore.main] + // snippet-end:[medicalimaging.java2.create_datastore.main] } \ No newline at end of file diff --git a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/DeleteDatastore.java b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/DeleteDatastore.java index 9e62909f4bf..4162c9f076d 100644 --- a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/DeleteDatastore.java +++ b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/DeleteDatastore.java @@ -1,25 +1,20 @@ -//snippet-sourcedescription:[DeleteDatastore.java demonstrates how to delete a data store in AWS HealthImaging.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS HealthImaging] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.medicalimaging; -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - -//snippet-start:[medicalimaging.java2.delete_datastore.import] +// snippet-start:[medicalimaging.java2.delete_datastore.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.medicalimaging.MedicalImagingClient; import software.amazon.awssdk.services.medicalimaging.model.DeleteDatastoreRequest; import software.amazon.awssdk.services.medicalimaging.model.MedicalImagingException; -//snippet-end:[medicalimaging.java2.delete_datastore.import] +// snippet-end:[medicalimaging.java2.delete_datastore.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. *

    * For more information, see the following documentation topic: *

    @@ -52,9 +47,9 @@ public static void main(String[] args) { medicalImagingClient.close(); } - //snippet-start:[medicalimaging.java2.delete_datastore.main] + // snippet-start:[medicalimaging.java2.delete_datastore.main] public static void deleteMedicalImagingDatastore(MedicalImagingClient medicalImagingClient, - String datastoreID) { + String datastoreID) { try { DeleteDatastoreRequest datastoreRequest = DeleteDatastoreRequest.builder() .datastoreId(datastoreID) @@ -65,5 +60,5 @@ public static void deleteMedicalImagingDatastore(MedicalImagingClient medicalIma System.exit(1); } } - //snippet-end:[medicalimaging.java2.delete_datastore.main] + // snippet-end:[medicalimaging.java2.delete_datastore.main] } \ No newline at end of file diff --git a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/DeleteImageSet.java b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/DeleteImageSet.java index 1c0fa9b78dd..497f259b199 100644 --- a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/DeleteImageSet.java +++ b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/DeleteImageSet.java @@ -1,17 +1,11 @@ -//snippet-sourcedescription:[GetImageSet.java demonstrates how to delete an image set.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS HealthImaging] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.medicalimaging; -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// snippet-start:[medicalimaging.java2.delete_imageset.import] -//snippet-start:[medicalimaging.java2.delete_imageset.import] - -//snippet-end:[medicalimaging.java2.delete_imageset.import] +// snippet-end:[medicalimaging.java2.delete_imageset.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; @@ -20,7 +14,8 @@ import software.amazon.awssdk.services.medicalimaging.model.MedicalImagingException; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. *

    * For more information, see the following documentation topic: *

    @@ -55,10 +50,10 @@ public static void main(String[] args) { medicalImagingClient.close(); } - //snippet-start:[medicalimaging.java2.delete_imageset.main] + // snippet-start:[medicalimaging.java2.delete_imageset.main] public static void deleteMedicalImageSet(MedicalImagingClient medicalImagingClient, - String datastoreId, - String imagesetId) { + String datastoreId, + String imagesetId) { try { DeleteImageSetRequest deleteImageSetRequest = DeleteImageSetRequest.builder() .datastoreId(datastoreId) @@ -73,5 +68,5 @@ public static void deleteMedicalImageSet(MedicalImagingClient medicalImagingClie System.exit(1); } } -//snippet-end:[medicalimaging.java2.delete_imageset.main] + // snippet-end:[medicalimaging.java2.delete_imageset.main] } diff --git a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/GetDatastore.java b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/GetDatastore.java index a3dc0466806..71f701fad55 100644 --- a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/GetDatastore.java +++ b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/GetDatastore.java @@ -1,15 +1,9 @@ -//snippet-sourcedescription:[GetDataStore.java demonstrates how to get a data store's pproperties in AWS HealthImaging.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS HealthImaging] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.medicalimaging; -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - -//snippet-start:[medicalimaging.java2.get_datastore.import] +// snippet-start:[medicalimaging.java2.get_datastore.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; @@ -18,10 +12,11 @@ import software.amazon.awssdk.services.medicalimaging.model.GetDatastoreRequest; import software.amazon.awssdk.services.medicalimaging.model.GetDatastoreResponse; import software.amazon.awssdk.services.medicalimaging.model.MedicalImagingException; -//snippet-end:[medicalimaging.java2.get_datastore.import] +// snippet-end:[medicalimaging.java2.get_datastore.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. *

    * For more information, see the following documentation topic: *

    @@ -57,9 +52,9 @@ public static void main(String[] args) { medicalImagingClient.close(); } - //snippet-start:[medicalimaging.java2.get_datastore.main] + // snippet-start:[medicalimaging.java2.get_datastore.main] public static DatastoreProperties getMedicalImageDatastore(MedicalImagingClient medicalImagingClient, - String datastoreID) { + String datastoreID) { try { GetDatastoreRequest datastoreRequest = GetDatastoreRequest.builder() .datastoreId(datastoreID) @@ -73,5 +68,5 @@ public static DatastoreProperties getMedicalImageDatastore(MedicalImagingClient return null; } - //snippet-end:[medicalimaging.java2.get_datastore.main] + // snippet-end:[medicalimaging.java2.get_datastore.main] } \ No newline at end of file diff --git a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/GetDicomImportJob.java b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/GetDicomImportJob.java index a488c100a92..a26ab82328e 100644 --- a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/GetDicomImportJob.java +++ b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/GetDicomImportJob.java @@ -1,15 +1,9 @@ -//snippet-sourcedescription:[StartDicomImportJob.java demonstrates how to get an import job's properties.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS HealthImaging] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.medicalimaging; -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - -//snippet-start:[medicalimaging.java2.get_dicom_import_job.import] +// snippet-start:[medicalimaging.java2.get_dicom_import_job.import] import com.google.gson.JsonElement; import com.google.gson.JsonObject; @@ -32,10 +26,11 @@ import java.util.ArrayList; import java.util.List; -//snippet-end:[medicalimaging.java2.get_dicom_import_job.import] +// snippet-end:[medicalimaging.java2.get_dicom_import_job.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. *

    * For more information, see the following documentation topic: *

    @@ -81,10 +76,10 @@ public static void main(String[] args) { medicalImagingClient.close(); } - //snippet-start:[medicalimaging.java2.get_dicom_import_job.main] + // snippet-start:[medicalimaging.java2.get_dicom_import_job.main] public static DICOMImportJobProperties getDicomImportJob(MedicalImagingClient medicalImagingClient, - String datastoreId, - String jobId) { + String datastoreId, + String jobId) { try { GetDicomImportJobRequest getDicomImportJobRequest = GetDicomImportJobRequest.builder() @@ -100,10 +95,10 @@ public static DICOMImportJobProperties getDicomImportJob(MedicalImagingClient me return null; } -//snippet-end:[medicalimaging.java2.get_dicom_import_job.main] + // snippet-end:[medicalimaging.java2.get_dicom_import_job.main] public static List getImageSetsForImportJobProperties(S3Client s3client, - DICOMImportJobProperties jobProperties) { + DICOMImportJobProperties jobProperties) { try { S3Utilities s3Utilities = s3client.utilities(); URI manifestUri = URI.create(jobProperties.outputS3Uri() + "job-output-manifest.json"); diff --git a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/GetImageFrame.java b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/GetImageFrame.java index eafa2e92e3f..94b42453bba 100644 --- a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/GetImageFrame.java +++ b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/GetImageFrame.java @@ -1,17 +1,11 @@ -//snippet-sourcedescription:[GetImageSet.java demonstrates how to retrieve an image set image frame.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS HealthImaging] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.medicalimaging; -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// snippet-start:[medicalimaging.java2.get_image_frame.import] -//snippet-start:[medicalimaging.java2.get_image_frame.import] - -//snippet-end:[medicalimaging.java2.get_image_frame.import] +// snippet-end:[medicalimaging.java2.get_image_frame.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; @@ -23,7 +17,8 @@ import java.nio.file.FileSystems; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. *

    * For more information, see the following documentation topic: *

    @@ -31,62 +26,61 @@ */ public class GetImageFrame { - public static void main(String[] args) { - final String usage = "\n" + - "Usage:\n" + - " \n\n" + - "Where:\n" + - " destinationPath - The destination path for the downloaded file.\n" + - " datastoreId - The ID of the data store.\n" + - " imagesetId - The ID of the image set.\n" + - " imageFrameId - The ID of the image frame.\n"; - - - if (args.length != 4) { - System.out.println(usage); - System.exit(1); + public static void main(String[] args) { + final String usage = "\n" + + "Usage:\n" + + " \n\n" + + "Where:\n" + + " destinationPath - The destination path for the downloaded file.\n" + + " datastoreId - The ID of the data store.\n" + + " imagesetId - The ID of the image set.\n" + + " imageFrameId - The ID of the image frame.\n"; + + if (args.length != 4) { + System.out.println(usage); + System.exit(1); + } + + String destinationPath = args[0]; + String datastoreId = args[1]; + String imagesetId = args[2]; + String imageFrameId = args[3]; + + Region region = Region.US_WEST_2; + MedicalImagingClient medicalImagingClient = MedicalImagingClient.builder() + .region(region) + .credentialsProvider(ProfileCredentialsProvider.create()) + .build(); + + getMedicalImageSetFrame(medicalImagingClient, destinationPath, + datastoreId, imagesetId, imageFrameId); + + medicalImagingClient.close(); } - String destinationPath = args[0]; - String datastoreId = args[1]; - String imagesetId = args[2]; - String imageFrameId = args[3]; - - Region region = Region.US_WEST_2; - MedicalImagingClient medicalImagingClient = MedicalImagingClient.builder() - .region(region) - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); - - getMedicalImageSetFrame(medicalImagingClient, destinationPath, - datastoreId, imagesetId, imageFrameId); - - medicalImagingClient.close(); - } - - //snippet-start:[medicalimaging.java2.get_image_frame.main] - public static void getMedicalImageSetFrame(MedicalImagingClient medicalImagingClient, - String destinationPath, - String datastoreId, - String imagesetId, - String imageFrameId) { - - try { - GetImageFrameRequest getImageSetMetadataRequest = GetImageFrameRequest.builder() - .datastoreId(datastoreId) - .imageSetId(imagesetId) - .imageFrameInformation(ImageFrameInformation.builder() - .imageFrameId(imageFrameId) - .build()) - .build(); - medicalImagingClient.getImageFrame(getImageSetMetadataRequest, - FileSystems.getDefault().getPath(destinationPath)); - - System.out.println("Image frame downloaded to " + destinationPath); - } catch (MedicalImagingException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + // snippet-start:[medicalimaging.java2.get_image_frame.main] + public static void getMedicalImageSetFrame(MedicalImagingClient medicalImagingClient, + String destinationPath, + String datastoreId, + String imagesetId, + String imageFrameId) { + + try { + GetImageFrameRequest getImageSetMetadataRequest = GetImageFrameRequest.builder() + .datastoreId(datastoreId) + .imageSetId(imagesetId) + .imageFrameInformation(ImageFrameInformation.builder() + .imageFrameId(imageFrameId) + .build()) + .build(); + medicalImagingClient.getImageFrame(getImageSetMetadataRequest, + FileSystems.getDefault().getPath(destinationPath)); + + System.out.println("Image frame downloaded to " + destinationPath); + } catch (MedicalImagingException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } } - } -//snippet-end:[medicalimaging.java2.get_image_frame.main] + // snippet-end:[medicalimaging.java2.get_image_frame.main] } diff --git a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/GetImageSet.java b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/GetImageSet.java index f2a726d7518..44898edc604 100644 --- a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/GetImageSet.java +++ b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/GetImageSet.java @@ -1,15 +1,9 @@ -//snippet-sourcedescription:[GetImageSet.java demonstrates how to retrieve information about an image set.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS HealthImaging] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.medicalimaging; -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - -//snippet-start:[medicalimaging.java2.get_imageset.import] +// snippet-start:[medicalimaging.java2.get_imageset.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; @@ -18,10 +12,11 @@ import software.amazon.awssdk.services.medicalimaging.model.GetImageSetResponse; import software.amazon.awssdk.services.medicalimaging.model.MedicalImagingException; -//snippet-end:[medicalimaging.java2.get_imageset.import] +// snippet-end:[medicalimaging.java2.get_imageset.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. *

    * For more information, see the following documentation topic: *

    @@ -59,19 +54,18 @@ public static void main(String[] args) { GetImageSetResponse getImageSetResponse = getMedicalImageSet(medicalImagingClient, datastoreId, imagesetId, versionid); - System.out.println("The get image response is " + getImageSetResponse); medicalImagingClient.close(); } - //snippet-start:[medicalimaging.java2.get_imageset.main] + // snippet-start:[medicalimaging.java2.get_imageset.main] public static GetImageSetResponse getMedicalImageSet(MedicalImagingClient medicalImagingClient, - String datastoreId, - String imagesetId, - String versionId) { + String datastoreId, + String imagesetId, + String versionId) { try { - GetImageSetRequest.Builder getImageSetRequestBuilder = GetImageSetRequest.builder() + GetImageSetRequest.Builder getImageSetRequestBuilder = GetImageSetRequest.builder() .datastoreId(datastoreId) .imageSetId(imagesetId); @@ -87,5 +81,5 @@ public static GetImageSetResponse getMedicalImageSet(MedicalImagingClient medica return null; } -//snippet-end:[medicalimaging.java2.get_imageset.main] + // snippet-end:[medicalimaging.java2.get_imageset.main] } diff --git a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/GetImageSetMetadata.java b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/GetImageSetMetadata.java index 298696bf104..c80c78bca1a 100644 --- a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/GetImageSetMetadata.java +++ b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/GetImageSetMetadata.java @@ -1,17 +1,11 @@ -//snippet-sourcedescription:[GetImageSet.java demonstrates how to retrieve the image set metadata.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS HealthImaging] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.medicalimaging; -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// snippet-start:[medicalimaging.java2.get_imageset_metadata.import] -//snippet-start:[medicalimaging.java2.get_imageset_metadata.import] - -//snippet-end:[medicalimaging.java2.get_imageset_metadata.import] +// snippet-end:[medicalimaging.java2.get_imageset_metadata.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; @@ -22,7 +16,8 @@ import java.nio.file.FileSystems; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. *

    * For more information, see the following documentation topic: *

    @@ -65,22 +60,20 @@ public static void main(String[] args) { medicalImagingClient.close(); } - //snippet-start:[medicalimaging.java2.get_imageset_metadata.main] + // snippet-start:[medicalimaging.java2.get_imageset_metadata.main] public static void getMedicalImageSetMetadata(MedicalImagingClient medicalImagingClient, - String destinationPath, - String datastoreId, - String imagesetId, - String versionId) { + String destinationPath, + String datastoreId, + String imagesetId, + String versionId) { try { - GetImageSetMetadataRequest.Builder getImageSetMetadataRequestBuilder = - GetImageSetMetadataRequest.builder() + GetImageSetMetadataRequest.Builder getImageSetMetadataRequestBuilder = GetImageSetMetadataRequest.builder() .datastoreId(datastoreId) .imageSetId(imagesetId); if (versionId != null) { - getImageSetMetadataRequestBuilder = - getImageSetMetadataRequestBuilder.versionId(versionId); + getImageSetMetadataRequestBuilder = getImageSetMetadataRequestBuilder.versionId(versionId); } medicalImagingClient.getImageSetMetadata(getImageSetMetadataRequestBuilder.build(), @@ -92,5 +85,5 @@ public static void getMedicalImageSetMetadata(MedicalImagingClient medicalImagin System.exit(1); } } -//snippet-end:[medicalimaging.java2.get_imageset_metadata.main] + // snippet-end:[medicalimaging.java2.get_imageset_metadata.main] } diff --git a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/ListDatastores.java b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/ListDatastores.java index 76e142309be..ad7c254c81b 100644 --- a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/ListDatastores.java +++ b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/ListDatastores.java @@ -1,15 +1,9 @@ -//snippet-sourcedescription:[ListDataStore.java demonstrates how to list the datastores in an AWS HealthImaging account.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS HealthImaging] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.medicalimaging; -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - -//snippet-start:[medicalimaging.java2.list_datastores.import] +// snippet-start:[medicalimaging.java2.list_datastores.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; @@ -22,10 +16,11 @@ import java.util.ArrayList; import java.util.List; -//snippet-end:[medicalimaging.java2.list_datastores.import] +// snippet-end:[medicalimaging.java2.list_datastores.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. *

    * For more information, see the following documentation topic: *

    @@ -48,7 +43,7 @@ public static void main(String[] args) { medicalImagingClient.close(); } - //snippet-start:[medicalimaging.java2.list_datastores.main] + // snippet-start:[medicalimaging.java2.list_datastores.main] public static List listMedicalImagingDatastores(MedicalImagingClient medicalImagingClient) { try { ListDatastoresRequest datastoreRequest = ListDatastoresRequest.builder() @@ -66,5 +61,5 @@ public static List listMedicalImagingDatastores(MedicalImaging return null; } - //snippet-end:[medicalimaging.java2.list_datastores.main] + // snippet-end:[medicalimaging.java2.list_datastores.main] } \ No newline at end of file diff --git a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/ListDicomImportJobs.java b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/ListDicomImportJobs.java index 44f567d08b7..4c3af62b400 100644 --- a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/ListDicomImportJobs.java +++ b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/ListDicomImportJobs.java @@ -1,15 +1,9 @@ -//snippet-sourcedescription:[StartDicomImportJob.java demonstrates how to list import jobs in AWS HealthImaging.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS HealthImaging] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.medicalimaging; -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - -//snippet-start:[medicalimaging.java2.list_dicom_import_jobs.import] +// snippet-start:[medicalimaging.java2.list_dicom_import_jobs.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; @@ -22,10 +16,11 @@ import java.util.ArrayList; import java.util.List; -//snippet-end:[medicalimaging.java2.list_dicom_import_jobs.import] +// snippet-end:[medicalimaging.java2.list_dicom_import_jobs.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. *

    * For more information, see the following documentation topic: *

    @@ -60,9 +55,9 @@ public static void main(String[] args) { medicalImagingClient.close(); } - //snippet-start:[medicalimaging.java2.list_dicom_import_jobs.main] + // snippet-start:[medicalimaging.java2.list_dicom_import_jobs.main] public static List listDicomImportJobs(MedicalImagingClient medicalImagingClient, - String datastoreId) { + String datastoreId) { try { ListDicomImportJobsRequest listDicomImportJobsRequest = ListDicomImportJobsRequest.builder() @@ -77,5 +72,5 @@ public static List listDicomImportJobs(MedicalImagingClie return new ArrayList<>(); } -//snippet-end:[medicalimaging.java2.list_dicom_import_jobs.main] + // snippet-end:[medicalimaging.java2.list_dicom_import_jobs.main] } diff --git a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/ListImageSetVersions.java b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/ListImageSetVersions.java index 1a51c644f34..5d606e2c224 100644 --- a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/ListImageSetVersions.java +++ b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/ListImageSetVersions.java @@ -1,15 +1,9 @@ -//snippet-sourcedescription:[GetImageSet.java demonstrates how to retrieve the versions for an image set.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS HealthImaging] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.medicalimaging; -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - -//snippet-start:[medicalimaging.java2.list_imageset_versions.import] +// snippet-start:[medicalimaging.java2.list_imageset_versions.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; @@ -22,10 +16,11 @@ import java.util.ArrayList; import java.util.List; -//snippet-end:[medicalimaging.java2.list_imageset_versions.import] +// snippet-end:[medicalimaging.java2.list_imageset_versions.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. *

    * For more information, see the following documentation topic: *

    @@ -55,25 +50,26 @@ public static void main(String[] args) { .credentialsProvider(ProfileCredentialsProvider.create()) .build(); - List imageSetProperties = listMedicalImageSetVersions(medicalImagingClient, datastoreId, imagesetId); - + List imageSetProperties = listMedicalImageSetVersions(medicalImagingClient, datastoreId, + imagesetId); System.out.println("The image set versions are " + imageSetProperties); medicalImagingClient.close(); } - //snippet-start:[medicalimaging.java2.list_imageset_versions.main] + // snippet-start:[medicalimaging.java2.list_imageset_versions.main] public static List listMedicalImageSetVersions(MedicalImagingClient medicalImagingClient, - String datastoreId, - String imagesetId) { + String datastoreId, + String imagesetId) { try { ListImageSetVersionsRequest getImageSetRequest = ListImageSetVersionsRequest.builder() .datastoreId(datastoreId) .imageSetId(imagesetId) .build(); - ListImageSetVersionsIterable responses = medicalImagingClient.listImageSetVersionsPaginator(getImageSetRequest); + ListImageSetVersionsIterable responses = medicalImagingClient + .listImageSetVersionsPaginator(getImageSetRequest); List imageSetProperties = new ArrayList<>(); responses.stream().forEach(response -> imageSetProperties.addAll(response.imageSetPropertiesList())); @@ -85,5 +81,5 @@ public static List listMedicalImageSetVersions(MedicalImagin return null; } -//snippet-end:[medicalimaging.java2.list_imageset_versions.main] + // snippet-end:[medicalimaging.java2.list_imageset_versions.main] } diff --git a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/ListTagsForResource.java b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/ListTagsForResource.java index 76e5f51d23d..fd987598ce4 100644 --- a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/ListTagsForResource.java +++ b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/ListTagsForResource.java @@ -1,17 +1,11 @@ -//snippet-sourcedescription:[GetImageSet.java demonstrates how to list tags for a resource.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS HealthImaging] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.medicalimaging; -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// snippet-start:[medicalimaging.java2.list_tags_for_resource.import] -//snippet-start:[medicalimaging.java2.list_tags_for_resource.import] - -//snippet-end:[medicalimaging.java2.list_tags_for_resource.import] +// snippet-end:[medicalimaging.java2.list_tags_for_resource.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; @@ -21,7 +15,8 @@ import software.amazon.awssdk.services.medicalimaging.model.MedicalImagingException; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. *

    * For more information, see the following documentation topic: *

    @@ -58,9 +53,9 @@ public static void main(String[] args) { medicalImagingClient.close(); } - //snippet-start:[medicalimaging.java2.list_tags_for_resource.main] + // snippet-start:[medicalimaging.java2.list_tags_for_resource.main] public static ListTagsForResourceResponse listMedicalImagingResourceTags(MedicalImagingClient medicalImagingClient, - String resourceArn) { + String resourceArn) { try { ListTagsForResourceRequest listTagsForResourceRequest = ListTagsForResourceRequest.builder() .resourceArn(resourceArn) @@ -74,5 +69,5 @@ public static ListTagsForResourceResponse listMedicalImagingResourceTags(Medical return null; } -//snippet-end:[medicalimaging.java2.list_tags_for_resource.main] + // snippet-end:[medicalimaging.java2.list_tags_for_resource.main] } diff --git a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/SearchImageSets.java b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/SearchImageSets.java index 2ef56d1fc85..76f003629e6 100644 --- a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/SearchImageSets.java +++ b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/SearchImageSets.java @@ -1,15 +1,9 @@ -//snippet-sourcedescription:[SearchImageSets.java demonstrates how to search for image sets in a data store.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS HealthImaging] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.medicalimaging; -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - -//snippet-start:[medicalimaging.java2.search_imagesets.import] +// snippet-start:[medicalimaging.java2.search_imagesets.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; @@ -23,10 +17,11 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -//snippet-end:[medicalimaging.java2.search_imagesets.import] +// snippet-end:[medicalimaging.java2.search_imagesets.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. *

    * For more information, see the following documentation topic: *

    @@ -35,116 +30,126 @@ public class SearchImageSets { - public static void main(String[] args) { - final String usage = "\n" + - "Usage:\n" + - " \n\n" + - "Where:\n" + - " datastoreId - The ID of the data store.\n" + - " patientId - The ID of the patient to search for.\\n"; - - if (args.length != 2) { - System.out.println(usage); - System.exit(1); + public static void main(String[] args) { + final String usage = "\n" + + "Usage:\n" + + " \n\n" + + "Where:\n" + + " datastoreId - The ID of the data store.\n" + + " patientId - The ID of the patient to search for.\\n"; + + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } + + String datastoreId = args[0]; + String patientId = args[1]; + + Region region = Region.US_WEST_2; + MedicalImagingClient medicalImagingClient = MedicalImagingClient.builder() + .region(region) + .credentialsProvider(ProfileCredentialsProvider.create()) + .build(); + + // Use case #1: EQUAL operator. + // snippet-start:[medicalimaging.java2.search_imagesets.use_case1] + List searchFilters = Collections.singletonList(SearchFilter.builder() + .operator(Operator.EQUAL) + .values(SearchByAttributeValue.builder() + .dicomPatientId(patientId) + .build()) + .build()); + + List imageSetsMetadataSummaries = searchMedicalImagingImageSets( + medicalImagingClient, + datastoreId, searchFilters); + if (imageSetsMetadataSummaries != null) { + System.out.println("The image sets for patient " + patientId + " are:\n" + + imageSetsMetadataSummaries); + System.out.println(); + } + // snippet-end:[medicalimaging.java2.search_imagesets.use_case1] + + // Use case #2: BETWEEN operator using DICOMStudyDate and DICOMStudyTime. + // snippet-start:[medicalimaging.java2.search_imagesets.use_case2] + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd"); + searchFilters = Collections.singletonList(SearchFilter.builder() + .operator(Operator.BETWEEN) + .values(SearchByAttributeValue.builder() + .dicomStudyDateAndTime(DICOMStudyDateAndTime.builder() + .dicomStudyDate("19990101") + .dicomStudyTime("000000.000") + .build()) + .build(), + SearchByAttributeValue.builder() + .dicomStudyDateAndTime(DICOMStudyDateAndTime.builder() + .dicomStudyDate((LocalDate.now() + .format(formatter))) + .dicomStudyTime("000000.000") + .build()) + .build()) + .build()); + + imageSetsMetadataSummaries = searchMedicalImagingImageSets(medicalImagingClient, + datastoreId, searchFilters); + if (imageSetsMetadataSummaries != null) { + System.out.println( + "The image sets searched with BETWEEN operator using DICOMStudyDate and DICOMStudyTime are:\n" + + + imageSetsMetadataSummaries); + System.out.println(); + } + // snippet-end:[medicalimaging.java2.search_imagesets.use_case2] + + // Use case #3: BETWEEN operator using createdAt. Time studies were previously + // persisted. + // snippet-start:[medicalimaging.java2.search_imagesets.use_case3] + searchFilters = Collections.singletonList(SearchFilter.builder() + .operator(Operator.BETWEEN) + .values(SearchByAttributeValue.builder() + .createdAt(Instant.parse("1985-04-12T23:20:50.52Z")) + .build(), + SearchByAttributeValue.builder() + .createdAt(Instant.now()) + .build()) + .build()); + + imageSetsMetadataSummaries = searchMedicalImagingImageSets(medicalImagingClient, + datastoreId, searchFilters); + if (imageSetsMetadataSummaries != null) { + System.out.println("The image sets searched with BETWEEN operator using createdAt are:\n " + + imageSetsMetadataSummaries); + System.out.println(); + } + // snippet-end:[medicalimaging.java2.search_imagesets.use_case3] + + medicalImagingClient.close(); } - String datastoreId = args[0]; - String patientId = args[1]; - - Region region = Region.US_WEST_2; - MedicalImagingClient medicalImagingClient = MedicalImagingClient.builder() - .region(region) - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); - - // Use case #1: EQUAL operator. - //snippet-start:[medicalimaging.java2.search_imagesets.use_case1] - List searchFilters = Collections.singletonList(SearchFilter.builder() - .operator(Operator.EQUAL) - .values(SearchByAttributeValue.builder() - .dicomPatientId(patientId) - .build()) - .build()); - - List imageSetsMetadataSummaries = searchMedicalImagingImageSets(medicalImagingClient, - datastoreId, searchFilters); - if (imageSetsMetadataSummaries != null) { - System.out.println("The image sets for patient " + patientId + " are:\n" + imageSetsMetadataSummaries); - System.out.println(); - } - //snippet-end:[medicalimaging.java2.search_imagesets.use_case1] - - // Use case #2: BETWEEN operator using DICOMStudyDate and DICOMStudyTime. - //snippet-start:[medicalimaging.java2.search_imagesets.use_case2] - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd"); - searchFilters = Collections.singletonList(SearchFilter.builder() - .operator(Operator.BETWEEN) - .values(SearchByAttributeValue.builder() - .dicomStudyDateAndTime(DICOMStudyDateAndTime.builder() - .dicomStudyDate("19990101") - .dicomStudyTime("000000.000") - .build()) - .build(), - SearchByAttributeValue.builder() - .dicomStudyDateAndTime(DICOMStudyDateAndTime.builder() - .dicomStudyDate((LocalDate.now().format(formatter))) - .dicomStudyTime("000000.000") - .build()) - .build()) - .build()); - - imageSetsMetadataSummaries = searchMedicalImagingImageSets(medicalImagingClient, - datastoreId, searchFilters); - if (imageSetsMetadataSummaries != null) { - System.out.println("The image sets searched with BETWEEN operator using DICOMStudyDate and DICOMStudyTime are:\n" + - imageSetsMetadataSummaries); - System.out.println(); - } - //snippet-end:[medicalimaging.java2.search_imagesets.use_case2] - - // Use case #3: BETWEEN operator using createdAt. Time studies were previously persisted. - //snippet-start:[medicalimaging.java2.search_imagesets.use_case3] - searchFilters = Collections.singletonList(SearchFilter.builder() - .operator(Operator.BETWEEN) - .values(SearchByAttributeValue.builder() - .createdAt(Instant.parse("1985-04-12T23:20:50.52Z")) - .build(), - SearchByAttributeValue.builder() - .createdAt(Instant.now()) - .build()) - .build()); - - imageSetsMetadataSummaries = searchMedicalImagingImageSets(medicalImagingClient, - datastoreId, searchFilters); - if (imageSetsMetadataSummaries != null) { - System.out.println("The image sets searched with BETWEEN operator using createdAt are:\n " + imageSetsMetadataSummaries); - System.out.println(); + // snippet-start:[medicalimaging.java2.search_imagesets.main] + public static List searchMedicalImagingImageSets( + MedicalImagingClient medicalImagingClient, + String datastoreId, List searchFilters) { + try { + SearchImageSetsRequest datastoreRequest = SearchImageSetsRequest.builder() + .datastoreId(datastoreId) + .searchCriteria(SearchCriteria.builder().filters(searchFilters).build()) + .build(); + SearchImageSetsIterable responses = medicalImagingClient + .searchImageSetsPaginator(datastoreRequest); + List imageSetsMetadataSummaries = new ArrayList<>(); + + responses.stream().forEach(response -> imageSetsMetadataSummaries + .addAll(response.imageSetsMetadataSummaries())); + + return imageSetsMetadataSummaries; + } catch (MedicalImagingException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + + return null; } - //snippet-end:[medicalimaging.java2.search_imagesets.use_case3] - - medicalImagingClient.close(); - } - - //snippet-start:[medicalimaging.java2.search_imagesets.main] - public static List searchMedicalImagingImageSets(MedicalImagingClient medicalImagingClient, - String datastoreId, List searchFilters) { - try { - SearchImageSetsRequest datastoreRequest = SearchImageSetsRequest.builder() - .datastoreId(datastoreId) - .searchCriteria(SearchCriteria.builder().filters(searchFilters).build()) - .build(); - SearchImageSetsIterable responses = medicalImagingClient.searchImageSetsPaginator(datastoreRequest); - List imageSetsMetadataSummaries = new ArrayList<>(); - - responses.stream().forEach(response -> imageSetsMetadataSummaries.addAll(response.imageSetsMetadataSummaries())); - - return imageSetsMetadataSummaries; - } catch (MedicalImagingException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - - return null; - } - //snippet-end:[medicalimaging.java2.search_imagesets.main] + // snippet-end:[medicalimaging.java2.search_imagesets.main] } diff --git a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/StartDicomImportJob.java b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/StartDicomImportJob.java index f613f9e2441..a87b4c8340f 100644 --- a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/StartDicomImportJob.java +++ b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/StartDicomImportJob.java @@ -1,15 +1,9 @@ -//snippet-sourcedescription:[StartDicomImportJob.java demonstrates how to import bulk data into in an AWS HealthImaging data store.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS HealthImaging] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.medicalimaging; -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - -//snippet-start:[medicalimaging.java2.start_dicom_import_job.import] +// snippet-start:[medicalimaging.java2.start_dicom_import_job.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; @@ -18,10 +12,11 @@ import software.amazon.awssdk.services.medicalimaging.model.StartDicomImportJobRequest; import software.amazon.awssdk.services.medicalimaging.model.StartDicomImportJobResponse; -//snippet-end:[medicalimaging.java2.start_dicom_import_job.import] +// snippet-end:[medicalimaging.java2.start_dicom_import_job.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. *

    * For more information, see the following documentation topic: *

    @@ -36,8 +31,10 @@ public static void main(String[] args) { "Where:\n" + " jobName - The import job name.\n" + " datastoreId - The ID of the data store.\n" + - " dataAccessRoleArn - The Amazon Resource Name (ARN) of the IAM role that grants permission to access medical imaging resource.\n" + - " inputS3Uri - The input prefix path for the S3 bucket that contains the DICOM files to be imported.\n" + + " dataAccessRoleArn - The Amazon Resource Name (ARN) of the IAM role that grants permission to access medical imaging resource.\n" + + + " inputS3Uri - The input prefix path for the S3 bucket that contains the DICOM files to be imported.\n" + + " outputS3Uri - The output prefix of the S3 bucket to upload the results of the DICOM import job.\n"; if (args.length != 5) { @@ -57,20 +54,21 @@ public static void main(String[] args) { .credentialsProvider(ProfileCredentialsProvider.create()) .build(); - String jobID = startDicomImportJob(medicalImagingClient, jobName, datastoreId, dataAccessRoleArn, inputS3Uri, outputS3Uri); + String jobID = startDicomImportJob(medicalImagingClient, jobName, datastoreId, dataAccessRoleArn, inputS3Uri, + outputS3Uri); System.out.println("The job ID is " + jobID); medicalImagingClient.close(); } - //snippet-start:[medicalimaging.java2.start_dicom_import_job.main] + // snippet-start:[medicalimaging.java2.start_dicom_import_job.main] public static String startDicomImportJob(MedicalImagingClient medicalImagingClient, - String jobName, - String datastoreId, - String dataAccessRoleArn, - String inputS3Uri, - String outputS3Uri) { + String jobName, + String datastoreId, + String dataAccessRoleArn, + String inputS3Uri, + String outputS3Uri) { try { StartDicomImportJobRequest startDicomImportJobRequest = StartDicomImportJobRequest.builder() @@ -89,5 +87,5 @@ public static String startDicomImportJob(MedicalImagingClient medicalImagingClie return ""; } -//snippet-end:[medicalimaging.java2.start_dicom_import_job.main] + // snippet-end:[medicalimaging.java2.start_dicom_import_job.main] } diff --git a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/TagResource.java b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/TagResource.java index ef922c02358..ef1bf684a43 100644 --- a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/TagResource.java +++ b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/TagResource.java @@ -1,15 +1,9 @@ -//snippet-sourcedescription:[GetImageSet.java demonstrates how to tag a resource.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS HealthImaging] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.medicalimaging; -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - -//snippet-start:[medicalimaging.java2.tag_resource.import] +// snippet-start:[medicalimaging.java2.tag_resource.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; @@ -20,10 +14,11 @@ import java.util.Map; -//snippet-end:[medicalimaging.java2.tag_resource.import] +// snippet-end:[medicalimaging.java2.tag_resource.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. *

    * For more information, see the following documentation topic: *

    @@ -53,14 +48,13 @@ public static void main(String[] args) { tagMedicalImagingResource(medicalImagingClient, resourceArn, ImmutableMap.of("Deployment", "Development")); - medicalImagingClient.close(); } - //snippet-start:[medicalimaging.java2.tag_resource.main] + // snippet-start:[medicalimaging.java2.tag_resource.main] public static void tagMedicalImagingResource(MedicalImagingClient medicalImagingClient, - String resourceArn, - Map tags) { + String resourceArn, + Map tags) { try { TagResourceRequest tagResourceRequest = TagResourceRequest.builder() .resourceArn(resourceArn) @@ -75,5 +69,5 @@ public static void tagMedicalImagingResource(MedicalImagingClient medicalImaging System.exit(1); } } -//snippet-end:[medicalimaging.java2.tag_resource.main] + // snippet-end:[medicalimaging.java2.tag_resource.main] } diff --git a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/TaggingDatastores.java b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/TaggingDatastores.java index 102b6831749..3b5754566c1 100644 --- a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/TaggingDatastores.java +++ b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/TaggingDatastores.java @@ -1,15 +1,9 @@ -//snippet-sourcedescription:[GetImageSet.java demonstrates tagging, untagging and listing tags for a data store.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS HealthImaging] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.medicalimaging; -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - -//snippet-start:[medicalimaging.java2.tagging_datastores.import] +// snippet-start:[medicalimaging.java2.tagging_datastores.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; @@ -19,10 +13,11 @@ import java.util.Collections; -//snippet-end:[medicalimaging.java2.tagging_datastores.import] +// snippet-end:[medicalimaging.java2.tagging_datastores.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. *

    * For more information, see the following documentation topic: *

    @@ -30,34 +25,37 @@ */ public class TaggingDatastores { - public static void main(String[] args) { - Region region = Region.US_WEST_2; - MedicalImagingClient medicalImagingClient = MedicalImagingClient.builder() - .region(region) - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); - - // Set datastoreArn to the ARN of an actual data store. - //snippet-start:[medicalimaging.java2.tagging_datastores.datastore_arn] - final String datastoreArn = - "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012"; - //snippet-end:[medicalimaging.java2.tagging_datastores.datastore_arn] - - //snippet-start:[medicalimaging.java2.tagging_datastores.tag] - TagResource.tagMedicalImagingResource(medicalImagingClient, datastoreArn, ImmutableMap.of("Deployment", "Development")); - //snippet-end:[medicalimaging.java2.tagging_datastores.tag] - - //snippet-start:[medicalimaging.java2.tagging_datastores.list] - ListTagsForResourceResponse result = ListTagsForResource.listMedicalImagingResourceTags(medicalImagingClient, datastoreArn); - if (result != null) { - System.out.println("Tags for resource: " + result.tags()); + public static void main(String[] args) { + Region region = Region.US_WEST_2; + MedicalImagingClient medicalImagingClient = MedicalImagingClient.builder() + .region(region) + .credentialsProvider(ProfileCredentialsProvider.create()) + .build(); + + // Set datastoreArn to the ARN of an actual data store. + // snippet-start:[medicalimaging.java2.tagging_datastores.datastore_arn] + final String datastoreArn = "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012"; + // snippet-end:[medicalimaging.java2.tagging_datastores.datastore_arn] + + // snippet-start:[medicalimaging.java2.tagging_datastores.tag] + TagResource.tagMedicalImagingResource(medicalImagingClient, datastoreArn, + ImmutableMap.of("Deployment", "Development")); + // snippet-end:[medicalimaging.java2.tagging_datastores.tag] + + // snippet-start:[medicalimaging.java2.tagging_datastores.list] + ListTagsForResourceResponse result = ListTagsForResource.listMedicalImagingResourceTags( + medicalImagingClient, + datastoreArn); + if (result != null) { + System.out.println("Tags for resource: " + result.tags()); + } + // snippet-end:[medicalimaging.java2.tagging_datastores.list] + + // snippet-start:[medicalimaging.java2.tagging_datastores.untag] + UntagResource.untagMedicalImagingResource(medicalImagingClient, datastoreArn, + Collections.singletonList("Deployment")); + // snippet-end:[medicalimaging.java2.tagging_datastores.untag] + + medicalImagingClient.close(); } - //snippet-end:[medicalimaging.java2.tagging_datastores.list] - - //snippet-start:[medicalimaging.java2.tagging_datastores.untag] - UntagResource.untagMedicalImagingResource(medicalImagingClient, datastoreArn, Collections.singletonList("Deployment")); - //snippet-end:[medicalimaging.java2.tagging_datastores.untag] - - medicalImagingClient.close(); - } } diff --git a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/TaggingImageSets.java b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/TaggingImageSets.java index c71513b27b7..9a2b4c851ff 100644 --- a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/TaggingImageSets.java +++ b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/TaggingImageSets.java @@ -1,17 +1,11 @@ -//snippet-sourcedescription:[GetImageSet.java demonstrates tagging, untagging and listing tags for an image set.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS HealthImaging] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.medicalimaging; -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// snippet-start:[medicalimaging.java2.tagging_imagesets.import] -//snippet-start:[medicalimaging.java2.tagging_imagesets.import] - -//snippet-end:[medicalimaging.java2.tagging_imagesets.import] +// snippet-end:[medicalimaging.java2.tagging_imagesets.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; @@ -22,7 +16,8 @@ import java.util.Collections; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. *

    * For more information, see the following documentation topic: *

    @@ -30,34 +25,37 @@ */ public class TaggingImageSets { - public static void main(String[] args) { - Region region = Region.US_WEST_2; - MedicalImagingClient medicalImagingClient = MedicalImagingClient.builder() - .region(region) - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); - - // Set imageSetArn to the ARN of an actual image set. - //snippet-start:[medicalimaging.java2.tagging_imagesets.datastore_arn] - final String imageSetArn = - "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012/imageset/12345678901234567890123456789012"; - //snippet-end:[medicalimaging.java2.tagging_imagesets.datastore_arn] - - //snippet-start:[medicalimaging.java2.tagging_imagesets.tag] - TagResource.tagMedicalImagingResource(medicalImagingClient, imageSetArn, ImmutableMap.of("Deployment", "Development")); - //snippet-end:[medicalimaging.java2.tagging_imagesets.tag] - - //snippet-start:[medicalimaging.java2.tagging_imagesets.list] - ListTagsForResourceResponse result = ListTagsForResource.listMedicalImagingResourceTags(medicalImagingClient, imageSetArn); - if (result != null) { - System.out.println("Tags for resource: " + result.tags()); + public static void main(String[] args) { + Region region = Region.US_WEST_2; + MedicalImagingClient medicalImagingClient = MedicalImagingClient.builder() + .region(region) + .credentialsProvider(ProfileCredentialsProvider.create()) + .build(); + + // Set imageSetArn to the ARN of an actual image set. + // snippet-start:[medicalimaging.java2.tagging_imagesets.datastore_arn] + final String imageSetArn = "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012/imageset/12345678901234567890123456789012"; + // snippet-end:[medicalimaging.java2.tagging_imagesets.datastore_arn] + + // snippet-start:[medicalimaging.java2.tagging_imagesets.tag] + TagResource.tagMedicalImagingResource(medicalImagingClient, imageSetArn, + ImmutableMap.of("Deployment", "Development")); + // snippet-end:[medicalimaging.java2.tagging_imagesets.tag] + + // snippet-start:[medicalimaging.java2.tagging_imagesets.list] + ListTagsForResourceResponse result = ListTagsForResource.listMedicalImagingResourceTags( + medicalImagingClient, + imageSetArn); + if (result != null) { + System.out.println("Tags for resource: " + result.tags()); + } + // snippet-end:[medicalimaging.java2.tagging_imagesets.list] + + // snippet-start:[medicalimaging.java2.tagging_imagesets.untag] + UntagResource.untagMedicalImagingResource(medicalImagingClient, imageSetArn, + Collections.singletonList("Deployment")); + // snippet-end:[medicalimaging.java2.tagging_imagesets.untag] + + medicalImagingClient.close(); } - //snippet-end:[medicalimaging.java2.tagging_imagesets.list] - - //snippet-start:[medicalimaging.java2.tagging_imagesets.untag] - UntagResource.untagMedicalImagingResource(medicalImagingClient, imageSetArn, Collections.singletonList("Deployment")); - //snippet-end:[medicalimaging.java2.tagging_imagesets.untag] - - medicalImagingClient.close(); - } } diff --git a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/UntagResource.java b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/UntagResource.java index af4e31b6890..b7f054fb83d 100644 --- a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/UntagResource.java +++ b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/UntagResource.java @@ -1,17 +1,11 @@ -//snippet-sourcedescription:[GetImageSet.java demonstrates how to remove tags from a resource.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS HealthImaging] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.medicalimaging; -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// snippet-start:[medicalimaging.java2.untag_resource.import] -//snippet-start:[medicalimaging.java2.untag_resource.import] - -//snippet-end:[medicalimaging.java2.untag_resource.import] +// snippet-end:[medicalimaging.java2.untag_resource.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; @@ -23,7 +17,8 @@ import java.util.Collections; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. *

    * For more information, see the following documentation topic: *

    @@ -53,14 +48,13 @@ public static void main(String[] args) { untagMedicalImagingResource(medicalImagingClient, resourceArn, Collections.singletonList("Deployment")); - medicalImagingClient.close(); } - //snippet-start:[medicalimaging.java2.untag_resource.main] + // snippet-start:[medicalimaging.java2.untag_resource.main] public static void untagMedicalImagingResource(MedicalImagingClient medicalImagingClient, - String resourceArn, - Collection tagKeys) { + String resourceArn, + Collection tagKeys) { try { UntagResourceRequest untagResourceRequest = UntagResourceRequest.builder() .resourceArn(resourceArn) @@ -75,5 +69,5 @@ public static void untagMedicalImagingResource(MedicalImagingClient medicalImagi System.exit(1); } } -//snippet-end:[medicalimaging.java2.untag_resource.main] + // snippet-end:[medicalimaging.java2.untag_resource.main] } diff --git a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/UpdateImageSetMetadata.java b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/UpdateImageSetMetadata.java index 2cc9dfa3a12..3f5ad744512 100644 --- a/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/UpdateImageSetMetadata.java +++ b/javav2/example_code/medicalimaging/src/main/java/com/example/medicalimaging/UpdateImageSetMetadata.java @@ -1,15 +1,9 @@ -//snippet-sourcedescription:[GetImageSet.java demonstrates how to update an image set's metadata.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[AWS HealthImaging] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.medicalimaging; -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - -//snippet-start:[medicalimaging.java2.update_image_set_metadata.import] +// snippet-start:[medicalimaging.java2.update_image_set_metadata.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; @@ -23,10 +17,11 @@ import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; -//snippet-end:[medicalimaging.java2.update_image_set_metadata.import] +// snippet-end:[medicalimaging.java2.update_image_set_metadata.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. *

    * For more information, see the following documentation topic: *

    @@ -34,68 +29,71 @@ */ public class UpdateImageSetMetadata { - public static void main(String[] args) { - final String usage = "\n" + - "Usage:\n" + - " \n\n" + - "Where:\n" + - " datastoreId - The ID of the data store.\n" + - " imagesetId - The ID of the image set.\n" + - " versionId - The latest version ID of the image set.\n"; - - if (args.length != 3) { - System.out.println(usage); - System.exit(1); + public static void main(String[] args) { + final String usage = "\n" + + "Usage:\n" + + " \n\n" + + "Where:\n" + + " datastoreId - The ID of the data store.\n" + + " imagesetId - The ID of the image set.\n" + + " versionId - The latest version ID of the image set.\n"; + + if (args.length != 3) { + System.out.println(usage); + System.exit(1); + } + + String datastoreId = args[0]; + String imagesetId = args[1]; + String versionid = args[2]; + + Region region = Region.US_WEST_2; + MedicalImagingClient medicalImagingClient = MedicalImagingClient.builder() + .region(region) + .credentialsProvider(ProfileCredentialsProvider.create()) + .build(); + + final String updateAttributes = "{\"SchemaVersion\":1.1,\"Patient\":{\"DICOM\":{\"PatientName\":\"MX^MX\"}}}"; + final String removeAttributes = "{\"SchemaVersion\":1.1,\"Patient\":{\"DICOM\":{\"PatientSex\":\"X\"}}}"; + MetadataUpdates metadataUpdates = MetadataUpdates.builder() + .dicomUpdates(DICOMUpdates.builder() + .updatableAttributes(SdkBytes.fromByteBuffer( + ByteBuffer.wrap(updateAttributes + .getBytes(StandardCharsets.UTF_8)))) + .removableAttributes(SdkBytes.fromByteBuffer( + ByteBuffer.wrap(removeAttributes + .getBytes(StandardCharsets.UTF_8)))) + .build()) + .build(); + + updateMedicalImageSetMetadata(medicalImagingClient, datastoreId, imagesetId, + versionid, metadataUpdates); + + medicalImagingClient.close(); } - String datastoreId = args[0]; - String imagesetId = args[1]; - String versionid = args[2]; - - Region region = Region.US_WEST_2; - MedicalImagingClient medicalImagingClient = MedicalImagingClient.builder() - .region(region) - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); - - final String updateAttributes = "{\"SchemaVersion\":1.1,\"Patient\":{\"DICOM\":{\"PatientName\":\"MX^MX\"}}}"; - final String removeAttributes = "{\"SchemaVersion\":1.1,\"Patient\":{\"DICOM\":{\"PatientSex\":\"X\"}}}"; - MetadataUpdates metadataUpdates = MetadataUpdates.builder() - .dicomUpdates(DICOMUpdates.builder() - .updatableAttributes(SdkBytes.fromByteBuffer( - ByteBuffer.wrap(updateAttributes.getBytes(StandardCharsets.UTF_8)))) - .removableAttributes(SdkBytes.fromByteBuffer( - ByteBuffer.wrap(removeAttributes.getBytes(StandardCharsets.UTF_8)))) - .build()) - .build(); - - updateMedicalImageSetMetadata(medicalImagingClient, datastoreId, imagesetId, - versionid, metadataUpdates); - - medicalImagingClient.close(); - } - - //snippet-start:[medicalimaging.java2.update_image_set_metadata.main] - public static void updateMedicalImageSetMetadata(MedicalImagingClient medicalImagingClient, - String datastoreId, - String imagesetId, - String versionId, - MetadataUpdates metadataUpdates) { - try { - UpdateImageSetMetadataRequest updateImageSetMetadataRequest = UpdateImageSetMetadataRequest.builder() - .datastoreId(datastoreId) - .imageSetId(imagesetId) - .latestVersionId(versionId) - .updateImageSetMetadataUpdates(metadataUpdates) - .build(); - - medicalImagingClient.updateImageSetMetadata(updateImageSetMetadataRequest); - - System.out.println("The image set metadata was updated"); - } catch (MedicalImagingException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + // snippet-start:[medicalimaging.java2.update_image_set_metadata.main] + public static void updateMedicalImageSetMetadata(MedicalImagingClient medicalImagingClient, + String datastoreId, + String imagesetId, + String versionId, + MetadataUpdates metadataUpdates) { + try { + UpdateImageSetMetadataRequest updateImageSetMetadataRequest = UpdateImageSetMetadataRequest + .builder() + .datastoreId(datastoreId) + .imageSetId(imagesetId) + .latestVersionId(versionId) + .updateImageSetMetadataUpdates(metadataUpdates) + .build(); + + medicalImagingClient.updateImageSetMetadata(updateImageSetMetadataRequest); + + System.out.println("The image set metadata was updated"); + } catch (MedicalImagingException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } } - } -//snippet-end:[medicalimaging.java2.update_image_set_metadata.main] + // snippet-end:[medicalimaging.java2.update_image_set_metadata.main] } diff --git a/javav2/example_code/medicalimaging/src/test/java/AWSMedicalImagingTest.java b/javav2/example_code/medicalimaging/src/test/java/AWSMedicalImagingTest.java index d3a90a2e1a2..64b0bc18670 100644 --- a/javav2/example_code/medicalimaging/src/test/java/AWSMedicalImagingTest.java +++ b/javav2/example_code/medicalimaging/src/test/java/AWSMedicalImagingTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.medicalimaging.*; import com.google.gson.Gson; @@ -45,8 +43,6 @@ public class AWSMedicalImagingTest { private static String importJobId = ""; - - @BeforeAll public static void setUp() { @@ -69,32 +65,34 @@ public static void setUp() { importJobId = values.getImportJobId(); dataResourceArn = values.getDataResourceArn(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - - try (InputStream input = AWSMedicalImagingTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - prop.load(input); - dataAccessRoleArn = prop.getProperty("dataAccessRoleArn"); - inputS3Uri= prop.getProperty("inputS3Uri"); - outputS3Uri= prop.getProperty("outputS3Uri"); - - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * + * try (InputStream input = + * AWSMedicalImagingTest.class.getClassLoader().getResourceAsStream( + * "config.properties")) { + * Properties prop = new Properties(); + * prop.load(input); + * dataAccessRoleArn = prop.getProperty("dataAccessRoleArn"); + * inputS3Uri= prop.getProperty("inputS3Uri"); + * outputS3Uri= prop.getProperty("outputS3Uri"); + * + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } - @SuppressWarnings("resource") private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_WEST_2) // TODO: change back to US-EAST-1 + .region(Region.US_WEST_2) // TODO: change back to US-EAST-1 .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); String secretName = "test/medicalimaging"; @@ -111,7 +109,8 @@ private static String getSecretValues() { @Tag("IntegrationTest") @Order(1) public void createDatastoreTest() { - assertDoesNotThrow(() -> createdDatastoreId = CreateDatastore.createMedicalImageDatastore(medicalImagingClient, datastoreName)); + assertDoesNotThrow(() -> createdDatastoreId = CreateDatastore.createMedicalImageDatastore(medicalImagingClient, + datastoreName)); assert (!createdDatastoreId.isEmpty()); } @@ -120,8 +119,9 @@ public void createDatastoreTest() { @Tag("IntegrationTest") @Order(2) public void getDatastoreTest() { - final DatastoreProperties[] datastoreProperties = {null}; - assertDoesNotThrow(() -> datastoreProperties[0] = GetDatastore.getMedicalImageDatastore(medicalImagingClient, workingDatastoreId)); + final DatastoreProperties[] datastoreProperties = { null }; + assertDoesNotThrow(() -> datastoreProperties[0] = GetDatastore.getMedicalImageDatastore(medicalImagingClient, + workingDatastoreId)); assertNotNull(datastoreProperties[0]); System.out.println("Test 2 passed"); @@ -132,8 +132,10 @@ public void getDatastoreTest() { @Tag("IntegrationTest") @Order(3) public void listDatastoresTest() { - @SuppressWarnings("rawtypes") final List[] dataStoreSummaries = {null}; - assertDoesNotThrow(() -> dataStoreSummaries[0] = ListDatastores.listMedicalImagingDatastores(medicalImagingClient)); + @SuppressWarnings("rawtypes") + final List[] dataStoreSummaries = { null }; + assertDoesNotThrow( + () -> dataStoreSummaries[0] = ListDatastores.listMedicalImagingDatastores(medicalImagingClient)); assertNotNull(dataStoreSummaries[0]); System.out.println("Test 3 passed"); @@ -144,7 +146,7 @@ public void listDatastoresTest() { @Tag("IntegrationTest") @Order(4) public void getDicomImportJobTest() { - final DICOMImportJobProperties[] dicomImportJobSummaries = {null}; + final DICOMImportJobProperties[] dicomImportJobSummaries = { null }; assertDoesNotThrow(() -> dicomImportJobSummaries[0] = GetDicomImportJob.getDicomImportJob(medicalImagingClient, workingDatastoreId, importJobId)); assertNotNull(dicomImportJobSummaries[0]); @@ -156,9 +158,11 @@ public void getDicomImportJobTest() { @Tag("IntegrationTest") @Order(5) public void listDicomImportJobsTest() { - @SuppressWarnings("rawtypes") final List[] dicomImportJobSummaries = {null}; - assertDoesNotThrow(() -> dicomImportJobSummaries[0] = ListDicomImportJobs.listDicomImportJobs(medicalImagingClient, - workingDatastoreId)); + @SuppressWarnings("rawtypes") + final List[] dicomImportJobSummaries = { null }; + assertDoesNotThrow( + () -> dicomImportJobSummaries[0] = ListDicomImportJobs.listDicomImportJobs(medicalImagingClient, + workingDatastoreId)); assertNotNull(dicomImportJobSummaries[0]); System.out.println("Test 5 passed"); @@ -171,14 +175,15 @@ public void searchImageSetsTest() { List searchFilters = Collections.singletonList(SearchFilter.builder() .operator(Operator.BETWEEN) .values(SearchByAttributeValue.builder() - .createdAt(Instant.parse("1985-04-12T23:20:50.52Z")) - .build(), + .createdAt(Instant.parse("1985-04-12T23:20:50.52Z")) + .build(), SearchByAttributeValue.builder() .createdAt(Instant.now()) .build()) .build()); - @SuppressWarnings("rawtypes") final List[] searchResults = {null}; + @SuppressWarnings("rawtypes") + final List[] searchResults = { null }; assertDoesNotThrow(() -> searchResults[0] = SearchImageSets.searchMedicalImagingImageSets(medicalImagingClient, workingDatastoreId, searchFilters)); assertNotNull(searchResults[0]); @@ -190,7 +195,7 @@ public void searchImageSetsTest() { @Tag("IntegrationTest") @Order(7) public void getImageSetTest() { - final GetImageSetResponse[] imageSetResponses = {null}; + final GetImageSetResponse[] imageSetResponses = { null }; assertDoesNotThrow(() -> imageSetResponses[0] = GetImageSet.getMedicalImageSet(medicalImagingClient, workingDatastoreId, imageSetId, "1")); assertNotNull(imageSetResponses[0]); @@ -208,7 +213,7 @@ public void getImageSetMetadataTest() { File metadataFile = new File(metadataFileName); assert (metadataFile.exists()); - //noinspection ResultOfMethodCallIgnored + // noinspection ResultOfMethodCallIgnored metadataFile.delete(); System.out.println("Test 8 passed"); @@ -224,7 +229,7 @@ public void getImageFrameTest() { File imageFile = new File(imageFileName); assert (imageFile.exists()); - //noinspection ResultOfMethodCallIgnored + // noinspection ResultOfMethodCallIgnored imageFile.delete(); System.out.println("Test 9 passed"); @@ -234,8 +239,10 @@ public void getImageFrameTest() { @Tag("IntegrationTest") @Order(10) public void listImageSetVersionsTest() { - @SuppressWarnings("rawtypes") List[] imageSetVersions = new List[1]; - assertDoesNotThrow(() -> imageSetVersions[0] = ListImageSetVersions.listMedicalImageSetVersions(medicalImagingClient, workingDatastoreId, imageSetId)); + @SuppressWarnings("rawtypes") + List[] imageSetVersions = new List[1]; + assertDoesNotThrow(() -> imageSetVersions[0] = ListImageSetVersions + .listMedicalImageSetVersions(medicalImagingClient, workingDatastoreId, imageSetId)); assertNotNull(imageSetVersions[0]); System.out.println("Test 10 passed"); @@ -245,8 +252,8 @@ public void listImageSetVersionsTest() { @Tag("IntegrationTest") @Order(11) public void tagResourceTest() { - assertDoesNotThrow(() -> TagResource.tagMedicalImagingResource(medicalImagingClient, dataResourceArn, ImmutableMap.of("Deployment", "Development"))); - + assertDoesNotThrow(() -> TagResource.tagMedicalImagingResource(medicalImagingClient, dataResourceArn, + ImmutableMap.of("Deployment", "Development"))); System.out.println("Test 11 passed"); } @@ -255,8 +262,9 @@ public void tagResourceTest() { @Tag("IntegrationTest") @Order(12) public void listTagsForResourceTest() { - ListTagsForResourceResponse[] listTagsForResourceResponses = {null}; - assertDoesNotThrow(() -> listTagsForResourceResponses[0] = ListTagsForResource.listMedicalImagingResourceTags(medicalImagingClient, dataResourceArn)); + ListTagsForResourceResponse[] listTagsForResourceResponses = { null }; + assertDoesNotThrow(() -> listTagsForResourceResponses[0] = ListTagsForResource + .listMedicalImagingResourceTags(medicalImagingClient, dataResourceArn)); assertNotNull(listTagsForResourceResponses[0]); System.out.println("Test 12 passed"); @@ -266,12 +274,12 @@ public void listTagsForResourceTest() { @Tag("IntegrationTest") @Order(13) public void untagResourceTest() { - assertDoesNotThrow(() -> UntagResource.untagMedicalImagingResource(medicalImagingClient, dataResourceArn, Collections.singletonList("Deployment"))); + assertDoesNotThrow(() -> UntagResource.untagMedicalImagingResource(medicalImagingClient, dataResourceArn, + Collections.singletonList("Deployment"))); System.out.println("Test 13 passed"); } - @Test @Tag("IntegrationTest") @Order(14) @@ -279,15 +287,17 @@ public void deleteDatastoreTest() { assert (!createdDatastoreId.isEmpty()); int count = 0; while (count < 20) { - final DatastoreProperties[] datastoreProperties = {null}; - assertDoesNotThrow(() -> datastoreProperties[0] = GetDatastore.getMedicalImageDatastore(medicalImagingClient, workingDatastoreId)); + final DatastoreProperties[] datastoreProperties = { null }; + assertDoesNotThrow(() -> datastoreProperties[0] = GetDatastore + .getMedicalImageDatastore(medicalImagingClient, workingDatastoreId)); if (datastoreProperties[0].datastoreStatus().toString().equals("ACTIVE")) { break; } assertDoesNotThrow(() -> Thread.sleep(1000)); count++; } - assertDoesNotThrow(() -> DeleteDatastore.deleteMedicalImagingDatastore(medicalImagingClient, createdDatastoreId)); + assertDoesNotThrow( + () -> DeleteDatastore.deleteMedicalImagingDatastore(medicalImagingClient, createdDatastoreId)); System.out.println("Test 14 passed"); } diff --git a/javav2/example_code/memorydb/src/main/java/com/example/memorydb/CreateCluster.java b/javav2/example_code/memorydb/src/main/java/com/example/memorydb/CreateCluster.java index 6f9f3ce6540..d39680f89a6 100644 --- a/javav2/example_code/memorydb/src/main/java/com/example/memorydb/CreateCluster.java +++ b/javav2/example_code/memorydb/src/main/java/com/example/memorydb/CreateCluster.java @@ -1,36 +1,30 @@ -//snippet-sourcedescription:[CreateCluster.java demonstrates how to create a cluster.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon MemoryDB for Redis] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.memorydb; -//snippet-start:[memoryDB.java2.create_cluster.main] -//snippet-start:[memoryDB.java2.create_cluster.import] +// snippet-start:[memoryDB.java2.create_cluster.main] +// snippet-start:[memoryDB.java2.create_cluster.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.memorydb.MemoryDbClient; import software.amazon.awssdk.services.memorydb.model.CreateClusterRequest; import software.amazon.awssdk.services.memorydb.model.CreateClusterResponse; import software.amazon.awssdk.services.memorydb.model.MemoryDbException; -//snippet-end:[memoryDB.java2.create_cluster.import] +// snippet-end:[memoryDB.java2.create_cluster.import] public class CreateCluster { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - clusterName - The name of the cluster.\s - nodeType - The compute and memory capacity of the nodes in the cluster.\s - subnetGroupName - The name of the subnet group to use for the cluster.\s - aclName - The name of the access control list (ACL) to associate with the cluster.\s - """; + Where: + clusterName - The name of the cluster.\s + nodeType - The compute and memory capacity of the nodes in the cluster.\s + subnetGroupName - The name of the subnet group to use for the cluster.\s + aclName - The name of the access control list (ACL) to associate with the cluster.\s + """; if (args.length != 4) { System.out.println(usage); @@ -43,23 +37,24 @@ public static void main(String[] args) { String aclName = args[3]; Region region = Region.US_EAST_1; MemoryDbClient memoryDbClient = MemoryDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); createSingleCluster(memoryDbClient, clusterName, nodeType, subnetGroupName, aclName); } - public static void createSingleCluster(MemoryDbClient memoryDbClient, String clusterName, String nodeType, String subnetGroupName, String aclName) { + public static void createSingleCluster(MemoryDbClient memoryDbClient, String clusterName, String nodeType, + String subnetGroupName, String aclName) { try { CreateClusterRequest request = CreateClusterRequest.builder() - .clusterName(clusterName) - .aclName(aclName) - .description("Created using the AWS SDK for Java") - .numShards(1) - .nodeType(nodeType) - .port(6379) - .subnetGroupName(subnetGroupName) - .build(); + .clusterName(clusterName) + .aclName(aclName) + .description("Created using the AWS SDK for Java") + .numShards(1) + .nodeType(nodeType) + .port(6379) + .subnetGroupName(subnetGroupName) + .build(); CreateClusterResponse response = memoryDbClient.createCluster(request); System.out.println("Cluster created. The ARN is " + response.cluster().arn()); @@ -70,4 +65,4 @@ public static void createSingleCluster(MemoryDbClient memoryDbClient, String clu } } } -//snippet-end:[memoryDB.java2.create_cluster.main] +// snippet-end:[memoryDB.java2.create_cluster.main] diff --git a/javav2/example_code/memorydb/src/main/java/com/example/memorydb/CreateSnapshot.java b/javav2/example_code/memorydb/src/main/java/com/example/memorydb/CreateSnapshot.java index e2c070895fd..627f1e83811 100644 --- a/javav2/example_code/memorydb/src/main/java/com/example/memorydb/CreateSnapshot.java +++ b/javav2/example_code/memorydb/src/main/java/com/example/memorydb/CreateSnapshot.java @@ -1,34 +1,28 @@ -//snippet-sourcedescription:[CreateSnapshot.java demonstrates how to create a copy of a cluster at a specific moment in time.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon MemoryDB for Redis] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.memorydb; -//snippet-start:[memoryDB.java2.create_snapshot.main] -//snippet-start:[memoryDB.java2.create_snapshot.import] +// snippet-start:[memoryDB.java2.create_snapshot.main] +// snippet-start:[memoryDB.java2.create_snapshot.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.memorydb.MemoryDbClient; import software.amazon.awssdk.services.memorydb.model.CreateSnapshotRequest; import software.amazon.awssdk.services.memorydb.model.CreateSnapshotResponse; import software.amazon.awssdk.services.memorydb.model.MemoryDbException; -//snippet-end:[memoryDB.java2.create_snapshot.import] +// snippet-end:[memoryDB.java2.create_snapshot.import] public class CreateSnapshot { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - clusterName - The name of the cluster.\s - snapShotName - The name for the snapshot being created.\s - """; + Where: + clusterName - The name of the cluster.\s + snapShotName - The name for the snapshot being created.\s + """; if (args.length != 2) { System.out.println(usage); @@ -39,8 +33,8 @@ public static void main(String[] args) { String snapShotName = args[1]; Region region = Region.US_EAST_1; MemoryDbClient memoryDbClient = MemoryDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); createSpecificSnapshot(memoryDbClient, clusterName, snapShotName); } @@ -48,9 +42,9 @@ public static void main(String[] args) { public static void createSpecificSnapshot(MemoryDbClient memoryDbClient, String clusterName, String snapShotName) { try { CreateSnapshotRequest request = CreateSnapshotRequest.builder() - .clusterName(clusterName) - .snapshotName(snapShotName) - .build(); + .clusterName(clusterName) + .snapshotName(snapShotName) + .build(); CreateSnapshotResponse response = memoryDbClient.createSnapshot(request); System.out.println("The ARN of the response is" + response.snapshot().arn()); @@ -61,4 +55,4 @@ public static void createSpecificSnapshot(MemoryDbClient memoryDbClient, String } } } - //snippet-end:[memoryDB.java2.create_snapshot.main] +// snippet-end:[memoryDB.java2.create_snapshot.main] diff --git a/javav2/example_code/memorydb/src/main/java/com/example/memorydb/DeleteCluster.java b/javav2/example_code/memorydb/src/main/java/com/example/memorydb/DeleteCluster.java index b8b4597a868..7d923f73109 100644 --- a/javav2/example_code/memorydb/src/main/java/com/example/memorydb/DeleteCluster.java +++ b/javav2/example_code/memorydb/src/main/java/com/example/memorydb/DeleteCluster.java @@ -1,31 +1,26 @@ -//snippet-sourcedescription:[DeleteClusters.java demonstrates how to delete a cluster.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon MemoryDB for Redis] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.memorydb; -//snippet-start:[memoryDB.java2.del_cluster.main] -//snippet-start:[memoryDB.java2.del_cluster.import] +// snippet-start:[memoryDB.java2.del_cluster.main] +// snippet-start:[memoryDB.java2.del_cluster.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.memorydb.MemoryDbClient; import software.amazon.awssdk.services.memorydb.model.DeleteClusterRequest; import software.amazon.awssdk.services.memorydb.model.MemoryDbException; -//snippet-end:[memoryDB.java2.del_cluster.import] +// snippet-end:[memoryDB.java2.del_cluster.import] public class DeleteCluster { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - clusterName - The name of the cluster.\s - """; + Where: + clusterName - The name of the cluster.\s + """; if (args.length != 1) { System.out.println(usage); @@ -35,8 +30,8 @@ public static void main(String[] args) { String clusterName = args[0]; Region region = Region.US_EAST_1; MemoryDbClient memoryDbClient = MemoryDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteSpecificCluster(memoryDbClient, clusterName); } @@ -44,8 +39,8 @@ public static void main(String[] args) { public static void deleteSpecificCluster(MemoryDbClient memoryDbClient, String clusterName) { try { DeleteClusterRequest clusterRequest = DeleteClusterRequest.builder() - .clusterName(clusterName) - .build(); + .clusterName(clusterName) + .build(); memoryDbClient.deleteCluster(clusterRequest); System.out.println(clusterName + " was successfully deleted"); @@ -56,4 +51,4 @@ public static void deleteSpecificCluster(MemoryDbClient memoryDbClient, String c } } } -//snippet-end:[memoryDB.java2.del_cluster.main] +// snippet-end:[memoryDB.java2.del_cluster.main] diff --git a/javav2/example_code/memorydb/src/main/java/com/example/memorydb/DescribeClusters.java b/javav2/example_code/memorydb/src/main/java/com/example/memorydb/DescribeClusters.java index 50896a191d3..0a566b427d6 100644 --- a/javav2/example_code/memorydb/src/main/java/com/example/memorydb/DescribeClusters.java +++ b/javav2/example_code/memorydb/src/main/java/com/example/memorydb/DescribeClusters.java @@ -1,16 +1,10 @@ -//snippet-sourcedescription:[DescribeClusters.java demonstrates how to retrieve information about all provisioned clusters.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon MemoryDB for Redis] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.memorydb; -//snippet-start:[memoryDB.java2.describe_clusters.main] -//snippet-start:[memoryDB.java2.describe_clusters.import] +// snippet-start:[memoryDB.java2.describe_clusters.main] +// snippet-start:[memoryDB.java2.describe_clusters.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.memorydb.MemoryDbClient; import software.amazon.awssdk.services.memorydb.model.Cluster; @@ -18,14 +12,14 @@ import software.amazon.awssdk.services.memorydb.model.DescribeClustersResponse; import software.amazon.awssdk.services.memorydb.model.MemoryDbException; import java.util.List; -//snippet-end:[memoryDB.java2.describe_clusters.import] +// snippet-end:[memoryDB.java2.describe_clusters.import] public class DescribeClusters { public static void main(String[] args) { Region region = Region.US_EAST_1; MemoryDbClient memoryDbClient = MemoryDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); getClusters(memoryDbClient); } @@ -33,7 +27,7 @@ public static void main(String[] args) { public static void getClusters(MemoryDbClient memoryDbClient) { try { DescribeClustersRequest request = DescribeClustersRequest.builder() - .build(); + .build(); DescribeClustersResponse response = memoryDbClient.describeClusters(request); List clusters = response.clusters(); @@ -49,4 +43,4 @@ public static void getClusters(MemoryDbClient memoryDbClient) { } } } -//snippet-end:[memoryDB.java2.describe_clusters.main] +// snippet-end:[memoryDB.java2.describe_clusters.main] diff --git a/javav2/example_code/memorydb/src/main/java/com/example/memorydb/DescribeSnapshots.java b/javav2/example_code/memorydb/src/main/java/com/example/memorydb/DescribeSnapshots.java index ff675566a88..c82ed7399e8 100644 --- a/javav2/example_code/memorydb/src/main/java/com/example/memorydb/DescribeSnapshots.java +++ b/javav2/example_code/memorydb/src/main/java/com/example/memorydb/DescribeSnapshots.java @@ -1,16 +1,10 @@ -//snippet-sourcedescription:[DescribeSnapshots.java demonstrates how to return information about cluster snapshots.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon MemoryDB for Redis] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.memorydb; -//snippet-start:[memoryDB.java2.describe_snapshot.main] -//snippet-start:[memoryDB.java2.describe_snapshot.import] +// snippet-start:[memoryDB.java2.describe_snapshot.main] +// snippet-start:[memoryDB.java2.describe_snapshot.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.memorydb.MemoryDbClient; import software.amazon.awssdk.services.memorydb.model.DescribeSnapshotsRequest; @@ -18,18 +12,18 @@ import software.amazon.awssdk.services.memorydb.model.MemoryDbException; import software.amazon.awssdk.services.memorydb.model.Snapshot; import java.util.List; -//snippet-end:[memoryDB.java2.describe_snapshot.import] +// snippet-end:[memoryDB.java2.describe_snapshot.import] public class DescribeSnapshots { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - clusterName - The name of the cluster.\s - """; + Where: + clusterName - The name of the cluster.\s + """; if (args.length != 1) { System.out.println(usage); @@ -39,8 +33,8 @@ public static void main(String[] args) { String clusterName = args[0]; Region region = Region.US_EAST_1; MemoryDbClient memoryDbClient = MemoryDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeALlSnapshots(memoryDbClient, clusterName); } @@ -48,9 +42,9 @@ public static void main(String[] args) { public static void describeALlSnapshots(MemoryDbClient memoryDbClient, String clusterName) { try { DescribeSnapshotsRequest request = DescribeSnapshotsRequest.builder() - .maxResults(10) - .clusterName(clusterName) - .build(); + .maxResults(10) + .clusterName(clusterName) + .build(); DescribeSnapshotsResponse response = memoryDbClient.describeSnapshots(request); List snapshots = response.snapshots(); @@ -65,4 +59,4 @@ public static void describeALlSnapshots(MemoryDbClient memoryDbClient, String cl } } } -//snippet-end:[memoryDB.java2.describe_snapshot.main] +// snippet-end:[memoryDB.java2.describe_snapshot.main] diff --git a/javav2/example_code/memorydb/src/main/java/com/example/memorydb/DescribeSpecificCluster.java b/javav2/example_code/memorydb/src/main/java/com/example/memorydb/DescribeSpecificCluster.java index e109b4b9f5e..32082597c37 100644 --- a/javav2/example_code/memorydb/src/main/java/com/example/memorydb/DescribeSpecificCluster.java +++ b/javav2/example_code/memorydb/src/main/java/com/example/memorydb/DescribeSpecificCluster.java @@ -1,16 +1,10 @@ -//snippet-sourcedescription:[DescribeSpecificCluster.java demonstrates how to retrieve information about a specific cluster.] -//snippet-keyword:[SDK for Java v2] -//snippet-service:[Amazon MemoryDB for Redis] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.memorydb; -//snippet-start:[memoryDB.java2.describe_sin_cluster.main] -//snippet-start:[memoryDB.java2.describe_sin_cluster.import] +// snippet-start:[memoryDB.java2.describe_sin_cluster.main] +// snippet-start:[memoryDB.java2.describe_sin_cluster.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.memorydb.MemoryDbClient; import software.amazon.awssdk.services.memorydb.model.Cluster; @@ -18,18 +12,18 @@ import software.amazon.awssdk.services.memorydb.model.DescribeClustersResponse; import software.amazon.awssdk.services.memorydb.model.MemoryDbException; import java.util.List; -//snippet-end:[memoryDB.java2.describe_sin_cluster.import] +// snippet-end:[memoryDB.java2.describe_sin_cluster.import] public class DescribeSpecificCluster { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - clusterName - The name of the cluster.\s - """; + Where: + clusterName - The name of the cluster.\s + """; if (args.length != 1) { System.out.println(usage); @@ -39,11 +33,12 @@ public static void main(String[] args) { String clusterName = args[0]; Region region = Region.US_EAST_1; MemoryDbClient memoryDbClient = MemoryDbClient.builder() - .region(region) - .build(); + .region(region) + .build(); checkIfAvailable(memoryDbClient, clusterName); } + public static void checkIfAvailable(MemoryDbClient memoryDbClient, String clusterName) { try { String status; @@ -72,8 +67,8 @@ private static Cluster getCluster(MemoryDbClient memoryDbClient, String clusterN try { DescribeClustersRequest request = DescribeClustersRequest.builder() - .clusterName(clusterName) - .build(); + .clusterName(clusterName) + .build(); DescribeClustersResponse response = memoryDbClient.describeClusters(request); List clusters = response.clusters(); @@ -90,4 +85,4 @@ private static Cluster getCluster(MemoryDbClient memoryDbClient, String clusterN return null; } } - //snippet-end:[memoryDB.java2.describe_sin_cluster.main] +// snippet-end:[memoryDB.java2.describe_sin_cluster.main] diff --git a/javav2/example_code/memorydb/src/test/java/MemoryDBTest.java b/javav2/example_code/memorydb/src/test/java/MemoryDBTest.java index bef0be4a095..608276eded3 100644 --- a/javav2/example_code/memorydb/src/test/java/MemoryDBTest.java +++ b/javav2/example_code/memorydb/src/test/java/MemoryDBTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.memorydb.*; import com.google.gson.Gson; @@ -23,19 +21,19 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class MemoryDBTest { private static MemoryDbClient memoryDbClient; - private static String clusterName=""; - private static String nodeType=""; - private static String subnetGroupName=""; - private static String aclName=""; - private static String snapShotName=""; + private static String clusterName = ""; + private static String nodeType = ""; + private static String subnetGroupName = ""; + private static String aclName = ""; + private static String snapShotName = ""; @BeforeAll public static void setUp() { Region region = Region.US_EAST_1; memoryDbClient = MemoryDbClient.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); Random random = new Random(); int randomNum = random.nextInt((10000 - 1) + 1) + 1; @@ -44,39 +42,43 @@ public static void setUp() { Gson gson = new Gson(); String json = getSecretValues(); SecretValues values = gson.fromJson(json, SecretValues.class); - clusterName = values.getClusterName()+ randomNum; + clusterName = values.getClusterName() + randomNum; nodeType = values.getNodeType(); subnetGroupName = values.getSubnetGroupName(); aclName = values.getAclName(); - snapShotName= values.getSnapShotName()+randomNum; - - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - try (InputStream input = MemoryDBTest.class.getClassLoader().getResourceAsStream("config.properties")) { - - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - prop.load(input); - clusterName = prop.getProperty("clusterName")+ java.util.UUID.randomUUID(); - nodeType = prop.getProperty("nodeType"); - subnetGroupName = prop.getProperty("subnetGroupName"); - aclName = prop.getProperty("aclName"); - snapShotName= prop.getProperty("snapShotName"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + snapShotName = values.getSnapShotName() + randomNum; + + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * try (InputStream input = + * MemoryDBTest.class.getClassLoader().getResourceAsStream("config.properties")) + * { + * + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * prop.load(input); + * clusterName = prop.getProperty("clusterName")+ java.util.UUID.randomUUID(); + * nodeType = prop.getProperty("nodeType"); + * subnetGroupName = prop.getProperty("subnetGroupName"); + * aclName = prop.getProperty("aclName"); + * snapShotName= prop.getProperty("snapShotName"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @Tag("IntegrationTest") @Order(1) public void createCluster() { - assertDoesNotThrow(() ->CreateCluster.createSingleCluster(memoryDbClient, clusterName, nodeType, subnetGroupName, aclName)); + assertDoesNotThrow(() -> CreateCluster.createSingleCluster(memoryDbClient, clusterName, nodeType, + subnetGroupName, aclName)); System.out.println("Test 1 passed"); } @@ -84,7 +86,7 @@ public void createCluster() { @Tag("IntegrationTest") @Order(2) public void describeSpecificCluster() { - assertDoesNotThrow(() ->DescribeSpecificCluster.checkIfAvailable(memoryDbClient, clusterName)); + assertDoesNotThrow(() -> DescribeSpecificCluster.checkIfAvailable(memoryDbClient, clusterName)); System.out.println("Test 2 passed"); } @@ -92,7 +94,7 @@ public void describeSpecificCluster() { @Tag("IntegrationTest") @Order(3) public void createSnapshot() { - assertDoesNotThrow(() ->CreateSnapshot.createSpecificSnapshot(memoryDbClient, clusterName, snapShotName)); + assertDoesNotThrow(() -> CreateSnapshot.createSpecificSnapshot(memoryDbClient, clusterName, snapShotName)); System.out.println("Test 3 passed"); } @@ -100,7 +102,7 @@ public void createSnapshot() { @Tag("IntegrationTest") @Order(4) public void describeSnapshot() { - assertDoesNotThrow(() ->DescribeSnapshots.describeALlSnapshots(memoryDbClient, clusterName)); + assertDoesNotThrow(() -> DescribeSnapshots.describeALlSnapshots(memoryDbClient, clusterName)); System.out.println("Test 4 passed"); } @@ -108,8 +110,8 @@ public void describeSnapshot() { @Tag("IntegrationTest") @Order(5) public void describeAllClusters() { - assertDoesNotThrow(() ->DescribeClusters.getClusters(memoryDbClient)); - assertDoesNotThrow(() ->DescribeSpecificCluster.checkIfAvailable(memoryDbClient, clusterName)); + assertDoesNotThrow(() -> DescribeClusters.getClusters(memoryDbClient)); + assertDoesNotThrow(() -> DescribeSpecificCluster.checkIfAvailable(memoryDbClient, clusterName)); System.out.println("Test 5 passed"); } @@ -117,19 +119,20 @@ public void describeAllClusters() { @Tag("IntegrationTest") @Order(6) public void deleteCluster() { - assertDoesNotThrow(() ->DeleteCluster.deleteSpecificCluster(memoryDbClient, clusterName)); + assertDoesNotThrow(() -> DeleteCluster.deleteSpecificCluster(memoryDbClient, clusterName)); System.out.println("Test 6 passed"); } + private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/memorydb"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -167,6 +170,3 @@ public String getAclName() { } } } - - - diff --git a/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/DeleteProgressStream.java b/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/DeleteProgressStream.java index 2dfc706bac8..4a920367c79 100644 --- a/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/DeleteProgressStream.java +++ b/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/DeleteProgressStream.java @@ -1,11 +1,5 @@ -// snippet-sourcedescription:[DeleteProgressStream.java demonstrates how to delete a progress stream.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS Migration Hub] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.migrationhub; @@ -18,7 +12,8 @@ // snippet-end:[migration.java2.delete_progress_stream.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +23,12 @@ public class DeleteProgressStream { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - progressStream - the name of a progress stream to delete.\s - """; + Where: + progressStream - the name of a progress stream to delete.\s + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +38,8 @@ public static void main(String[] args) { String progressStream = args[0]; Region region = Region.US_WEST_2; MigrationHubClient migrationClient = MigrationHubClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteStream(migrationClient, progressStream); migrationClient.close(); @@ -52,9 +47,10 @@ public static void main(String[] args) { public static void deleteStream(MigrationHubClient migrationClient, String streamName) { try { - DeleteProgressUpdateStreamRequest deleteProgressUpdateStreamRequest = DeleteProgressUpdateStreamRequest.builder() - .progressUpdateStreamName(streamName) - .build(); + DeleteProgressUpdateStreamRequest deleteProgressUpdateStreamRequest = DeleteProgressUpdateStreamRequest + .builder() + .progressUpdateStreamName(streamName) + .build(); migrationClient.deleteProgressUpdateStream(deleteProgressUpdateStreamRequest); System.out.println(streamName + " is deleted"); diff --git a/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/DescribeAppState.java b/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/DescribeAppState.java index 6b8412b598b..b3f1d0e31a2 100644 --- a/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/DescribeAppState.java +++ b/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/DescribeAppState.java @@ -1,11 +1,5 @@ -// snippet-sourcedescription:[DescribeAppState.java demonstrates how to get the migration status of an application.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS Migration Hub] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.migrationhub; @@ -19,7 +13,8 @@ // snippet-end:[migration.java2.describe_app_state.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,12 +24,12 @@ public class DescribeAppState { public static void main(String[] args) { final String usage = """ - Usage: - DescribeAppState \s + Usage: + DescribeAppState \s - Where: - appId - the application id value.\s - """; + Where: + appId - the application id value.\s + """; if (args.length != 1) { System.out.println(usage); @@ -44,8 +39,8 @@ public static void main(String[] args) { String appId = args[0]; Region region = Region.US_WEST_2; MigrationHubClient migrationClient = MigrationHubClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeApplicationState(migrationClient, appId); migrationClient.close(); @@ -54,10 +49,11 @@ public static void main(String[] args) { public static void describeApplicationState(MigrationHubClient migrationClient, String appId) { try { DescribeApplicationStateRequest applicationStateRequest = DescribeApplicationStateRequest.builder() - .applicationId(appId) - .build(); + .applicationId(appId) + .build(); - DescribeApplicationStateResponse applicationStateResponse = migrationClient.describeApplicationState(applicationStateRequest); + DescribeApplicationStateResponse applicationStateResponse = migrationClient + .describeApplicationState(applicationStateRequest); System.out.println("The application status is " + applicationStateResponse.applicationStatusAsString()); } catch (MigrationHubException e) { diff --git a/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/DescribeMigrationTask.java b/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/DescribeMigrationTask.java index 6bb3192583e..753623452d6 100644 --- a/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/DescribeMigrationTask.java +++ b/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/DescribeMigrationTask.java @@ -1,11 +1,5 @@ -// snippet-sourcedescription:[DescribeMigrationTask.java demonstrates how to get a list of attributes associated with a migration task.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS Migration Hub] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.migrationhub; @@ -19,7 +13,8 @@ // snippet-end:[migration.java2.describe_migration.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,13 +25,13 @@ public class DescribeMigrationTask { public static void main(String[] args) { final String usage = """ - Usage: - DescribeMigrationTask \s + Usage: + DescribeMigrationTask \s - Where: - migrationTask - the name of a migration task.\s - progressStream - the name of a progress stream.\s - """; + Where: + migrationTask - the name of a migration task.\s + progressStream - the name of a progress stream.\s + """; if (args.length < 2) { System.out.println(usage); @@ -47,21 +42,23 @@ public static void main(String[] args) { String progressStream = args[1]; Region region = Region.US_WEST_2; MigrationHubClient migrationClient = MigrationHubClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeMigTask(migrationClient, migrationTask, progressStream); migrationClient.close(); } - public static void describeMigTask(MigrationHubClient migrationClient, String migrationTask, String progressStream) { + public static void describeMigTask(MigrationHubClient migrationClient, String migrationTask, + String progressStream) { try { DescribeMigrationTaskRequest migrationTaskRequestRequest = DescribeMigrationTaskRequest.builder() - .progressUpdateStream(progressStream) - .migrationTaskName(migrationTask) - .build(); + .progressUpdateStream(progressStream) + .migrationTaskName(migrationTask) + .build(); - DescribeMigrationTaskResponse migrationTaskResponse = migrationClient.describeMigrationTask(migrationTaskRequestRequest); + DescribeMigrationTaskResponse migrationTaskResponse = migrationClient + .describeMigrationTask(migrationTaskRequestRequest); System.out.println("The name is " + migrationTaskResponse.migrationTask().migrationTaskName()); } catch (MigrationHubException e) { diff --git a/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/ImportMigrationTask.java b/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/ImportMigrationTask.java index 7f7eac360b2..466197a8f54 100644 --- a/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/ImportMigrationTask.java +++ b/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/ImportMigrationTask.java @@ -1,11 +1,5 @@ -// snippet-sourcedescription:[ImportMigrationTask.java demonstrates how to register a new migration task.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS Migration Hub] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.migrationhub; @@ -19,7 +13,8 @@ // snippet-end:[migration.java2.import_migration.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,13 +24,13 @@ public class ImportMigrationTask { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - migrationTask - the name of a migration task.\s - progressStream - the name of a progress stream.\s - """; + Where: + migrationTask - the name of a migration task.\s + progressStream - the name of a progress stream.\s + """; if (args.length != 2) { System.out.println(usage); @@ -46,8 +41,8 @@ public static void main(String[] args) { String progressStream = args[1]; Region region = Region.US_WEST_2; MigrationHubClient migrationClient = MigrationHubClient.builder() - .region(region) - .build(); + .region(region) + .build(); importMigrTask(migrationClient, migrationTask, progressStream); migrationClient.close(); @@ -56,16 +51,16 @@ public static void main(String[] args) { public static void importMigrTask(MigrationHubClient migrationClient, String migrationTask, String progressStream) { try { CreateProgressUpdateStreamRequest progressUpdateStreamRequest = CreateProgressUpdateStreamRequest.builder() - .progressUpdateStreamName(progressStream) - .dryRun(false) - .build(); + .progressUpdateStreamName(progressStream) + .dryRun(false) + .build(); migrationClient.createProgressUpdateStream(progressUpdateStreamRequest); ImportMigrationTaskRequest migrationTaskRequest = ImportMigrationTaskRequest.builder() - .migrationTaskName(migrationTask) - .progressUpdateStream(progressStream) - .dryRun(false) - .build(); + .migrationTaskName(migrationTask) + .progressUpdateStream(progressStream) + .dryRun(false) + .build(); migrationClient.importMigrationTask(migrationTaskRequest); diff --git a/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/ListApplications.java b/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/ListApplications.java index 89f00d5165a..be92edf65cd 100644 --- a/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/ListApplications.java +++ b/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/ListApplications.java @@ -1,11 +1,5 @@ -// snippet-sourcedescription:[ListApplications.java demonstrates how to list applications.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS Migration Hub] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.migrationhub; @@ -15,13 +9,14 @@ import software.amazon.awssdk.services.migrationhub.MigrationHubClient; import software.amazon.awssdk.services.migrationhub.model.ApplicationState; import software.amazon.awssdk.services.migrationhub.model.ListApplicationStatesRequest; -import software.amazon.awssdk.services.migrationhub.model.ListApplicationStatesResponse ; +import software.amazon.awssdk.services.migrationhub.model.ListApplicationStatesResponse; import software.amazon.awssdk.services.migrationhub.model.MigrationHubException; import java.util.List; // snippet-end:[migration.java2.list_apps.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,8 +26,8 @@ public class ListApplications { public static void main(String[] args) { Region region = Region.US_WEST_2; MigrationHubClient migrationClient = MigrationHubClient.builder() - .region(region) - .build(); + .region(region) + .build(); listApps(migrationClient); migrationClient.close(); @@ -41,8 +36,8 @@ public static void main(String[] args) { public static void listApps(MigrationHubClient migrationClient) { try { ListApplicationStatesRequest applicationStatesRequest = ListApplicationStatesRequest.builder() - .maxResults(10) - .build(); + .maxResults(10) + .build(); ListApplicationStatesResponse response = migrationClient.listApplicationStates(applicationStatesRequest); List apps = response.applicationStateList(); @@ -57,4 +52,4 @@ public static void listApps(MigrationHubClient migrationClient) { } } } - // snippet-end:[migration.java2.list_apps.main] +// snippet-end:[migration.java2.list_apps.main] diff --git a/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/ListCreatedArtifacts.java b/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/ListCreatedArtifacts.java index 29027fffa81..7a5067da5bd 100644 --- a/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/ListCreatedArtifacts.java +++ b/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/ListCreatedArtifacts.java @@ -1,13 +1,5 @@ -// snippet-sourcedescription:[ListCreatedArtifacts.java demonstrates how to List the created artifacts attached to a given migration task.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS Migration Hub] -// snippet-keyword:[Code Sample] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.migrationhub; @@ -23,7 +15,8 @@ // snippet-end:[migration.java2.list_artifacts.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -33,8 +26,8 @@ public class ListCreatedArtifacts { public static void main(String[] args) { Region region = Region.US_WEST_2; MigrationHubClient migrationClient = MigrationHubClient.builder() - .region(region) - .build(); + .region(region) + .build(); listArtifacts(migrationClient); migrationClient.close(); @@ -43,10 +36,10 @@ public static void main(String[] args) { public static void listArtifacts(MigrationHubClient migrationClient) { try { ListCreatedArtifactsRequest listCreatedArtifactsRequest = ListCreatedArtifactsRequest.builder() - .maxResults(10) - .migrationTaskName("SampleApp5") - .progressUpdateStream("ProgressSteamB") - .build(); + .maxResults(10) + .migrationTaskName("SampleApp5") + .progressUpdateStream("ProgressSteamB") + .build(); ListCreatedArtifactsResponse response = migrationClient.listCreatedArtifacts(listCreatedArtifactsRequest); List apps = response.createdArtifactList(); @@ -61,4 +54,4 @@ public static void listArtifacts(MigrationHubClient migrationClient) { } } } - // snippet-end:[migration.java2.list_artifacts.main] +// snippet-end:[migration.java2.list_artifacts.main] diff --git a/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/ListMigrationTasks.java b/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/ListMigrationTasks.java index 40780024e92..6351fb37e66 100644 --- a/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/ListMigrationTasks.java +++ b/javav2/example_code/migrationhub/src/main/java/com/example/migrationhub/ListMigrationTasks.java @@ -1,11 +1,5 @@ -// snippet-sourcedescription:[ListMigrationTasks.java demonstrates how to list migration tasks.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[AWS Migration Hub] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.migrationhub; @@ -21,7 +15,8 @@ // snippet-end:[migration.java2.list_migration_tasks.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,8 +26,8 @@ public class ListMigrationTasks { public static void main(String[] args) { Region region = Region.US_WEST_2; MigrationHubClient migrationClient = MigrationHubClient.builder() - .region(region) - .build(); + .region(region) + .build(); listMigrTasks(migrationClient); migrationClient.close(); @@ -41,8 +36,8 @@ public static void main(String[] args) { public static void listMigrTasks(MigrationHubClient migrationClient) { try { ListMigrationTasksRequest listMigrationTasksRequest = ListMigrationTasksRequest.builder() - .maxResults(10) - .build(); + .maxResults(10) + .build(); ListMigrationTasksResponse response = migrationClient.listMigrationTasks(listMigrationTasksRequest); List migrationList = response.migrationTaskSummaryList(); diff --git a/javav2/example_code/migrationhub/src/test/java/MigrationHubTest.java b/javav2/example_code/migrationhub/src/test/java/MigrationHubTest.java index 63d235b6ec6..596c1238122 100644 --- a/javav2/example_code/migrationhub/src/test/java/MigrationHubTest.java +++ b/javav2/example_code/migrationhub/src/test/java/MigrationHubTest.java @@ -1,14 +1,12 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.migrationhub.*; import com.google.gson.Gson; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.services.migrationhub.MigrationHubClient; import org.junit.jupiter.api.*; -import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; @@ -22,16 +20,16 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class MigrationHubTest { private static MigrationHubClient migrationClient; - private static String appId=""; - private static String migrationtask =""; - private static String progress =""; + private static String appId = ""; + private static String migrationtask = ""; + private static String progress = ""; @BeforeAll public static void setUp() { migrationClient = MigrationHubClient.builder() - .region(Region.US_WEST_2) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_WEST_2) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -41,25 +39,28 @@ public static void setUp() { migrationtask = values.getMigrationtask(); progress = values.getProgress(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - - try (InputStream input = MigrationHubTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - prop.load(input); - appId = prop.getProperty("appId"); - migrationtask = prop.getProperty("migrationtask"); - progress = prop.getProperty("progress"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * + * try (InputStream input = + * MigrationHubTest.class.getClassLoader().getResourceAsStream( + * "config.properties")) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * prop.load(input); + * appId = prop.getProperty("appId"); + * migrationtask = prop.getProperty("migrationtask"); + * progress = prop.getProperty("progress"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @@ -74,7 +75,7 @@ public void ImportMigrationTask() { @Tag("IntegrationTest") @Order(2) public void DescribeAppState() { - assertDoesNotThrow(() ->DescribeAppState.describeApplicationState(migrationClient, appId)); + assertDoesNotThrow(() -> DescribeAppState.describeApplicationState(migrationClient, appId)); System.out.println("Test 2 passed"); } @@ -82,43 +83,44 @@ public void DescribeAppState() { @Tag("IntegrationTest") @Order(3) public void DescribeMigrationTask() { - assertDoesNotThrow(() ->DescribeMigrationTask.describeMigTask(migrationClient, migrationtask, progress)); + assertDoesNotThrow(() -> DescribeMigrationTask.describeMigTask(migrationClient, migrationtask, progress)); System.out.println("Test 3 passed"); - } + } @Test @Tag("IntegrationTest") @Order(4) - public void ListApplications() { - assertDoesNotThrow(() ->ListApplications.listApps(migrationClient)); - System.out.println("Test 4 passed"); - } + public void ListApplications() { + assertDoesNotThrow(() -> ListApplications.listApps(migrationClient)); + System.out.println("Test 4 passed"); + } @Test @Tag("IntegrationTest") @Order(5) - public void ListMigrationTasks() { - assertDoesNotThrow(() ->ListMigrationTasks.listMigrTasks(migrationClient)); - System.out.println("Test 5 passed"); - } + public void ListMigrationTasks() { + assertDoesNotThrow(() -> ListMigrationTasks.listMigrTasks(migrationClient)); + System.out.println("Test 5 passed"); + } @Test @Tag("IntegrationTest") @Order(6) - public void DeleteProgressStream() { - assertDoesNotThrow(() ->DeleteProgressStream.deleteStream(migrationClient, progress)); - System.out.println("Test 6 passed"); - } + public void DeleteProgressStream() { + assertDoesNotThrow(() -> DeleteProgressStream.deleteStream(migrationClient, progress)); + System.out.println("Test 6 passed"); + } + private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/migrationhub"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -146,4 +148,3 @@ public String getProgress() { } } - diff --git a/javav2/example_code/mq/src/main/java/com/example/mq/CreateBroker.java b/javav2/example_code/mq/src/main/java/com/example/mq/CreateBroker.java index e315498e17d..79100760385 100644 --- a/javav2/example_code/mq/src/main/java/com/example/mq/CreateBroker.java +++ b/javav2/example_code/mq/src/main/java/com/example/mq/CreateBroker.java @@ -1,15 +1,5 @@ -//snippet-sourcedescription:[CreateBroker.java demonstrates how to create an Amazon MQ broker.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon MQ] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2/18/2021] -//snippet-sourceauthor:[fararmin-aws] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[mq.java2.create_broker.complete] package com.example.mq; @@ -29,14 +19,14 @@ public class CreateBroker { public static void main(String[] args) { final String USAGE = """ - Usage: CreateBrokerActiveMQ + Usage: CreateBrokerActiveMQ - Where: - engineType - Required. RABBITMQ or ACTIVEMQ for broker's engine type. - brokerName - Optional. The name of the Amazon MQ for ActiveMQ broker. + Where: + engineType - Required. RABBITMQ or ACTIVEMQ for broker's engine type. + brokerName - Optional. The name of the Amazon MQ for ActiveMQ broker. + + """; - """; - int argsLength = args.length; String brokerName = ""; String engineType = ""; @@ -44,64 +34,64 @@ public static void main(String[] args) { if (argsLength < 1 || argsLength > 2) { System.out.println(USAGE); System.exit(1); - } else { + } else { engineType = args[0]; if (argsLength == 1) { - brokerName = engineType + "-" + System.currentTimeMillis(); + brokerName = engineType + "-" + System.currentTimeMillis(); } else { brokerName = args[1]; } } Region region = Region.US_WEST_2; - MqClient mqClient = MqClient.builder() + MqClient mqClient = MqClient.builder() .region(region) .build(); - + String brokerId = createBroker(mqClient, engineType, brokerName); System.out.println("The broker ID is: " + brokerId); mqClient.close(); } + // snippet-start:[mq.java2.create_broker.main] public static String createBroker(MqClient mqClient, String engineType, String brokerName) { try { // Create an Amazon MQ User object. User user = User.builder() - .username("testAdminUser") - .password("testAdminPassword") - .consoleAccess(true) - .build(); + .username("testAdminUser") + .password("testAdminPassword") + .consoleAccess(true) + .build(); // Check the latest minor version release for the given engine type, // and use the latest version to create the broker. DescribeBrokerEngineTypesRequest engineTypeRequest = DescribeBrokerEngineTypesRequest.builder() - .engineType(engineType) - .build(); - + .engineType(engineType) + .build(); + DescribeBrokerEngineTypesResponse enginesRequest = mqClient.describeBrokerEngineTypes(engineTypeRequest); String engineVersion = enginesRequest.brokerEngineTypes().get(0) - .engineVersions().get(0) - .name(); + .engineVersions().get(0) + .name(); // Creates a new Amazon MQ broker. // Creates a new broker configuration for ActiveMQ brokers. CreateBrokerResponse result = mqClient.createBroker(CreateBrokerRequest.builder() - .brokerName(brokerName) - .engineType(engineType) - .engineVersion(engineVersion) - .deploymentMode("SINGLE_INSTANCE") - .users(user) - .publiclyAccessible(true) - .autoMinorVersionUpgrade(true) - .hostInstanceType("mq.t3.micro") - .build()); - + .brokerName(brokerName) + .engineType(engineType) + .engineVersion(engineVersion) + .deploymentMode("SINGLE_INSTANCE") + .users(user) + .publiclyAccessible(true) + .autoMinorVersionUpgrade(true) + .hostInstanceType("mq.t3.micro") + .build()); return result.brokerId(); } catch (MqException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); } return ""; } diff --git a/javav2/example_code/mq/src/main/java/com/example/mq/CreateConfiguration.java b/javav2/example_code/mq/src/main/java/com/example/mq/CreateConfiguration.java index 0376db7f2be..8eb388c6a78 100644 --- a/javav2/example_code/mq/src/main/java/com/example/mq/CreateConfiguration.java +++ b/javav2/example_code/mq/src/main/java/com/example/mq/CreateConfiguration.java @@ -1,15 +1,5 @@ -//snippet-sourcedescription:[CreateConfiguration.java demonstrates how to create an Amazon MQ configuration.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon MQ] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2/18/2021] -//snippet-sourceauthor:[fararmin-aws] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[mq.java2.create_configuration.complete] package com.example.mq; @@ -22,18 +12,17 @@ import software.amazon.awssdk.services.mq.model.MqException; // snippet-end:[mq.java2.create_configuration.import] - public class CreateConfiguration { public static void main(String[] args) { final String USAGE = """ - Usage: CreateConfiguration + Usage: CreateConfiguration - Where: - configurationName - the name of the ActiveMQ configuration. + Where: + configurationName - the name of the ActiveMQ configuration. - """; + """; String configurationName = ""; if (args.length > 1) { @@ -44,26 +33,27 @@ public static void main(String[] args) { } else { configurationName = "Configuration-" + System.currentTimeMillis(); } - + Region region = Region.US_WEST_2; - + MqClient mqClient = MqClient.builder() .region(region) .build(); - + String result = createNewConfigutation(mqClient, configurationName); System.out.println("Configuration ID: " + result); mqClient.close(); } + // snippet-start:[mq.java2.create_configuration.main] public static String createNewConfigutation(MqClient mqClient, String configurationName) { try { CreateConfigurationRequest configurationRequest = CreateConfigurationRequest.builder() - .name(configurationName) - .engineVersion("5.15.14") - .engineType("ACTIVEMQ") - .authenticationStrategy("SIMPLE") - .build(); + .name(configurationName) + .engineVersion("5.15.14") + .engineType("ACTIVEMQ") + .authenticationStrategy("SIMPLE") + .build(); CreateConfigurationResponse response = mqClient.createConfiguration(configurationRequest); return response.id(); diff --git a/javav2/example_code/mq/src/main/java/com/example/mq/DescribeBroker.java b/javav2/example_code/mq/src/main/java/com/example/mq/DescribeBroker.java index 0265aac8456..73abca71097 100644 --- a/javav2/example_code/mq/src/main/java/com/example/mq/DescribeBroker.java +++ b/javav2/example_code/mq/src/main/java/com/example/mq/DescribeBroker.java @@ -1,15 +1,5 @@ -//snippet-sourcedescription:[DescribeBroker.java demonstrates how to describe an Amazon MQ broker using the Java SDK.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon MQ] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2/18/2021] -//snippet-sourceauthor:[fararmin-aws] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[mq.java2.describe_broker.complete] @@ -27,13 +17,13 @@ public class DescribeBroker { public static void main(String[] args) { final String USAGE = """ - Usage: DescribeBroker + Usage: DescribeBroker + + Where: + brokerName - The name of the broker. - Where: - brokerName - The name of the broker. + """; - """; - String brokerName = ""; if (args.length != 1) { @@ -44,26 +34,26 @@ public static void main(String[] args) { } Region region = Region.US_WEST_2; - + MqClient mqClient = MqClient.builder() .region(region) .build(); - + String result = describeBroker(mqClient, brokerName); System.out.print("Broker ID: " + result); mqClient.close(); } + // snippet-start:[mq.java2.describe_broker.main] public static String describeBroker(MqClient mqClient, String brokerName) { try { DescribeBrokerRequest request = DescribeBrokerRequest.builder() - .brokerId(brokerName) - .build(); - + .brokerId(brokerName) + .build(); + DescribeBrokerResponse response = mqClient.describeBroker(request); System.out.print(response + "\n\n"); return response.brokerId(); - } catch (MqException e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/mq/src/main/java/com/example/mq/ListBrokers.java b/javav2/example_code/mq/src/main/java/com/example/mq/ListBrokers.java index c4206122a41..c77575da430 100644 --- a/javav2/example_code/mq/src/main/java/com/example/mq/ListBrokers.java +++ b/javav2/example_code/mq/src/main/java/com/example/mq/ListBrokers.java @@ -1,15 +1,5 @@ -//snippet-sourcedescription:[ListBrokers.java demonstrates how to list existing Amazon MQ brokers.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon MQ] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2/18/2021] -//snippet-sourceauthor:[fararmin-aws] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[mq.java2.list_brokers.complete] package com.example.mq; @@ -28,18 +18,19 @@ public class ListBrokers { public static void main(String[] args) { Region region = Region.US_WEST_2; - MqClient mqClient = MqClient.builder() + MqClient mqClient = MqClient.builder() .region(region) .build(); List results = listBrokers(mqClient); for (BrokerSummary result : results) { System.out.print("Name: " + result.brokerName() + " | " + - "ID: " + result.brokerId() + " | " + result.brokerState() + "\n"); + "ID: " + result.brokerId() + " | " + result.brokerState() + "\n"); } - + mqClient.close(); } + // snippet-start:[mq.java2.list_brokers.main] public static List listBrokers(MqClient mqClient) { List brokerList = new ArrayList<>(); diff --git a/javav2/example_code/mq/src/main/java/com/example/mq/ListConfigurations.java b/javav2/example_code/mq/src/main/java/com/example/mq/ListConfigurations.java index 5e0a1ee7774..0c838aca204 100644 --- a/javav2/example_code/mq/src/main/java/com/example/mq/ListConfigurations.java +++ b/javav2/example_code/mq/src/main/java/com/example/mq/ListConfigurations.java @@ -1,15 +1,5 @@ -//snippet-sourcedescription:[ListConfigurations.java demonstrates how to list existing Amazon MQ configurations.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon MQ] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2/18/2021] -//snippet-sourceauthor:[fararmin-aws] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[mq.java2.list_configurations.complete] package com.example.mq; @@ -26,21 +16,22 @@ public class ListConfigurations { public static void main(String[] args) { Region region = Region.US_WEST_2; - MqClient mqClient = MqClient.builder() + MqClient mqClient = MqClient.builder() .region(region) .build(); - + // Applies only to Amazon MQ for ActiveMQ brokers. List results = listConfigurations(mqClient); for (Configuration result : results) { System.out.println("Name: " + result.name() + " | " + - "ID: " + result.id() + "\n"); + "ID: " + result.id() + "\n"); } mqClient.close(); } + // snippet-start:[mq.java2.list_configurations.main] public static List listConfigurations(MqClient mqClient) { diff --git a/javav2/example_code/mq/src/main/java/com/example/mq/UpdateBrokerConfiguration.java b/javav2/example_code/mq/src/main/java/com/example/mq/UpdateBrokerConfiguration.java index a20d8506a4f..79a8572c6a4 100644 --- a/javav2/example_code/mq/src/main/java/com/example/mq/UpdateBrokerConfiguration.java +++ b/javav2/example_code/mq/src/main/java/com/example/mq/UpdateBrokerConfiguration.java @@ -1,15 +1,5 @@ -//snippet-sourcedescription:[UpdateBrokerConfigurations.java demonstrates how to associate a new configuration with a specified broker.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon MQ] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[2/18/2021] -//snippet-sourceauthor:[fararmin-aws] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[mq.java2.update_broker_configuration.complete] package com.example.mq; @@ -27,15 +17,15 @@ public class UpdateBrokerConfiguration { public static void main(String[] args) { final String USAGE = """ - Usage: CreateConfiguration + Usage: CreateConfiguration - Where: - brokerId - The ID of the broker being updated - configurationId - The ID of the configuration being associate with a broker. + Where: + brokerId - The ID of the broker being updated + configurationId - The ID of the configuration being associate with a broker. - Tip: You can use ListBrokers and ListConfigurations to display a list of your brokers and configurations. + Tip: You can use ListBrokers and ListConfigurations to display a list of your brokers and configurations. - """; + """; int argsLength = args.length; String brokerId = ""; @@ -50,33 +40,34 @@ public static void main(String[] args) { } Region region = Region.US_WEST_2; - + MqClient mqClient = MqClient.builder() .region(region) .build(); - + // Applies only to Amazon MQ for ActiveMQ brokers. String result = updateBrokerConfiguration(mqClient, brokerId, configurationId); System.out.println(result); mqClient.close(); } + // snippet-start:[mq.java2.update_broker_configuration.main] public static String updateBrokerConfiguration(MqClient mqClient, String brokerId, String configurationId) { try { ConfigurationId configuration = ConfigurationId.builder() - .id(configurationId) - .build(); + .id(configurationId) + .build(); UpdateBrokerRequest request = UpdateBrokerRequest.builder() - //brokerId is the ID of an existing broker where the change is to be applied. - .brokerId(brokerId) - // configuration is an existing XML broker configuration that will be associated - // with the specified broker. - .configuration(configuration) - .build(); - + // brokerId is the ID of an existing broker where the change is to be applied. + .brokerId(brokerId) + // configuration is an existing XML broker configuration that will be associated + // with the specified broker. + .configuration(configuration) + .build(); + UpdateBrokerResponse response = mqClient.updateBroker(request); - + return response.brokerId(); } catch (MqException e) { diff --git a/javav2/example_code/mq/src/test/java/AmazonMQTest.java b/javav2/example_code/mq/src/test/java/AmazonMQTest.java index 4541de8e5ed..60f51da13b7 100644 --- a/javav2/example_code/mq/src/test/java/AmazonMQTest.java +++ b/javav2/example_code/mq/src/test/java/AmazonMQTest.java @@ -1,7 +1,6 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + import com.example.mq.*; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.mq.MqClient; @@ -18,7 +17,7 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AmazonMQTest { - private static MqClient mqClient ; + private static MqClient mqClient; private static Region region; private static String engineType = ""; private static String brokerName = ""; @@ -43,7 +42,7 @@ public static void setUp() throws IOException { return; } - //load a properties file from class path, inside static method + // load a properties file from class path, inside static method prop.load(input); // Populate the data members required for all tests diff --git a/javav2/example_code/opensearch/src/main/java/com/example/search/CreateDomain.java b/javav2/example_code/opensearch/src/main/java/com/example/search/CreateDomain.java index abd1dc4464c..1f7bef3dc62 100644 --- a/javav2/example_code/opensearch/src/main/java/com/example/search/CreateDomain.java +++ b/javav2/example_code/opensearch/src/main/java/com/example/search/CreateDomain.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[CreateDomain.java demonstrates how to create a new Amazon OpenSearch Service domain.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon OpenSearch Service] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.search; // snippet-start:[opensearch.java2.create_domain.main] @@ -22,7 +17,8 @@ // snippet-end:[opensearch.java2.create_domain.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,12 +28,12 @@ public class CreateDomain { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - domainName - The name of the domain to create. - """; + Where: + domainName - The name of the domain to create. + """; if (args.length != 1) { System.out.println(usage); @@ -47,8 +43,8 @@ public static void main(String[] args) { String domainName = args[0]; Region region = Region.US_EAST_1; OpenSearchClient searchClient = OpenSearchClient.builder() - .region(region) - .build(); + .region(region) + .build(); createNewDomain(searchClient, domainName); System.out.println("Done"); @@ -57,30 +53,30 @@ public static void main(String[] args) { public static void createNewDomain(OpenSearchClient searchClient, String domainName) { try { ClusterConfig clusterConfig = ClusterConfig.builder() - .dedicatedMasterEnabled(true) - .dedicatedMasterCount(3) - .dedicatedMasterType("t2.small.search") - .instanceType("t2.small.search") - .instanceCount(5) - .build(); + .dedicatedMasterEnabled(true) + .dedicatedMasterCount(3) + .dedicatedMasterType("t2.small.search") + .instanceType("t2.small.search") + .instanceCount(5) + .build(); EBSOptions ebsOptions = EBSOptions.builder() - .ebsEnabled(true) - .volumeSize(10) - .volumeType(VolumeType.GP2) - .build(); + .ebsEnabled(true) + .volumeSize(10) + .volumeType(VolumeType.GP2) + .build(); NodeToNodeEncryptionOptions encryptionOptions = NodeToNodeEncryptionOptions.builder() - .enabled(true) - .build(); + .enabled(true) + .build(); CreateDomainRequest domainRequest = CreateDomainRequest.builder() - .domainName(domainName) - .engineVersion("OpenSearch_1.0") - .clusterConfig(clusterConfig) - .ebsOptions(ebsOptions) - .nodeToNodeEncryptionOptions(encryptionOptions) - .build(); + .domainName(domainName) + .engineVersion("OpenSearch_1.0") + .clusterConfig(clusterConfig) + .ebsOptions(ebsOptions) + .nodeToNodeEncryptionOptions(encryptionOptions) + .build(); System.out.println("Sending domain creation request..."); CreateDomainResponse createResponse = searchClient.createDomain(domainRequest); diff --git a/javav2/example_code/opensearch/src/main/java/com/example/search/DeleteDomain.java b/javav2/example_code/opensearch/src/main/java/com/example/search/DeleteDomain.java index 5c675f5f7fc..8e880175070 100644 --- a/javav2/example_code/opensearch/src/main/java/com/example/search/DeleteDomain.java +++ b/javav2/example_code/opensearch/src/main/java/com/example/search/DeleteDomain.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DeleteDomain.java demonstrates how to delete an Amazon OpenSearch Service domain.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon OpenSearch Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.search; @@ -18,7 +12,8 @@ // snippet-end:[opensearch.java2.delete_domain.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +23,12 @@ public class DeleteDomain { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - domainName - The name of the domain to delete. - """; + Where: + domainName - The name of the domain to delete. + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +38,8 @@ public static void main(String[] args) { String domainName = args[0]; Region region = Region.US_EAST_1; OpenSearchClient searchClient = OpenSearchClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteSpecificDomain(searchClient, domainName); System.out.println("Done"); @@ -53,8 +48,8 @@ public static void main(String[] args) { public static void deleteSpecificDomain(OpenSearchClient searchClient, String domainName) { try { DeleteDomainRequest domainRequest = DeleteDomainRequest.builder() - .domainName(domainName) - .build(); + .domainName(domainName) + .build(); searchClient.deleteDomain(domainRequest); System.out.println(domainName + " was successfully deleted."); diff --git a/javav2/example_code/opensearch/src/main/java/com/example/search/ListDomainNames.java b/javav2/example_code/opensearch/src/main/java/com/example/search/ListDomainNames.java index 4bd4910e99c..14eb6a93e6b 100644 --- a/javav2/example_code/opensearch/src/main/java/com/example/search/ListDomainNames.java +++ b/javav2/example_code/opensearch/src/main/java/com/example/search/ListDomainNames.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[ListDomainNames.java demonstrates how to list Amazon OpenSearch Service domains.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.search; // snippet-start:[opensearch.java2.list_domains.main] @@ -22,7 +17,8 @@ import java.util.List; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,9 +28,9 @@ public class ListDomainNames { public static void main(String[] args) { Region region = Region.US_EAST_1; OpenSearchClient searchClient = OpenSearchClient.builder() - .region(region) - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(ProfileCredentialsProvider.create()) + .build(); listAllDomains(searchClient); System.out.println("Done"); } @@ -42,8 +38,8 @@ public static void main(String[] args) { public static void listAllDomains(OpenSearchClient searchClient) { try { ListDomainNamesRequest namesRequest = ListDomainNamesRequest.builder() - .engineType("OpenSearch") - .build(); + .engineType("OpenSearch") + .build(); ListDomainNamesResponse response = searchClient.listDomainNames(namesRequest); List domainInfoList = response.domainNames(); diff --git a/javav2/example_code/opensearch/src/main/java/com/example/search/UpdateDomain.java b/javav2/example_code/opensearch/src/main/java/com/example/search/UpdateDomain.java index 13e9e554556..6ad4437f04f 100644 --- a/javav2/example_code/opensearch/src/main/java/com/example/search/UpdateDomain.java +++ b/javav2/example_code/opensearch/src/main/java/com/example/search/UpdateDomain.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[UpdateDomain.java demonstrates how modify a cluster configuration of the specified domain.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon OpenSearch Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.search; @@ -20,7 +14,8 @@ // snippet-end:[opensearch.java2.update_domain.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,13 +25,13 @@ public class UpdateDomain { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - domainName - The name of the domain to update. + Where: + domainName - The name of the domain to update. - """; + """; if (args.length != 1) { System.out.println(usage); @@ -46,8 +41,8 @@ public static void main(String[] args) { String domainName = args[0]; Region region = Region.US_EAST_1; OpenSearchClient searchClient = OpenSearchClient.builder() - .region(region) - .build(); + .region(region) + .build(); updateSpecificDomain(searchClient, domainName); System.out.println("Done"); @@ -56,13 +51,13 @@ public static void main(String[] args) { public static void updateSpecificDomain(OpenSearchClient searchClient, String domainName) { try { ClusterConfig clusterConfig = ClusterConfig.builder() - .instanceCount(3) - .build(); + .instanceCount(3) + .build(); UpdateDomainConfigRequest updateDomainConfigRequest = UpdateDomainConfigRequest.builder() - .domainName(domainName) - .clusterConfig(clusterConfig) - .build(); + .domainName(domainName) + .clusterConfig(clusterConfig) + .build(); System.out.println("Sending domain update request..."); UpdateDomainConfigResponse updateResponse = searchClient.updateDomainConfig(updateDomainConfigRequest); diff --git a/javav2/example_code/opensearch/src/test/java/OpenSearchTest.java b/javav2/example_code/opensearch/src/test/java/OpenSearchTest.java index c3a723a09f7..d8b999aadff 100644 --- a/javav2/example_code/opensearch/src/test/java/OpenSearchTest.java +++ b/javav2/example_code/opensearch/src/test/java/OpenSearchTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import org.junit.jupiter.api.*; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; @@ -16,14 +14,14 @@ public class OpenSearchTest { private static OpenSearchClient searchClient; - private static String domainName=""; + private static String domainName = ""; @BeforeAll public static void setUp() throws IOException { searchClient = OpenSearchClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); try (InputStream input = OpenSearchTest.class.getClassLoader().getResourceAsStream("config.properties")) { Properties prop = new Properties(); @@ -34,7 +32,7 @@ public static void setUp() throws IOException { // Populate the data members required for all tests prop.load(input); - domainName ="testdomain"; + domainName = "testdomain"; } catch (IOException ex) { ex.printStackTrace(); @@ -45,11 +43,10 @@ public static void setUp() throws IOException { @Tag("IntegrationTest") @Order(1) public void createDomainTest() { - CreateDomain. createNewDomain(searchClient, domainName); + CreateDomain.createNewDomain(searchClient, domainName); System.out.println("Test 1 passed"); } - @Test @Tag("IntegrationTest") @Order(2) diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateBatchInferenceJob.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateBatchInferenceJob.java index eeb9009808b..3d97fc54d34 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateBatchInferenceJob.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateBatchInferenceJob.java @@ -1,25 +1,19 @@ -//snippet-sourcedescription:[CreateBatchInferenceJob.java demonstrates how to create -// an Amazon Personalize batch inference job.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Personalize] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.create_batch_inference_job.import] +// snippet-start:[personalize.java2.create_batch_inference_job.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; import software.amazon.awssdk.services.personalize.model.*; import java.time.Instant; import java.util.HashMap; -//snippet-end:[personalize.java2.create_batch_inference_job.import] +// snippet-end:[personalize.java2.create_batch_inference_job.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. *

    * For information, see this documentation topic: *

    @@ -28,136 +22,140 @@ public class CreateBatchInferenceJob { - public static void main(String[] args) { + public static void main(String[] args) { - final String USAGE = """ + final String USAGE = """ - Usage: - CreateDatasetImportJob + Usage: + CreateDatasetImportJob - Where: - solutionVersionArn - The Amazon Resource Name (ARN) of the solution version you want to use. - jobName - The name for the batch inference job. - s3InputDataSource - The path to the Amazon S3 bucket where your input list of users or items is stored. - s3DataDestination - The path to the Amazon S3 bucket where Amazon Personalize will output the batch recommendations. - roleArn - The ARN of the IAM service-linked role thathas permissions to add data to your output Amazon S3 bucket. - explorationWeight - A User-Personalization recipe specific field that specifies how much to explore (how often to include new items in recommendations) - explorationItemAgeCutOff - A User-Personalization recipe specific field that defines what Amazon Personalize considers a new item in exploration. + Where: + solutionVersionArn - The Amazon Resource Name (ARN) of the solution version you want to use. + jobName - The name for the batch inference job. + s3InputDataSource - The path to the Amazon S3 bucket where your input list of users or items is stored. + s3DataDestination - The path to the Amazon S3 bucket where Amazon Personalize will output the batch recommendations. + roleArn - The ARN of the IAM service-linked role thathas permissions to add data to your output Amazon S3 bucket. + explorationWeight - A User-Personalization recipe specific field that specifies how much to explore (how often to include new items in recommendations) + explorationItemAgeCutOff - A User-Personalization recipe specific field that defines what Amazon Personalize considers a new item in exploration. - """; + """; - // If omitting User-Personalization exploration fields, change from 7 to 5. - if (args.length != 7) { - System.out.println(USAGE); - System.exit(1); - } - String solutionVersionArn = args[0]; - String jobName = args[1]; - String s3InputDataSource = args[2]; - String s3DataDestination = args[3]; - String roleArn = args[4]; - String explorationWeight = args[5]; - String explorationItemAgeCutOff = args[6]; - - // Change to the region where your Amazon Personalize resources are located - Region region = Region.US_WEST_2; - PersonalizeClient personalizeClient = PersonalizeClient.builder() - .region(region) - .build(); - - String batchInferenceJobArn = createPersonalizeBatchInferenceJob(personalizeClient, solutionVersionArn, - jobName, s3InputDataSource, s3DataDestination, roleArn, explorationWeight, explorationItemAgeCutOff); - System.out.println("Batch inference job ARN: " + batchInferenceJobArn); - personalizeClient.close(); - } - - //snippet-start:[personalize.java2.create_batch_inference_job.main] - public static String createPersonalizeBatchInferenceJob(PersonalizeClient personalizeClient, - String solutionVersionArn, - String jobName, - String s3InputDataSourcePath, - String s3DataDestinationPath, - String roleArn, - String explorationWeight, - String explorationItemAgeCutOff) { - - long waitInMilliseconds = 60 * 1000; - String status; - String batchInferenceJobArn; - - try { - - // Set up data input and output parameters. - S3DataConfig inputSource = S3DataConfig.builder() - .path(s3InputDataSourcePath) - .build(); - - S3DataConfig outputDestination = S3DataConfig.builder() - .path(s3DataDestinationPath) - .build(); - - BatchInferenceJobInput jobInput = BatchInferenceJobInput.builder() - .s3DataSource(inputSource) - .build(); - - BatchInferenceJobOutput jobOutputLocation = BatchInferenceJobOutput.builder() - .s3DataDestination(outputDestination) - .build(); - - // Optional code to build the User-Personalization specific item exploration config. - HashMap explorationConfig = new HashMap<>(); - - explorationConfig.put("explorationWeight", explorationWeight); - explorationConfig.put("explorationItemAgeCutOff", explorationItemAgeCutOff); - - BatchInferenceJobConfig jobConfig = BatchInferenceJobConfig.builder() - .itemExplorationConfig(explorationConfig) - .build(); - - // End optional User-Personalization recipe specific code. - - CreateBatchInferenceJobRequest createBatchInferenceJobRequest = CreateBatchInferenceJobRequest.builder() - .solutionVersionArn(solutionVersionArn) - .jobInput(jobInput) - .jobOutput(jobOutputLocation) - .jobName(jobName) - .roleArn(roleArn) - .batchInferenceJobConfig(jobConfig) // Optional - .build(); - - batchInferenceJobArn = personalizeClient.createBatchInferenceJob(createBatchInferenceJobRequest) - .batchInferenceJobArn(); - - DescribeBatchInferenceJobRequest describeBatchInferenceJobRequest = DescribeBatchInferenceJobRequest.builder() - .batchInferenceJobArn(batchInferenceJobArn) - .build(); - - long maxTime = Instant.now().getEpochSecond() + 3 * 60 * 60; - while (Instant.now().getEpochSecond() < maxTime) { - - BatchInferenceJob batchInferenceJob = personalizeClient - .describeBatchInferenceJob(describeBatchInferenceJobRequest) - .batchInferenceJob(); - - status = batchInferenceJob.status(); - System.out.println("Batch inference job status: " + status); - - if (status.equals("ACTIVE") || status.equals("CREATE FAILED")) { - break; + // If omitting User-Personalization exploration fields, change from 7 to 5. + if (args.length != 7) { + System.out.println(USAGE); + System.exit(1); } + String solutionVersionArn = args[0]; + String jobName = args[1]; + String s3InputDataSource = args[2]; + String s3DataDestination = args[3]; + String roleArn = args[4]; + String explorationWeight = args[5]; + String explorationItemAgeCutOff = args[6]; + + // Change to the region where your Amazon Personalize resources are located + Region region = Region.US_WEST_2; + PersonalizeClient personalizeClient = PersonalizeClient.builder() + .region(region) + .build(); + + String batchInferenceJobArn = createPersonalizeBatchInferenceJob(personalizeClient, solutionVersionArn, + jobName, s3InputDataSource, s3DataDestination, roleArn, explorationWeight, + explorationItemAgeCutOff); + System.out.println("Batch inference job ARN: " + batchInferenceJobArn); + personalizeClient.close(); + } + + // snippet-start:[personalize.java2.create_batch_inference_job.main] + public static String createPersonalizeBatchInferenceJob(PersonalizeClient personalizeClient, + String solutionVersionArn, + String jobName, + String s3InputDataSourcePath, + String s3DataDestinationPath, + String roleArn, + String explorationWeight, + String explorationItemAgeCutOff) { + + long waitInMilliseconds = 60 * 1000; + String status; + String batchInferenceJobArn; + try { - Thread.sleep(waitInMilliseconds); - } catch (InterruptedException e) { - System.out.println(e.getMessage()); - } - } - return batchInferenceJobArn; - } catch (PersonalizeException e) { - System.out.println(e.awsErrorDetails().errorMessage()); + // Set up data input and output parameters. + S3DataConfig inputSource = S3DataConfig.builder() + .path(s3InputDataSourcePath) + .build(); + + S3DataConfig outputDestination = S3DataConfig.builder() + .path(s3DataDestinationPath) + .build(); + + BatchInferenceJobInput jobInput = BatchInferenceJobInput.builder() + .s3DataSource(inputSource) + .build(); + + BatchInferenceJobOutput jobOutputLocation = BatchInferenceJobOutput.builder() + .s3DataDestination(outputDestination) + .build(); + + // Optional code to build the User-Personalization specific item exploration + // config. + HashMap explorationConfig = new HashMap<>(); + + explorationConfig.put("explorationWeight", explorationWeight); + explorationConfig.put("explorationItemAgeCutOff", explorationItemAgeCutOff); + + BatchInferenceJobConfig jobConfig = BatchInferenceJobConfig.builder() + .itemExplorationConfig(explorationConfig) + .build(); + + // End optional User-Personalization recipe specific code. + + CreateBatchInferenceJobRequest createBatchInferenceJobRequest = CreateBatchInferenceJobRequest + .builder() + .solutionVersionArn(solutionVersionArn) + .jobInput(jobInput) + .jobOutput(jobOutputLocation) + .jobName(jobName) + .roleArn(roleArn) + .batchInferenceJobConfig(jobConfig) // Optional + .build(); + + batchInferenceJobArn = personalizeClient.createBatchInferenceJob(createBatchInferenceJobRequest) + .batchInferenceJobArn(); + + DescribeBatchInferenceJobRequest describeBatchInferenceJobRequest = DescribeBatchInferenceJobRequest + .builder() + .batchInferenceJobArn(batchInferenceJobArn) + .build(); + + long maxTime = Instant.now().getEpochSecond() + 3 * 60 * 60; + while (Instant.now().getEpochSecond() < maxTime) { + + BatchInferenceJob batchInferenceJob = personalizeClient + .describeBatchInferenceJob(describeBatchInferenceJobRequest) + .batchInferenceJob(); + + status = batchInferenceJob.status(); + System.out.println("Batch inference job status: " + status); + + if (status.equals("ACTIVE") || status.equals("CREATE FAILED")) { + break; + } + try { + Thread.sleep(waitInMilliseconds); + } catch (InterruptedException e) { + System.out.println(e.getMessage()); + } + } + return batchInferenceJobArn; + + } catch (PersonalizeException e) { + System.out.println(e.awsErrorDetails().errorMessage()); + } + return ""; } - return ""; - } - //snippet-end:[personalize.java2.create_batch_inference_job.main] + // snippet-end:[personalize.java2.create_batch_inference_job.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateCampaign.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateCampaign.java index f26a29bcf78..0669073c393 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateCampaign.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateCampaign.java @@ -1,24 +1,19 @@ -//snippet-sourcedescription:[CreateCampaign.java demonstrates how to create an Amazon Personalize campaign.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Personalize] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.create_campaign.import] +// snippet-start:[personalize.java2.create_campaign.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; import software.amazon.awssdk.services.personalize.model.CreateCampaignRequest; import software.amazon.awssdk.services.personalize.model.CreateCampaignResponse; import software.amazon.awssdk.services.personalize.model.PersonalizeException; -//snippet-end:[personalize.java2.create_campaign.import] +// snippet-end:[personalize.java2.create_campaign.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -30,15 +25,15 @@ public static void main(String[] args) { final String USAGE = """ - Usage: - + Usage: + - Where: - solutionVersionArn - The ARN of the solution version. + Where: + solutionVersionArn - The ARN of the solution version. - name - The name of the Amazon Personalization campaign. + name - The name of the Amazon Personalization campaign. - """; + """; if (args.length != 2) { System.out.println(USAGE); @@ -49,30 +44,31 @@ public static void main(String[] args) { String name = args[1]; Region region = Region.US_EAST_1; PersonalizeClient personalizeClient = PersonalizeClient.builder() - .region(region) - .build(); + .region(region) + .build(); createPersonalCompaign(personalizeClient, solutionVersionArn, name); personalizeClient.close(); } - //snippet-start:[personalize.java2.create_campaign.main] - public static void createPersonalCompaign(PersonalizeClient personalizeClient, String solutionVersionArn, String name) { + // snippet-start:[personalize.java2.create_campaign.main] + public static void createPersonalCompaign(PersonalizeClient personalizeClient, String solutionVersionArn, + String name) { try { CreateCampaignRequest createCampaignRequest = CreateCampaignRequest.builder() - .minProvisionedTPS(1) - .solutionVersionArn(solutionVersionArn) - .name(name) - .build(); + .minProvisionedTPS(1) + .solutionVersionArn(solutionVersionArn) + .name(name) + .build(); CreateCampaignResponse campaignResponse = personalizeClient.createCampaign(createCampaignRequest); - System.out.println("The campaign ARN is "+campaignResponse.campaignArn()); + System.out.println("The campaign ARN is " + campaignResponse.campaignArn()); } catch (PersonalizeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } - //snippet-end:[personalize.java2.create_campaign.main] + // snippet-end:[personalize.java2.create_campaign.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDataset.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDataset.java index 6c1d9e14365..a75b2b5f974 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDataset.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDataset.java @@ -1,35 +1,29 @@ -//snippet-sourcedescription:[CreateDataset.java demonstrates how to create an Amazon Personalize dataset.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Personalize] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.create_dataset.import] +// snippet-start:[personalize.java2.create_dataset.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.model.CreateDatasetRequest; import software.amazon.awssdk.services.personalize.PersonalizeClient; import software.amazon.awssdk.services.personalize.model.PersonalizeException; -//snippet-end:[personalize.java2.create_dataset.import] +// snippet-end:[personalize.java2.create_dataset.import] public class CreateDataset { public static void main(String[] args) { final String USAGE = """ - Usage: - + Usage: + - Where: - datasetName - The name for the dataset. - datasetGroupArn - The Amazon Resource Name (ARN) for the dataset group. - datasetType- The type of dataset (INTERACTIONS, USERS, or ITEMS). - schemaArn - The ARN for the dataset's schema. + Where: + datasetName - The name for the dataset. + datasetGroupArn - The Amazon Resource Name (ARN) for the dataset group. + datasetType- The type of dataset (INTERACTIONS, USERS, or ITEMS). + schemaArn - The ARN for the dataset's schema. - """; + """; if (args.length != 4) { System.out.println(USAGE); @@ -44,30 +38,30 @@ public static void main(String[] args) { // Change to the region where your resources are located Region region = Region.US_WEST_2; PersonalizeClient personalizeClient = PersonalizeClient.builder() - .region(region) - .build(); + .region(region) + .build(); String datasetArn = createDataset(personalizeClient, datasetName, datasetGroupArn, datasetType, schemaArn); System.out.println("Dataset ARN: " + datasetArn); personalizeClient.close(); } - //snippet-start:[personalize.java2.create_dataset.main] + // snippet-start:[personalize.java2.create_dataset.main] public static String createDataset(PersonalizeClient personalizeClient, - String datasetName, - String datasetGroupArn, - String datasetType, - String schemaArn) { + String datasetName, + String datasetGroupArn, + String datasetType, + String schemaArn) { try { CreateDatasetRequest request = CreateDatasetRequest.builder() - .name(datasetName) - .datasetGroupArn(datasetGroupArn) - .datasetType(datasetType) - .schemaArn(schemaArn) - .build(); + .name(datasetName) + .datasetGroupArn(datasetGroupArn) + .datasetType(datasetType) + .schemaArn(schemaArn) + .build(); String datasetArn = personalizeClient.createDataset(request) - .datasetArn(); + .datasetArn(); System.out.println("Dataset " + datasetName + " created."); return datasetArn; @@ -77,5 +71,5 @@ public static String createDataset(PersonalizeClient personalizeClient, } return ""; } - //snippet-end:[personalize.java2.create_dataset.main] + // snippet-end:[personalize.java2.create_dataset.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDatasetExportJob.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDatasetExportJob.java index 9d7d3ea5261..8c73d4ecfcd 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDatasetExportJob.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDatasetExportJob.java @@ -1,20 +1,9 @@ -//snippet-sourcedescription:[CreateDatasetExportJob.java demonstrates how to create -// an Amazon Personalize dataset export job that exports data from a dataset to an Amazon S3 bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon Personalize] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[7/13/2021] -//snippet-sourceauthor:[seashman - AWS] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.create_dataset_export_job.import] +// snippet-start:[personalize.java2.create_dataset_export_job.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; @@ -28,26 +17,26 @@ import java.time.Instant; -//snippet-end:[personalize.java2.create_dataset_export_job.import] +// snippet-end:[personalize.java2.create_dataset_export_job.import] public class CreateDatasetExportJob { - public static void main(String [] args) { + public static void main(String[] args) { final String USAGE = """ - Usage: - CreateDatasetExportJob + Usage: + CreateDatasetExportJob - Where: - jobName - The name for the dataset export job. - datasetArn - The Amazon Resource Name (ARN) of the dataset that contains the data to export. - ingestionMode - The data to export, based on how you imported the data. - roleArn - The Amazon Resource Name (ARN) of the IAM service role thathas permissions to add data to your output Amazon S3 bucket. - s3BucketPath - The path to your output bucket - kmsKeyArn - The ARN for your KMS key + Where: + jobName - The name for the dataset export job. + datasetArn - The Amazon Resource Name (ARN) of the dataset that contains the data to export. + ingestionMode - The data to export, based on how you imported the data. + roleArn - The Amazon Resource Name (ARN) of the IAM service role thathas permissions to add data to your output Amazon S3 bucket. + s3BucketPath - The path to your output bucket + kmsKeyArn - The ARN for your KMS key + + """; - """; - if (args.length != 6) { System.out.println(USAGE); System.exit(1); @@ -56,18 +45,16 @@ public static void main(String [] args) { IngestionMode ingestionMode = IngestionMode.ALL; String jobName = args[0]; String datasetArn = args[1]; - + if (args[2].toLowerCase().equals("put")) { ingestionMode = IngestionMode.PUT; - } - else if (args[2].toLowerCase().equals("bulk")) { + } else if (args[2].toLowerCase().equals("bulk")) { ingestionMode = IngestionMode.BULK; } String roleArn = args[3]; String s3BucketPath = args[4]; String kmsKeyArn = args[5]; - Region region = Region.US_WEST_2; PersonalizeClient personalizeClient = PersonalizeClient.builder() .region(region) @@ -75,22 +62,24 @@ else if (args[2].toLowerCase().equals("bulk")) { createDatasetExportJob(personalizeClient, jobName, datasetArn, ingestionMode, roleArn, s3BucketPath, kmsKeyArn); personalizeClient.close(); } - //snippet-start:[personalize.java2.create_dataset_export_job.main] + + // snippet-start:[personalize.java2.create_dataset_export_job.main] public static String createDatasetExportJob(PersonalizeClient personalizeClient, - String jobName, - String datasetArn, - IngestionMode ingestionMode, - String roleArn, - String s3BucketPath, - String kmsKeyArn) { - + String jobName, + String datasetArn, + IngestionMode ingestionMode, + String roleArn, + String s3BucketPath, + String kmsKeyArn) { + long waitInMilliseconds = 30 * 1000; // 30 seconds String status = null; try { S3DataConfig exportS3DataConfig = S3DataConfig.builder().path(s3BucketPath).kmsKeyArn(kmsKeyArn).build(); - DatasetExportJobOutput jobOutput = DatasetExportJobOutput.builder().s3DataDestination(exportS3DataConfig).build(); + DatasetExportJobOutput jobOutput = DatasetExportJobOutput.builder().s3DataDestination(exportS3DataConfig) + .build(); CreateDatasetExportJobRequest createRequest = CreateDatasetExportJobRequest.builder() .jobName(jobName) @@ -101,23 +90,24 @@ public static String createDatasetExportJob(PersonalizeClient personalizeClient, .build(); String datasetExportJobArn = personalizeClient.createDatasetExportJob(createRequest).datasetExportJobArn(); - + DescribeDatasetExportJobRequest describeDatasetExportJobRequest = DescribeDatasetExportJobRequest.builder() - .datasetExportJobArn(datasetExportJobArn) - .build(); + .datasetExportJobArn(datasetExportJobArn) + .build(); long maxTime = Instant.now().getEpochSecond() + 3 * 60 * 60; while (Instant.now().getEpochSecond() < maxTime) { - DatasetExportJob datasetExportJob = personalizeClient.describeDatasetExportJob(describeDatasetExportJobRequest) + DatasetExportJob datasetExportJob = personalizeClient + .describeDatasetExportJob(describeDatasetExportJobRequest) .datasetExportJob(); status = datasetExportJob.status(); System.out.println("Export job status: " + status); - + if (status.equals("ACTIVE") || status.equals("CREATE FAILED")) { - return status; + return status; } try { Thread.sleep(waitInMilliseconds); @@ -130,5 +120,5 @@ public static String createDatasetExportJob(PersonalizeClient personalizeClient, } return ""; } - //snippet-end:[personalize.java2.create_dataset_export_job.main] + // snippet-end:[personalize.java2.create_dataset_export_job.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDatasetGroup.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDatasetGroup.java index 92dba5969f6..76f777d4807 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDatasetGroup.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDatasetGroup.java @@ -1,19 +1,9 @@ -//snippet-sourcedescription:[CreateDatasetGroup.java demonstrates how to create an Amazon Personalize dataset group.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon Personalize] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[5/11/2021] -//snippet-sourceauthor:[seashman - AWS] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.create_dataset_group.import] +// snippet-start:[personalize.java2.create_dataset_group.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; @@ -22,20 +12,20 @@ import software.amazon.awssdk.services.personalize.model.DescribeDatasetGroupRequest; import java.time.Instant; -//snippet-end:[personalize.java2.create_dataset_group.import] +// snippet-end:[personalize.java2.create_dataset_group.import] public class CreateDatasetGroup { public static void main(String[] args) { final String USAGE = """ - Usage: - CreateDatasetGroup + Usage: + CreateDatasetGroup - Where: - name - The name for the new dataset group. + Where: + name - The name for the new dataset group. - """; + """; if (args.length != 1) { System.out.println(USAGE); @@ -56,7 +46,7 @@ public static void main(String[] args) { personalizeClient.close(); } - //snippet-start:[personalize.java2.create_dataset_group.main] + // snippet-start:[personalize.java2.create_dataset_group.main] public static String createDatasetGroup(PersonalizeClient personalizeClient, String datasetGroupName) { try { @@ -69,6 +59,6 @@ public static String createDatasetGroup(PersonalizeClient personalizeClient, Str } return ""; } - //snippet-end:[personalize.java2.create_dataset_group.main] + // snippet-end:[personalize.java2.create_dataset_group.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDatasetImportJob.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDatasetImportJob.java index 4ec3db9b176..0dd648faebf 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDatasetImportJob.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDatasetImportJob.java @@ -1,20 +1,9 @@ -//snippet-sourcedescription:[CreateDatasetImportJob.java demonstrates how to create an -// Amazon Personalize dataset import job that imports data into an Amazon Personalize dataset.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon Personalize] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[5/11/2021] -//snippet-sourceauthor:[seashman - AWS] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.create_dataset_import_job.import] +// snippet-start:[personalize.java2.create_dataset_import_job.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; @@ -25,7 +14,7 @@ import software.amazon.awssdk.services.personalize.model.DescribeDatasetImportJobRequest; import java.time.Instant; -//snippet-end:[personalize.java2.create_dataset_import_job.import] +// snippet-end:[personalize.java2.create_dataset_import_job.import] public class CreateDatasetImportJob { @@ -33,16 +22,16 @@ public static void main(String[] args) { final String USAGE = """ - Usage: - CreateDatasetImportJob + Usage: + CreateDatasetImportJob - Where: - datasetArn - The Amazon Resource Name (ARN) of the destination dataset. - s3BucketPath - The path to the Amazon S3 bucket where the data that you want to upload to your dataset is stored. - jobName - The name for the dataset import job. - roleArn - The ARN of the IAM service-linked role thathas permissions to add data to your output Amazon S3 bucket. + Where: + datasetArn - The Amazon Resource Name (ARN) of the destination dataset. + s3BucketPath - The path to the Amazon S3 bucket where the data that you want to upload to your dataset is stored. + jobName - The name for the dataset import job. + roleArn - The ARN of the IAM service-linked role thathas permissions to add data to your output Amazon S3 bucket. - """; + """; if (args.length != 4) { System.out.println(USAGE); @@ -65,12 +54,12 @@ public static void main(String[] args) { personalizeClient.close(); } - //snippet-start:[personalize.java2.create_dataset_import_job.main] + // snippet-start:[personalize.java2.create_dataset_import_job.main] public static String createPersonalizeDatasetImportJob(PersonalizeClient personalizeClient, - String jobName, - String datasetArn, - String s3BucketPath, - String roleArn) { + String jobName, + String datasetArn, + String s3BucketPath, + String roleArn) { long waitInMilliseconds = 60 * 1000; String status; @@ -121,5 +110,5 @@ public static String createPersonalizeDatasetImportJob(PersonalizeClient persona } return ""; } - //snippet-end:[personalize.java2.create_dataset_import_job.main] + // snippet-end:[personalize.java2.create_dataset_import_job.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDomainDatasetGroup.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDomainDatasetGroup.java index 4ff4e37cb9f..4b3725c88e7 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDomainDatasetGroup.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDomainDatasetGroup.java @@ -1,20 +1,9 @@ -//snippet-sourcedescription:[CreateDomainDatasetGroup.java demonstrates how to create an Amazon Personalize -// domain dataset group.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon Personalize] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[3/11/2022] -//snippet-sourceauthor:[seashman - AWS] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.create_domain_dataset_group.import] +// snippet-start:[personalize.java2.create_domain_dataset_group.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; @@ -22,20 +11,20 @@ import software.amazon.awssdk.services.personalize.model.CreateDatasetGroupRequest; import java.time.Instant; -//snippet-end:[personalize.java2.create_domain_dataset_group.import] +// snippet-end:[personalize.java2.create_domain_dataset_group.import] public class CreateDomainDatasetGroup { public static void main(String[] args) { final String USAGE = """ - Usage: - CreateDomainDatasetGroup + Usage: + CreateDomainDatasetGroup - Where: - name - The name for the new dataset group. domain - The domain for the dataset group. Specify either ECOMMERCE or VIDEO_ON_DEMAND. + Where: + name - The name for the new dataset group. domain - The domain for the dataset group. Specify either ECOMMERCE or VIDEO_ON_DEMAND. - """; + """; if (args.length != 2) { System.out.println(USAGE); @@ -57,10 +46,10 @@ public static void main(String[] args) { personalizeClient.close(); } - //snippet-start:[personalize.java2.create_domain_dataset_group.main] + // snippet-start:[personalize.java2.create_domain_dataset_group.main] public static String createDomainDatasetGroup(PersonalizeClient personalizeClient, - String datasetGroupName, - String domain) { + String datasetGroupName, + String domain) { try { CreateDatasetGroupRequest createDatasetGroupRequest = CreateDatasetGroupRequest.builder() @@ -73,6 +62,6 @@ public static String createDomainDatasetGroup(PersonalizeClient personalizeClien } return ""; } - //snippet-end:[personalize.java2.create_domain_dataset_group.main] + // snippet-end:[personalize.java2.create_domain_dataset_group.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDomainSchema.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDomainSchema.java index 40ef89a0500..028c518aaaf 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDomainSchema.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateDomainSchema.java @@ -1,20 +1,9 @@ -//snippet-sourcedescription:[CreateDomainSchema.java demonstrates how to create -// an Amazon Personalize schema for a dataset in a domain dataset group.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon Personalize] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[3/5/2022] -//snippet-sourceauthor:[seashman - AWS] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.create_domain_schema.import] +// snippet-start:[personalize.java2.create_domain_schema.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.model.CreateSchemaRequest; @@ -24,22 +13,22 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; -//snippet-end:[personalize.java2.create_domain_schema.import] +// snippet-end:[personalize.java2.create_domain_schema.import] public class CreateDomainSchema { public static void main(String[] args) { final String USAGE = """ - Usage: - CreateSchema + Usage: + CreateSchema - Where: - name - The name for the schema. - domain - The domain of the dataset's domain dataset group. - schemaLocation - the location of the schema JSON file. + Where: + name - The name for the schema. + domain - The domain of the dataset's domain dataset group. + schemaLocation - the location of the schema JSON file. - """; + """; if (args.length != 3) { System.out.println(USAGE); @@ -50,7 +39,6 @@ public static void main(String[] args) { String domain = args[1]; String filePath = args[2]; - Region region = Region.US_WEST_2; PersonalizeClient personalizeClient = PersonalizeClient.builder() @@ -62,8 +50,10 @@ public static void main(String[] args) { personalizeClient.close(); } - //snippet-start:[personalize.java2.create_domain_schema.main] - public static String createDomainSchema(PersonalizeClient personalizeClient, String schemaName, String domain, String filePath) { + + // snippet-start:[personalize.java2.create_domain_schema.main] + public static String createDomainSchema(PersonalizeClient personalizeClient, String schemaName, String domain, + String filePath) { String schema = null; try { @@ -91,7 +81,6 @@ public static String createDomainSchema(PersonalizeClient personalizeClient, Str } return ""; } - //snippet-end:[personalize.java2.create_domain_schema.main] - + // snippet-end:[personalize.java2.create_domain_schema.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateEventTracker.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateEventTracker.java index 24792bf4dcf..b7b294f115f 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateEventTracker.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateEventTracker.java @@ -1,20 +1,9 @@ -//snippet-sourcedescription:[CreateEventTracker.java demonstrates how to create -// an Amazon Personalize event tracker that you can use with the PutEvents operation.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon Personalize] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[7/13/2021] -//snippet-sourceauthor:[seashman - AWS] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.create_event_tracker.import] +// snippet-start:[personalize.java2.create_event_tracker.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; @@ -24,56 +13,60 @@ import software.amazon.awssdk.services.personalize.model.DescribeEventTrackerRequest; import java.time.Instant; -//snippet-end:[personalize.java2.create_event_tracker.import] + +// snippet-end:[personalize.java2.create_event_tracker.import] public class CreateEventTracker { - public static void main(String [] args) { - + public static void main(String[] args) { + final String USAGE = """ - Usage: - CreateDatasetGroup + Usage: + CreateDatasetGroup - Where: - datasetGroupArn - The Amazon Resource Name (ARN) of the dataset group that receives the event data - name - The name for the event tracker. + Where: + datasetGroupArn - The Amazon Resource Name (ARN) of the dataset group that receives the event data + name - The name for the event tracker. + + """; - """; - if (args.length != 2) { System.out.println(USAGE); System.exit(1); } - + String datasetGroupArn = args[0]; String eventTrackerName = args[1]; Region region = Region.US_WEST_2; PersonalizeClient personalizeClient = PersonalizeClient.builder() - .region(region) - .build(); + .region(region) + .build(); String trackerId = createEventTracker(personalizeClient, eventTrackerName, datasetGroupArn); System.out.println(trackerId); personalizeClient.close(); } - //snippet-start:[personalize.java2.create_event_tracker.main] - public static String createEventTracker(PersonalizeClient personalizeClient, String eventTrackerName, String datasetGroupArn) { - + + // snippet-start:[personalize.java2.create_event_tracker.main] + public static String createEventTracker(PersonalizeClient personalizeClient, String eventTrackerName, + String datasetGroupArn) { + String eventTrackerId = ""; String eventTrackerArn; long maxTime = 3 * 60 * 60; // 3 hours long waitInMilliseconds = 20 * 1000; // 20 seconds String status; - + try { CreateEventTrackerRequest createEventTrackerRequest = CreateEventTrackerRequest.builder() - .name(eventTrackerName) - .datasetGroupArn(datasetGroupArn) - .build(); - - CreateEventTrackerResponse createEventTrackerResponse = personalizeClient.createEventTracker(createEventTrackerRequest); - + .name(eventTrackerName) + .datasetGroupArn(datasetGroupArn) + .build(); + + CreateEventTrackerResponse createEventTrackerResponse = personalizeClient + .createEventTracker(createEventTrackerRequest); + eventTrackerArn = createEventTrackerResponse.eventTrackerArn(); eventTrackerId = createEventTrackerResponse.trackingId(); System.out.println("Event tracker ARN: " + eventTrackerArn); @@ -82,10 +75,9 @@ public static String createEventTracker(PersonalizeClient personalizeClient, Str maxTime = Instant.now().getEpochSecond() + maxTime; DescribeEventTrackerRequest describeRequest = DescribeEventTrackerRequest.builder() - .eventTrackerArn(eventTrackerArn) - .build(); + .eventTrackerArn(eventTrackerArn) + .build(); - while (Instant.now().getEpochSecond() < maxTime) { status = personalizeClient.describeEventTracker(describeRequest).eventTracker().status(); @@ -101,12 +93,11 @@ public static String createEventTracker(PersonalizeClient personalizeClient, Str } } return eventTrackerId; - } - catch (PersonalizeException e){ + } catch (PersonalizeException e) { System.out.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return eventTrackerId; } - //snippet-end:[personalize.java2.create_event_tracker.main] + // snippet-end:[personalize.java2.create_event_tracker.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateFilter.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateFilter.java index 978a65528ef..958c9ea8e84 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateFilter.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateFilter.java @@ -1,39 +1,29 @@ -//snippet-sourcedescription:[CreateFilter.java demonstrates how to create an Amazon Personalize filter.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon Personalize] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[7/13/2021] -//snippet-sourceauthor:[seashman - AWS] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.create_filter.import] +// snippet-start:[personalize.java2.create_filter.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.model.CreateFilterRequest; import software.amazon.awssdk.services.personalize.PersonalizeClient; import software.amazon.awssdk.services.personalize.model.PersonalizeException; -//snippet-end:[personalize.java2.create_filter.import] +// snippet-end:[personalize.java2.create_filter.import] public class CreateFilter { - public static void main(String [] args) { + public static void main(String[] args) { final String USAGE = """ - Usage: - CreateFilter + Usage: + CreateFilter - Where: - filterName - The name for the filter. - datasetGroupArn - The Amazon Resource Name (ARN) for the destination dataset group. - filterExpression - The expression for the filter. + Where: + filterName - The name for the filter. + datasetGroupArn - The Amazon Resource Name (ARN) for the destination dataset group. + filterExpression - The expression for the filter. - """; + """; if (args.length != 3) { System.out.println(USAGE); @@ -56,11 +46,12 @@ public static void main(String [] args) { personalizeClient.close(); } - //snippet-start:[personalize.java2.create_filter.main] + + // snippet-start:[personalize.java2.create_filter.main] public static String createFilter(PersonalizeClient personalizeClient, - String filterName, - String datasetGroupArn, - String filterExpression) { + String filterName, + String datasetGroupArn, + String filterExpression) { try { CreateFilterRequest request = CreateFilterRequest.builder() .name(filterName) @@ -69,14 +60,12 @@ public static String createFilter(PersonalizeClient personalizeClient, .build(); return personalizeClient.createFilter(request).filterArn(); - } - catch(PersonalizeException e) { + } catch (PersonalizeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } - //snippet-end:[personalize.java2.create_filter.main] - + // snippet-end:[personalize.java2.create_filter.main] } \ No newline at end of file diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateRecommender.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateRecommender.java index d7ea4625178..31e3bb7e613 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateRecommender.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateRecommender.java @@ -1,20 +1,9 @@ -//snippet-sourcedescription:[CreateRecommender.java demonstrates how to create an Amazon Personalize recommender -// for a domain dataset group.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon Personalize] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[1/3/2022] -//snippet-sourceauthor:[seashman - AWS] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.create_recommender.import] +// snippet-start:[personalize.java2.create_recommender.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; import software.amazon.awssdk.services.personalize.model.CreateRecommenderRequest; @@ -23,10 +12,11 @@ import software.amazon.awssdk.services.personalize.model.PersonalizeException; import java.time.Instant; -//snippet-end:[personalize.java2.create_recommender.import] +// snippet-end:[personalize.java2.create_recommender.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -38,15 +28,15 @@ public static void main(String[] args) { final String USAGE = """ - Usage: - CreateRecommender + Usage: + CreateRecommender - Where: - datasetGroupArn - The ARN of the destination dataset group for the recommender. - name - The name of the new recommender. - recipeArn - The ARN of the use case (recipe) for the recommender. + Where: + datasetGroupArn - The ARN of the destination dataset group for the recommender. + name - The name of the new recommender. + recipeArn - The ARN of the use case (recipe) for the recommender. - """; + """; if (args.length != 3) { System.out.println(USAGE); @@ -67,54 +57,56 @@ public static void main(String[] args) { personalizeClient.close(); } - //snippet-start:[personalize.java2.create_recommender.main] + // snippet-start:[personalize.java2.create_recommender.main] public static String createRecommender(PersonalizeClient personalizeClient, - String name, - String datasetGroupArn, - String recipeArn) { + String name, + String datasetGroupArn, + String recipeArn) { long maxTime = 0; long waitInMilliseconds = 30 * 1000; // 30 seconds String recommenderStatus = ""; try { - CreateRecommenderRequest createRecommenderRequest = CreateRecommenderRequest.builder() - .datasetGroupArn(datasetGroupArn) - .name(name) - .recipeArn(recipeArn) - .build(); - - CreateRecommenderResponse recommenderResponse = personalizeClient.createRecommender(createRecommenderRequest); - String recommenderArn = recommenderResponse.recommenderArn(); - System.out.println("The recommender ARN is " + recommenderArn); - - DescribeRecommenderRequest describeRecommenderRequest = DescribeRecommenderRequest.builder() - .recommenderArn(recommenderArn) - .build(); - - maxTime = Instant.now().getEpochSecond() + 3 * 60 * 60; - - while (Instant.now().getEpochSecond() < maxTime) { - - recommenderStatus = personalizeClient.describeRecommender(describeRecommenderRequest).recommender().status(); - System.out.println("Recommender status: " + recommenderStatus); - - if (recommenderStatus.equals("ACTIVE") || recommenderStatus.equals("CREATE FAILED")) { - break; - } - try { - Thread.sleep(waitInMilliseconds); - } catch (InterruptedException e) { - System.out.println(e.getMessage()); - } + CreateRecommenderRequest createRecommenderRequest = CreateRecommenderRequest.builder() + .datasetGroupArn(datasetGroupArn) + .name(name) + .recipeArn(recipeArn) + .build(); + + CreateRecommenderResponse recommenderResponse = personalizeClient + .createRecommender(createRecommenderRequest); + String recommenderArn = recommenderResponse.recommenderArn(); + System.out.println("The recommender ARN is " + recommenderArn); + + DescribeRecommenderRequest describeRecommenderRequest = DescribeRecommenderRequest.builder() + .recommenderArn(recommenderArn) + .build(); + + maxTime = Instant.now().getEpochSecond() + 3 * 60 * 60; + + while (Instant.now().getEpochSecond() < maxTime) { + + recommenderStatus = personalizeClient.describeRecommender(describeRecommenderRequest).recommender() + .status(); + System.out.println("Recommender status: " + recommenderStatus); + + if (recommenderStatus.equals("ACTIVE") || recommenderStatus.equals("CREATE FAILED")) { + break; + } + try { + Thread.sleep(waitInMilliseconds); + } catch (InterruptedException e) { + System.out.println(e.getMessage()); } - return recommenderArn; + } + return recommenderArn; - } catch(PersonalizeException e) { + } catch (PersonalizeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } - //snippet-end:[personalize.java2.create_recommender.main] + // snippet-end:[personalize.java2.create_recommender.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateSchema.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateSchema.java index 8683219dd33..5b6885b27c1 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateSchema.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateSchema.java @@ -1,20 +1,9 @@ -//snippet-sourcedescription:[CreateSchema.java demonstrates how to create -// an Amazon Personalize schema.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon Personalize] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[7/13/2021] -//snippet-sourceauthor:[seashman - AWS] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.create_schema.import] +// snippet-start:[personalize.java2.create_schema.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.model.CreateSchemaRequest; @@ -24,21 +13,21 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; -//snippet-end:[personalize.java2.create_schema.import] +// snippet-end:[personalize.java2.create_schema.import] public class CreateSchema { public static void main(String[] args) { final String USAGE = """ - Usage: - CreateSchema + Usage: + CreateSchema - Where: - name - The name for the schema. - schemaLocation - the location of the schema JSON file. + Where: + name - The name for the schema. + schemaLocation - the location of the schema JSON file. - """; + """; if (args.length != 2) { System.out.println(USAGE); @@ -48,7 +37,6 @@ public static void main(String[] args) { String schemaName = args[0]; String filePath = args[1]; - Region region = Region.US_WEST_2; PersonalizeClient personalizeClient = PersonalizeClient.builder() @@ -60,7 +48,8 @@ public static void main(String[] args) { personalizeClient.close(); } - //snippet-start:[personalize.java2.create_schema.main] + + // snippet-start:[personalize.java2.create_schema.main] public static String createSchema(PersonalizeClient personalizeClient, String schemaName, String filePath) { String schema = null; @@ -88,7 +77,6 @@ public static String createSchema(PersonalizeClient personalizeClient, String sc } return ""; } - //snippet-end:[personalize.java2.create_schema.main] - + // snippet-end:[personalize.java2.create_schema.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateSolution.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateSolution.java index dd89d777c64..9e80f792e67 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateSolution.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateSolution.java @@ -1,24 +1,19 @@ -//snippet-sourcedescription:[CreateSolution.java demonstrates how to create an Amazon Personalize solution.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Personalize] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.create_solution.import] +// snippet-start:[personalize.java2.create_solution.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; import software.amazon.awssdk.services.personalize.model.CreateSolutionRequest; import software.amazon.awssdk.services.personalize.model.PersonalizeException; import software.amazon.awssdk.services.personalize.model.CreateSolutionResponse; -//snippet-end:[personalize.java2.create_solution.import] +// snippet-end:[personalize.java2.create_solution.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -30,17 +25,17 @@ public static void main(String[] args) { final String USAGE = """ - Usage: - CreateSolution + Usage: + CreateSolution - Where: - datasetGroupArn - The ARN of the dataset group. + Where: + datasetGroupArn - The ARN of the dataset group. - solutionName - The name of the Amazon Personalization campaign. + solutionName - The name of the Amazon Personalization campaign. - recipeArn - The ARN of the recipe. + recipeArn - The ARN of the recipe. - """; + """; if (args.length != 3) { System.out.println(USAGE); @@ -53,26 +48,26 @@ public static void main(String[] args) { Region region = Region.US_EAST_1; PersonalizeClient personalizeClient = PersonalizeClient.builder() - .region(region) - .build(); + .region(region) + .build(); String solutionArn = createPersonalizeSolution(personalizeClient, datasetGroupArn, solutionName, recipeArn); - System.out.println("The Amazon Personalize solution ARN is "+solutionArn); + System.out.println("The Amazon Personalize solution ARN is " + solutionArn); personalizeClient.close(); } - //snippet-start:[personalize.java2.create_solution.main] + // snippet-start:[personalize.java2.create_solution.main] public static String createPersonalizeSolution(PersonalizeClient personalizeClient, - String datasetGroupArn, - String solutionName, - String recipeArn) { + String datasetGroupArn, + String solutionName, + String recipeArn) { try { CreateSolutionRequest solutionRequest = CreateSolutionRequest.builder() - .name(solutionName) - .datasetGroupArn(datasetGroupArn) - .recipeArn(recipeArn) - .build(); + .name(solutionName) + .datasetGroupArn(datasetGroupArn) + .recipeArn(recipeArn) + .build(); CreateSolutionResponse solutionResponse = personalizeClient.createSolution(solutionRequest); return solutionResponse.solutionArn(); @@ -83,5 +78,5 @@ public static String createPersonalizeSolution(PersonalizeClient personalizeClie } return ""; } - //snippet-end:[personalize.java2.create_solution.main] + // snippet-end:[personalize.java2.create_solution.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateSolutionVersion.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateSolutionVersion.java index 298b3dd6bbf..34087ff5358 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateSolutionVersion.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/CreateSolutionVersion.java @@ -1,19 +1,9 @@ -//snippet-sourcedescription:[CreateSolutionVersion.java demonstrates how to create -// an Amazon Personalize solution version (train a model).] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon Personalize] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[7/13/2021] -//snippet-sourceauthor:[seashman - AWS] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.personalize; -//snippet-start:[personalize.java2.create_solution_version.import] +// snippet-start:[personalize.java2.create_solution_version.import] import java.time.Instant; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; @@ -22,21 +12,21 @@ import software.amazon.awssdk.services.personalize.model.CreateSolutionVersionResponse; import software.amazon.awssdk.services.personalize.model.DescribeSolutionRequest; import software.amazon.awssdk.services.personalize.model.DescribeSolutionVersionRequest; -//snippet-end:[personalize.java2.create_solution_version.import] +// snippet-end:[personalize.java2.create_solution_version.import] public class CreateSolutionVersion { - public static void main(String [] args) { + public static void main(String[] args) { - final String USAGE = """ + final String USAGE = """ - Usage: - CreateSolutionVersion + Usage: + CreateSolutionVersion - Where: - solutionArn - The ARN of the solution. + Where: + solutionArn - The ARN of the solution. - """; + """; if (args.length != 1) { System.out.println(USAGE); @@ -54,7 +44,7 @@ public static void main(String [] args) { personalizeClient.close(); } - //snippet-start:[personalize.java2.create_solution_version.main] + // snippet-start:[personalize.java2.create_solution_version.main] public static String createPersonalizeSolutionVersion(PersonalizeClient personalizeClient, String solutionArn) { long maxTime = 0; long waitInMilliseconds = 30 * 1000; // 30 seconds @@ -64,12 +54,12 @@ public static String createPersonalizeSolutionVersion(PersonalizeClient personal try { DescribeSolutionRequest describeSolutionRequest = DescribeSolutionRequest.builder() - .solutionArn(solutionArn) - .build(); - + .solutionArn(solutionArn) + .build(); + maxTime = Instant.now().getEpochSecond() + 3 * 60 * 60; - // Wait until solution is active. + // Wait until solution is active. while (Instant.now().getEpochSecond() < maxTime) { solutionStatus = personalizeClient.describeSolution(describeSolutionRequest).solution().status(); @@ -88,21 +78,23 @@ public static String createPersonalizeSolutionVersion(PersonalizeClient personal if (solutionStatus.equals("ACTIVE")) { CreateSolutionVersionRequest createSolutionVersionRequest = CreateSolutionVersionRequest.builder() - .solutionArn(solutionArn) - .build(); + .solutionArn(solutionArn) + .build(); - CreateSolutionVersionResponse createSolutionVersionResponse = personalizeClient.createSolutionVersion(createSolutionVersionRequest); + CreateSolutionVersionResponse createSolutionVersionResponse = personalizeClient + .createSolutionVersion(createSolutionVersionRequest); solutionVersionArn = createSolutionVersionResponse.solutionVersionArn(); System.out.println("Solution version ARN: " + solutionVersionArn); DescribeSolutionVersionRequest describeSolutionVersionRequest = DescribeSolutionVersionRequest.builder() - .solutionVersionArn(solutionVersionArn) - .build(); + .solutionVersionArn(solutionVersionArn) + .build(); while (Instant.now().getEpochSecond() < maxTime) { - solutionVersionStatus = personalizeClient.describeSolutionVersion(describeSolutionVersionRequest).solutionVersion().status(); + solutionVersionStatus = personalizeClient.describeSolutionVersion(describeSolutionVersionRequest) + .solutionVersion().status(); System.out.println("Solution version status: " + solutionVersionStatus); if (solutionVersionStatus.equals("ACTIVE") || solutionVersionStatus.equals("CREATE FAILED")) { @@ -116,11 +108,11 @@ public static String createPersonalizeSolutionVersion(PersonalizeClient personal } return solutionVersionArn; } - } catch(PersonalizeException e) { + } catch (PersonalizeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } - //snippet-end:[personalize.java2.create_solution_version.main] + // snippet-end:[personalize.java2.create_solution_version.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/DeleteCampaign.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/DeleteCampaign.java index 3b808d7117e..5f74a6b68c7 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/DeleteCampaign.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/DeleteCampaign.java @@ -1,23 +1,18 @@ -//snippet-sourcedescription:[DeleteCampaign.java demonstrates how to delete an Amazon Personalize campaign.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Personalize] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.delete_campaign.import] +// snippet-start:[personalize.java2.delete_campaign.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; import software.amazon.awssdk.services.personalize.model.DeleteCampaignRequest; import software.amazon.awssdk.services.personalize.model.PersonalizeException; -//snippet-end:[personalize.java2.delete_campaign.import] +// snippet-end:[personalize.java2.delete_campaign.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -29,13 +24,13 @@ public static void main(String[] args) { final String USAGE = """ - Usage: - DeleteCampaign \s + Usage: + DeleteCampaign \s - Where: - campaignArn - The ARN of the campaign to delete. + Where: + campaignArn - The ARN of the campaign to delete. - """; + """; if (args.length != 1) { System.out.println(USAGE); @@ -45,20 +40,20 @@ public static void main(String[] args) { String campaignArn = args[0]; Region region = Region.US_EAST_1; PersonalizeClient personalizeClient = PersonalizeClient.builder() - .region(region) - .build(); + .region(region) + .build(); - deleteSpecificCampaign(personalizeClient, campaignArn) ; + deleteSpecificCampaign(personalizeClient, campaignArn); personalizeClient.close(); } - //snippet-start:[personalize.java2.delete_campaign.main] - public static void deleteSpecificCampaign(PersonalizeClient personalizeClient, String campaignArn ) { + // snippet-start:[personalize.java2.delete_campaign.main] + public static void deleteSpecificCampaign(PersonalizeClient personalizeClient, String campaignArn) { try { DeleteCampaignRequest campaignRequest = DeleteCampaignRequest.builder() - .campaignArn(campaignArn) - .build(); + .campaignArn(campaignArn) + .build(); personalizeClient.deleteCampaign(campaignRequest); @@ -67,5 +62,5 @@ public static void deleteSpecificCampaign(PersonalizeClient personalizeClient, S System.exit(1); } } - //snippet-end:[personalize.java2.delete_campaign.main] + // snippet-end:[personalize.java2.delete_campaign.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/DeleteEventTracker.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/DeleteEventTracker.java index ca822958001..cee9f95a58c 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/DeleteEventTracker.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/DeleteEventTracker.java @@ -1,53 +1,43 @@ -//snippet-sourcedescription:[DeleteEventTracker.java demonstrates how to delete -// an Amazon Personalize event tracker.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon Personalize] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[7/13/2021] -//snippet-sourceauthor:[seashman - AWS] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.personalize; -//snippet-start:[personalize.java2.delete_event_tracker.import] +// snippet-start:[personalize.java2.delete_event_tracker.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; import software.amazon.awssdk.services.personalize.model.PersonalizeException; import software.amazon.awssdk.services.personalize.model.DeleteEventTrackerRequest; -//snippet-end:[personalize.java2.delete_event_tracker.import] + +// snippet-end:[personalize.java2.delete_event_tracker.import] public class DeleteEventTracker { - public static void main(String [] args) { + public static void main(String[] args) { Region region = Region.US_WEST_2; String eventTrackerArn = args[0]; PersonalizeClient personalizeClient = PersonalizeClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteEventTracker(personalizeClient, eventTrackerArn); personalizeClient.close(); } - //snippet-start:[personalize.java2.delete_event_tracker.main] + + // snippet-start:[personalize.java2.delete_event_tracker.main] public static void deleteEventTracker(PersonalizeClient personalizeClient, String eventTrackerArn) { try { DeleteEventTrackerRequest deleteEventTrackerRequest = DeleteEventTrackerRequest.builder() - .eventTrackerArn(eventTrackerArn) - .build(); - - int status = - personalizeClient.deleteEventTracker(deleteEventTrackerRequest).sdkHttpResponse().statusCode(); + .eventTrackerArn(eventTrackerArn) + .build(); + + int status = personalizeClient.deleteEventTracker(deleteEventTrackerRequest).sdkHttpResponse().statusCode(); System.out.println("Status code:" + status); - - } - catch (PersonalizeException e) { + + } catch (PersonalizeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } - //snippet-end:[personalize.java2.delete_event_tracker.main] + // snippet-end:[personalize.java2.delete_event_tracker.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/DeleteSolution.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/DeleteSolution.java index 4b34b3ebe9a..b98fcd572fe 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/DeleteSolution.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/DeleteSolution.java @@ -1,23 +1,18 @@ -//snippet-sourcedescription:[DeleteSolution.java demonstrates how to delete an Amazon Personalize solution.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Personalize] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.delete_solution.import] +// snippet-start:[personalize.java2.delete_solution.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; import software.amazon.awssdk.services.personalize.model.DeleteSolutionRequest; import software.amazon.awssdk.services.personalize.model.PersonalizeException; -//snippet-end:[personalize.java2.delete_solution.import] +// snippet-end:[personalize.java2.delete_solution.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -28,13 +23,13 @@ public static void main(String[] args) { final String USAGE = """ - Usage: - DeleteSolution + Usage: + DeleteSolution - Where: - solutionArn - the ARN of the solution to delete. + Where: + solutionArn - the ARN of the solution to delete. - """; + """; if (args.length != 1) { System.out.println(USAGE); @@ -44,20 +39,20 @@ public static void main(String[] args) { String solutionArn = args[0]; Region region = Region.US_EAST_1; PersonalizeClient personalizeClient = PersonalizeClient.builder() - .region(region) - .build(); + .region(region) + .build(); - deleteGivenSolution(personalizeClient, solutionArn ); + deleteGivenSolution(personalizeClient, solutionArn); personalizeClient.close(); } - //snippet-start:[personalize.java2.delete_solution.main] - public static void deleteGivenSolution(PersonalizeClient personalizeClient, String solutionArn ) { + // snippet-start:[personalize.java2.delete_solution.main] + public static void deleteGivenSolution(PersonalizeClient personalizeClient, String solutionArn) { try { DeleteSolutionRequest solutionRequest = DeleteSolutionRequest.builder() - .solutionArn(solutionArn) - .build(); + .solutionArn(solutionArn) + .build(); personalizeClient.deleteSolution(solutionRequest); System.out.println("Done"); @@ -67,5 +62,5 @@ public static void deleteGivenSolution(PersonalizeClient personalizeClient, Stri System.exit(1); } } - //snippet-end:[personalize.java2.delete_solution.main] + // snippet-end:[personalize.java2.delete_solution.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/DescribeCampaign.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/DescribeCampaign.java index 548e2bea4cb..be8db6ea69a 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/DescribeCampaign.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/DescribeCampaign.java @@ -1,24 +1,20 @@ -//snippet-sourcedescription:[DescribeCampaign.java demonstrates how to describe an Amazon Personalize campaign.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Personalize] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.describe_campaign.import] +// snippet-start:[personalize.java2.describe_campaign.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; import software.amazon.awssdk.services.personalize.model.DescribeCampaignRequest; import software.amazon.awssdk.services.personalize.model.DescribeCampaignResponse; import software.amazon.awssdk.services.personalize.model.Campaign; import software.amazon.awssdk.services.personalize.model.PersonalizeException; -//snippet-end:[personalize.java2.describe_campaign.import] +// snippet-end:[personalize.java2.describe_campaign.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -30,13 +26,13 @@ public static void main(String[] args) { final String USAGE = """ - Usage: - DescribeCampaign + Usage: + DescribeCampaign - Where: - campaignArn - The ARN of the campaign. + Where: + campaignArn - The ARN of the campaign. - """; + """; if (args.length < 1) { System.out.println(USAGE); @@ -46,30 +42,30 @@ public static void main(String[] args) { String campaignArn = args[0]; Region region = Region.US_EAST_1; PersonalizeClient personalizeClient = PersonalizeClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeSpecificCampaign(personalizeClient, campaignArn); personalizeClient.close(); } - //snippet-start:[personalize.java2.describe_campaign.main] + // snippet-start:[personalize.java2.describe_campaign.main] public static void describeSpecificCampaign(PersonalizeClient personalizeClient, String campaignArn) { try { DescribeCampaignRequest campaignRequest = DescribeCampaignRequest.builder() - .campaignArn(campaignArn) - .build(); + .campaignArn(campaignArn) + .build(); DescribeCampaignResponse campaignResponse = personalizeClient.describeCampaign(campaignRequest); Campaign myCampaign = campaignResponse.campaign(); - System.out.println("The Campaign name is "+myCampaign.name()); - System.out.println("The Campaign status is "+myCampaign.status()); + System.out.println("The Campaign name is " + myCampaign.name()); + System.out.println("The Campaign status is " + myCampaign.status()); } catch (PersonalizeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } - //snippet-end:[personalize.java2.describe_campaign.main] + // snippet-end:[personalize.java2.describe_campaign.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/DescribeRecipe.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/DescribeRecipe.java index 81a85a534b7..77d29eda832 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/DescribeRecipe.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/DescribeRecipe.java @@ -1,24 +1,19 @@ -//snippet-sourcedescription:[DescribeRecipe.java demonstrates how to describe an Amazon Personalize recipe.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Personalize] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.describe_recipe.import] +// snippet-start:[personalize.java2.describe_recipe.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; import software.amazon.awssdk.services.personalize.model.DescribeRecipeRequest; import software.amazon.awssdk.services.personalize.model.DescribeRecipeResponse; import software.amazon.awssdk.services.personalize.model.PersonalizeException; -//snippet-end:[personalize.java2.describe_recipe.import] +// snippet-end:[personalize.java2.describe_recipe.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -29,13 +24,13 @@ public static void main(String[] args) { final String USAGE = """ - Usage: - DescribeRecipe + Usage: + DescribeRecipe - Where: - recipeArn - The ARN of the recipe. + Where: + recipeArn - The ARN of the recipe. - """; + """; if (args.length < 1) { System.out.println(USAGE); @@ -45,28 +40,28 @@ public static void main(String[] args) { String recipeArn = args[0]; Region region = Region.US_EAST_1; PersonalizeClient personalizeClient = PersonalizeClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeSpecificRecipe(personalizeClient, recipeArn); personalizeClient.close(); } - //snippet-start:[personalize.java2.describe_recipe.main] + // snippet-start:[personalize.java2.describe_recipe.main] public static void describeSpecificRecipe(PersonalizeClient personalizeClient, String recipeArn) { - try{ + try { DescribeRecipeRequest recipeRequest = DescribeRecipeRequest.builder() - .recipeArn(recipeArn) - .build(); + .recipeArn(recipeArn) + .build(); DescribeRecipeResponse recipeResponse = personalizeClient.describeRecipe(recipeRequest); - System.out.println("The recipe name is "+recipeResponse.recipe().name()); + System.out.println("The recipe name is " + recipeResponse.recipe().name()); } catch (PersonalizeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } - //snippet-end:[personalize.java2.describe_recipe.main] + // snippet-end:[personalize.java2.describe_recipe.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/DescribeSolution.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/DescribeSolution.java index 8070074b25a..e3da3d2c4b0 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/DescribeSolution.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/DescribeSolution.java @@ -1,24 +1,19 @@ -//snippet-sourcedescription:[DescribeSolution.java demonstrates how to describe an Amazon Personalize solution.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Personalize] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.describe_solution.import] +// snippet-start:[personalize.java2.describe_solution.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; import software.amazon.awssdk.services.personalize.model.DescribeSolutionRequest; import software.amazon.awssdk.services.personalize.model.DescribeSolutionResponse; import software.amazon.awssdk.services.personalize.model.PersonalizeException; -//snippet-end:[personalize.java2.describe_solution.import] +// snippet-end:[personalize.java2.describe_solution.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -30,13 +25,13 @@ public static void main(String[] args) { final String USAGE = """ - Usage: - DescribeSolution + Usage: + DescribeSolution - Where: - solutionArn - The ARN of the solution. + Where: + solutionArn - The ARN of the solution. - """; + """; if (args.length < 1) { System.out.println(USAGE); @@ -46,28 +41,28 @@ public static void main(String[] args) { String solutionArn = args[0]; Region region = Region.US_EAST_1; PersonalizeClient personalizeClient = PersonalizeClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeSpecificSolution(personalizeClient, solutionArn); personalizeClient.close(); } - //snippet-start:[personalize.java2.describe_solution.main] - public static void describeSpecificSolution(PersonalizeClient personalizeClient, String solutionArn) { + // snippet-start:[personalize.java2.describe_solution.main] + public static void describeSpecificSolution(PersonalizeClient personalizeClient, String solutionArn) { - try { - DescribeSolutionRequest solutionRequest = DescribeSolutionRequest.builder() - .solutionArn(solutionArn) - .build(); + try { + DescribeSolutionRequest solutionRequest = DescribeSolutionRequest.builder() + .solutionArn(solutionArn) + .build(); - DescribeSolutionResponse response = personalizeClient.describeSolution(solutionRequest); - System.out.println("The Solution name is "+response.solution().name()); + DescribeSolutionResponse response = personalizeClient.describeSolution(solutionRequest); + System.out.println("The Solution name is " + response.solution().name()); - } catch (PersonalizeException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - //snippet-end:[personalize.java2.describe_solution.main] + } catch (PersonalizeException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + // snippet-end:[personalize.java2.describe_solution.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/FilterRecommendations.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/FilterRecommendations.java index b48673e3285..c856111ce18 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/FilterRecommendations.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/FilterRecommendations.java @@ -1,19 +1,9 @@ -//snippet-sourcedescription:[FilterRecommendations.java demonstrates how use a filter when requesting recommendations] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon Personalize] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[7/13/2021] -//snippet-sourceauthor:[seashman - AWS] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.filter_recommendations.import] +// snippet-start:[personalize.java2.filter_recommendations.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalizeruntime.model.PersonalizeRuntimeException; import software.amazon.awssdk.services.personalizeruntime.PersonalizeRuntimeClient; @@ -24,10 +14,11 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -//snippet-end:[personalize.java2.filter_recommendations.import] +// snippet-end:[personalize.java2.filter_recommendations.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -38,22 +29,25 @@ public class FilterRecommendations { public static void main(String[] args) { // This example shows how to use a filter with an expression that has - // two placeholder parameters, and passes two values to the first and one to the second. + // two placeholder parameters, and passes two values to the first and one to the + // second. // in the GetRecommendations request. - // Your filter may not have the same number of parameters or you may not want to use two values. - // Change the following code and the PersonalizeTest.java code based on the number of parameters + // Your filter may not have the same number of parameters or you may not want to + // use two values. + // Change the following code and the PersonalizeTest.java code based on the + // number of parameters // your expression uses and the values you want to pass. final String USAGE = """ - Usage: - GetRecommendations + Usage: + GetRecommendations - Where: - campaignArn - The Amazon Resource Name (ARN) of the campaign. - userId - The user ID to provide recommendations for. filterArn - The ARN of the filter to use. parameter1Name - The name of the first placeholder parameter in the filter. parameter1Value1 - The first value to pass to the first parameter. parameter1Value2 - The second value to pass to the first parameter. parameter2Name = The name of the second placeholder parameter in the filter. parameter2Value = The value to pass to the second parameter + Where: + campaignArn - The Amazon Resource Name (ARN) of the campaign. + userId - The user ID to provide recommendations for. filterArn - The ARN of the filter to use. parameter1Name - The name of the first placeholder parameter in the filter. parameter1Value1 - The first value to pass to the first parameter. parameter1Value2 - The second value to pass to the first parameter. parameter2Name = The name of the second placeholder parameter in the filter. parameter2Value = The value to pass to the second parameter - """; + """; if (args.length != 8) { System.out.println(USAGE); @@ -78,16 +72,17 @@ public static void main(String[] args) { parameter1Value2, parameter2Name, parameter2Value); personalizeRuntimeClient.close(); } - //snippet-start:[personalize.java2.filter_recommendations.main] + + // snippet-start:[personalize.java2.filter_recommendations.main] public static void getFilteredRecs(PersonalizeRuntimeClient personalizeRuntimeClient, - String campaignArn, - String userId, - String filterArn, - String parameter1Name, - String parameter1Value1, - String parameter1Value2, - String parameter2Name, - String parameter2Value){ + String campaignArn, + String userId, + String filterArn, + String parameter1Name, + String parameter1Value1, + String parameter1Value2, + String parameter2Name, + String parameter2Value) { try { @@ -106,17 +101,18 @@ public static void getFilteredRecs(PersonalizeRuntimeClient personalizeRuntimeCl .filterValues(filterValues) .build(); - GetRecommendationsResponse recommendationsResponse = personalizeRuntimeClient.getRecommendations(recommendationsRequest); + GetRecommendationsResponse recommendationsResponse = personalizeRuntimeClient + .getRecommendations(recommendationsRequest); List items = recommendationsResponse.itemList(); - for (PredictedItem item: items) { - System.out.println("Item Id is : "+item.itemId()); - System.out.println("Item score is : "+item.score()); + for (PredictedItem item : items) { + System.out.println("Item Id is : " + item.itemId()); + System.out.println("Item score is : " + item.score()); } } catch (PersonalizeRuntimeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } - //snippet-end:[personalize.java2.filter_recommendations.main] + // snippet-end:[personalize.java2.filter_recommendations.main] } \ No newline at end of file diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/GetPersonalizedRanking.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/GetPersonalizedRanking.java index b0ca34dc07e..5f5f66f3ded 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/GetPersonalizedRanking.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/GetPersonalizedRanking.java @@ -1,20 +1,9 @@ -//snippet-sourcedescription:[GetPersonalizedRanking.java demonstrates how to request a -// personalized ranking of items for a user.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon Personalize] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[7/13/2021] -//snippet-sourceauthor:[seashman - AWS] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.get_personalized_ranking.import] +// snippet-start:[personalize.java2.get_personalized_ranking.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalizeruntime.PersonalizeRuntimeClient; @@ -26,10 +15,11 @@ import java.util.Arrays; import java.util.List; import java.util.ArrayList; -//snippet-end:[personalize.java2.get_personalized_ranking.import] +// snippet-end:[personalize.java2.get_personalized_ranking.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. *

    * For information, see this documentation topic: *

    @@ -41,15 +31,15 @@ public static void main(String[] args) { final String USAGE = """ - Usage: - GetPersonalizedRanking + Usage: + GetPersonalizedRanking - Where: - campaignArn - The ARN of the campaign. - userId - The user ID to provide recommendations for. - itemList - A comma delimited list of items to rank for the user + Where: + campaignArn - The ARN of the campaign. + userId - The user ID to provide recommendations for. + itemList - A comma delimited list of items to rank for the user - """; + """; if (args.length < 3) { System.out.println(USAGE); @@ -67,11 +57,11 @@ public static void main(String[] args) { personalizeRuntimeClient.close(); } - //snippet-start:[personalize.java2.get_personalized_ranking.main] + // snippet-start:[personalize.java2.get_personalized_ranking.main] public static List getRankedRecs(PersonalizeRuntimeClient personalizeRuntimeClient, - String campaignArn, - String userId, - ArrayList items) { + String campaignArn, + String userId, + ArrayList items) { try { GetPersonalizedRankingRequest rankingRecommendationsRequest = GetPersonalizedRankingRequest.builder() @@ -80,8 +70,8 @@ public static List getRankedRecs(PersonalizeRuntimeClient persona .inputList(items) .build(); - GetPersonalizedRankingResponse recommendationsResponse = - personalizeRuntimeClient.getPersonalizedRanking(rankingRecommendationsRequest); + GetPersonalizedRankingResponse recommendationsResponse = personalizeRuntimeClient + .getPersonalizedRanking(rankingRecommendationsRequest); List rankedItems = recommendationsResponse.personalizedRanking(); int rank = 1; for (PredictedItem item : rankedItems) { @@ -98,5 +88,5 @@ public static List getRankedRecs(PersonalizeRuntimeClient persona } return null; } - //snippet-end:[personalize.java2.get_personalized_ranking.main] + // snippet-end:[personalize.java2.get_personalized_ranking.main] } \ No newline at end of file diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/GetRecommendations.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/GetRecommendations.java index 8a430fd3abb..bf5afd396db 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/GetRecommendations.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/GetRecommendations.java @@ -1,15 +1,9 @@ -//snippet-sourcedescription:[GetRecommendations.java demonstrates how to return a list of recommended items.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Personalize] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.get_recommendations.import] +// snippet-start:[personalize.java2.get_recommendations.import] import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalizeruntime.PersonalizeRuntimeClient; @@ -17,10 +11,11 @@ import software.amazon.awssdk.services.personalizeruntime.model.GetRecommendationsResponse; import software.amazon.awssdk.services.personalizeruntime.model.PredictedItem; import java.util.List; -//snippet-end:[personalize.java2.get_recommendations.import] +// snippet-end:[personalize.java2.get_recommendations.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -32,13 +27,13 @@ public static void main(String[] args) { final String USAGE = """ - Usage: - GetRecommendations + Usage: + GetRecommendations - Where: - campaignArn - The ARN of the campaign. - userId - The user ID to provide recommendations for - """; + Where: + campaignArn - The ARN of the campaign. + userId - The user ID to provide recommendations for + """; if (args.length < 2) { System.out.println(USAGE); @@ -49,28 +44,29 @@ public static void main(String[] args) { String userId = args[1]; Region region = Region.US_EAST_1; PersonalizeRuntimeClient personalizeRuntimeClient = PersonalizeRuntimeClient.builder() - .region(region) - .build(); + .region(region) + .build(); getRecs(personalizeRuntimeClient, campaignArn, userId); personalizeRuntimeClient.close(); } - //snippet-start:[personalize.java2.get_recommendations.main] - public static void getRecs(PersonalizeRuntimeClient personalizeRuntimeClient, String campaignArn, String userId){ + // snippet-start:[personalize.java2.get_recommendations.main] + public static void getRecs(PersonalizeRuntimeClient personalizeRuntimeClient, String campaignArn, String userId) { try { GetRecommendationsRequest recommendationsRequest = GetRecommendationsRequest.builder() - .campaignArn(campaignArn) - .numResults(20) - .userId(userId) - .build(); + .campaignArn(campaignArn) + .numResults(20) + .userId(userId) + .build(); - GetRecommendationsResponse recommendationsResponse = personalizeRuntimeClient.getRecommendations(recommendationsRequest); + GetRecommendationsResponse recommendationsResponse = personalizeRuntimeClient + .getRecommendations(recommendationsRequest); List items = recommendationsResponse.itemList(); - for (PredictedItem item: items) { - System.out.println("Item Id is : "+item.itemId()); - System.out.println("Item score is : "+item.score()); + for (PredictedItem item : items) { + System.out.println("Item Id is : " + item.itemId()); + System.out.println("Item score is : " + item.score()); } } catch (AwsServiceException e) { @@ -78,5 +74,5 @@ public static void getRecs(PersonalizeRuntimeClient personalizeRuntimeClient, St System.exit(1); } } - //snippet-end:[personalize.java2.get_recommendations.main] + // snippet-end:[personalize.java2.get_recommendations.main] } \ No newline at end of file diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/GetRecommendationsFromRecommender.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/GetRecommendationsFromRecommender.java index 4d441d36594..6e5752ec05b 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/GetRecommendationsFromRecommender.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/GetRecommendationsFromRecommender.java @@ -1,20 +1,9 @@ -//snippet-sourcedescription:[GetRecommendations.java demonstrates how to return a list of recommended items -// from a recommender created in a domain dataset group.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon Personalize] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[1/6/22] -//snippet-sourceauthor:[seashman - AWS] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.get_recommendations_from_recommender.import] +// snippet-start:[personalize.java2.get_recommendations_from_recommender.import] import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalizeruntime.PersonalizeRuntimeClient; @@ -22,10 +11,11 @@ import software.amazon.awssdk.services.personalizeruntime.model.GetRecommendationsResponse; import software.amazon.awssdk.services.personalizeruntime.model.PredictedItem; import java.util.List; -//snippet-end:[personalize.java2.get_recommendations_from_recommender.import] +// snippet-end:[personalize.java2.get_recommendations_from_recommender.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -37,13 +27,13 @@ public static void main(String[] args) { final String USAGE = """ - Usage: - GetRecommendations + Usage: + GetRecommendations - Where: - recommenderArn - The ARN of the recommender. - userId - The user ID to provide recommendations for - """; + Where: + recommenderArn - The ARN of the recommender. + userId - The user ID to provide recommendations for + """; if (args.length < 2) { System.out.println(USAGE); @@ -60,8 +50,10 @@ public static void main(String[] args) { getRecs(personalizeRuntimeClient, recommenderArn, userId); personalizeRuntimeClient.close(); } - //snippet-start:[personalize.java2.get_recommendations_from_recommender.main] - public static void getRecs(PersonalizeRuntimeClient personalizeRuntimeClient, String recommenderArn, String userId){ + + // snippet-start:[personalize.java2.get_recommendations_from_recommender.main] + public static void getRecs(PersonalizeRuntimeClient personalizeRuntimeClient, String recommenderArn, + String userId) { try { GetRecommendationsRequest recommendationsRequest = GetRecommendationsRequest.builder() @@ -70,17 +62,18 @@ public static void getRecs(PersonalizeRuntimeClient personalizeRuntimeClient, St .userId(userId) .build(); - GetRecommendationsResponse recommendationsResponse = personalizeRuntimeClient.getRecommendations(recommendationsRequest); + GetRecommendationsResponse recommendationsResponse = personalizeRuntimeClient + .getRecommendations(recommendationsRequest); List items = recommendationsResponse.itemList(); - for (PredictedItem item: items) { - System.out.println("Item Id is : "+item.itemId()); - System.out.println("Item score is : "+item.score()); + for (PredictedItem item : items) { + System.out.println("Item Id is : " + item.itemId()); + System.out.println("Item score is : " + item.score()); } } catch (AwsServiceException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } - //snippet-end:[personalize.java2.get_recommendations_from_recommender.main] + // snippet-end:[personalize.java2.get_recommendations_from_recommender.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/ListCampaigns.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/ListCampaigns.java index 21755f96b7f..3b3d02cb1be 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/ListCampaigns.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/ListCampaigns.java @@ -1,14 +1,9 @@ -//snippet-sourcedescription:[ListCampaigns.java demonstrates how to list Amazon Personalize campaigns.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Personalize] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.personalize; -//snippet-start:[personalize.java2.list_campaigns.import] +// snippet-start:[personalize.java2.list_campaigns.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; import software.amazon.awssdk.services.personalize.model.CampaignSummary; @@ -16,10 +11,11 @@ import software.amazon.awssdk.services.personalize.model.ListCampaignsResponse; import software.amazon.awssdk.services.personalize.model.PersonalizeException; import java.util.List; -//snippet-end:[personalize.java2.list_campaigns.import] +// snippet-end:[personalize.java2.list_campaigns.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -31,13 +27,13 @@ public static void main(String[] args) { final String USAGE = """ - Usage: - ListCampaigns + Usage: + ListCampaigns - Where: - solutionArn - The ARN of the solution. + Where: + solutionArn - The ARN of the solution. - """; + """; if (args.length != 1) { System.out.println(USAGE); @@ -47,27 +43,27 @@ public static void main(String[] args) { String solutionArn = args[0]; Region region = Region.US_EAST_1; PersonalizeClient personalizeClient = PersonalizeClient.builder() - .region(region) - .build(); + .region(region) + .build(); listAllCampaigns(personalizeClient, solutionArn); personalizeClient.close(); } - //snippet-start:[personalize.java2.list_campaigns.main] + // snippet-start:[personalize.java2.list_campaigns.main] public static void listAllCampaigns(PersonalizeClient personalizeClient, String solutionArn) { - try{ + try { ListCampaignsRequest campaignsRequest = ListCampaignsRequest.builder() - .maxResults(10) - .solutionArn(solutionArn) - .build(); + .maxResults(10) + .solutionArn(solutionArn) + .build(); ListCampaignsResponse response = personalizeClient.listCampaigns(campaignsRequest); List campaigns = response.campaigns(); - for (CampaignSummary campaign: campaigns) { - System.out.println("Campaign name is : "+campaign.name()); - System.out.println("Campaign ARN is : "+campaign.campaignArn()); + for (CampaignSummary campaign : campaigns) { + System.out.println("Campaign name is : " + campaign.name()); + System.out.println("Campaign ARN is : " + campaign.campaignArn()); } } catch (PersonalizeException e) { @@ -75,5 +71,5 @@ public static void listAllCampaigns(PersonalizeClient personalizeClient, String System.exit(1); } } - //snippet-end:[personalize.java2.list_campaigns.main] + // snippet-end:[personalize.java2.list_campaigns.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/ListDatasetGroups.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/ListDatasetGroups.java index efd5e71af08..f607572cb8c 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/ListDatasetGroups.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/ListDatasetGroups.java @@ -1,15 +1,9 @@ -//snippet-sourcedescription:[ListDatasetGroups.java demonstrates how to list Amazon Personalize data set groups.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Personalize] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.list_dsgroups.import] +// snippet-start:[personalize.java2.list_dsgroups.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; import software.amazon.awssdk.services.personalize.model.ListDatasetGroupsRequest; @@ -17,10 +11,11 @@ import software.amazon.awssdk.services.personalize.model.DatasetGroupSummary; import software.amazon.awssdk.services.personalize.model.PersonalizeException; import java.util.List; -//snippet-end:[personalize.java2.list_dsgroups.import] +// snippet-end:[personalize.java2.list_dsgroups.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -31,26 +26,26 @@ public class ListDatasetGroups { public static void main(String[] args) { Region region = Region.US_EAST_1; PersonalizeClient personalizeClient = PersonalizeClient.builder() - .region(region) - .build(); + .region(region) + .build(); listDSGroups(personalizeClient); personalizeClient.close(); } - //snippet-start:[personalize.java2.list_dsgroups.main] - public static void listDSGroups( PersonalizeClient personalizeClient ) { + // snippet-start:[personalize.java2.list_dsgroups.main] + public static void listDSGroups(PersonalizeClient personalizeClient) { try { ListDatasetGroupsRequest groupsRequest = ListDatasetGroupsRequest.builder() - .maxResults(15) - .build(); + .maxResults(15) + .build(); ListDatasetGroupsResponse groupsResponse = personalizeClient.listDatasetGroups(groupsRequest); List groups = groupsResponse.datasetGroups(); - for (DatasetGroupSummary group: groups) { - System.out.println("The DataSet name is : "+group.name()); - System.out.println("The DataSet ARN is : "+group.datasetGroupArn()); + for (DatasetGroupSummary group : groups) { + System.out.println("The DataSet name is : " + group.name()); + System.out.println("The DataSet ARN is : " + group.datasetGroupArn()); } } catch (PersonalizeException e) { @@ -58,5 +53,5 @@ public static void listDSGroups( PersonalizeClient personalizeClient ) { System.exit(1); } } - //snippet-end:[personalize.java2.list_dsgroups.main] + // snippet-end:[personalize.java2.list_dsgroups.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/ListRecipes.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/ListRecipes.java index e0bfe222e7d..84115110578 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/ListRecipes.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/ListRecipes.java @@ -1,15 +1,9 @@ -//snippet-sourcedescription:[ListRecipes.java demonstrates how to list Amazon Personalize recipes.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Personalize] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.list_recipes.import] +// snippet-start:[personalize.java2.list_recipes.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; import software.amazon.awssdk.services.personalize.model.ListRecipesRequest; @@ -17,10 +11,11 @@ import software.amazon.awssdk.services.personalize.model.PersonalizeException; import software.amazon.awssdk.services.personalize.model.RecipeSummary; import java.util.List; -//snippet-end:[personalize.java2.list_recipes.import] +// snippet-end:[personalize.java2.list_recipes.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -31,26 +26,26 @@ public class ListRecipes { public static void main(String[] args) { Region region = Region.US_EAST_1; PersonalizeClient personalizeClient = PersonalizeClient.builder() - .region(region) - .build(); + .region(region) + .build(); listAllRecipes(personalizeClient); personalizeClient.close(); } - //snippet-start:[personalize.java2.list_recipes.main] + // snippet-start:[personalize.java2.list_recipes.main] public static void listAllRecipes(PersonalizeClient personalizeClient) { try { ListRecipesRequest recipesRequest = ListRecipesRequest.builder() - .maxResults(15) - .build(); + .maxResults(15) + .build(); ListRecipesResponse response = personalizeClient.listRecipes(recipesRequest); List recipes = response.recipes(); - for (RecipeSummary recipe: recipes) { - System.out.println("The recipe ARN is: "+recipe.recipeArn()); - System.out.println("The recipe name is: "+recipe.name()); + for (RecipeSummary recipe : recipes) { + System.out.println("The recipe ARN is: " + recipe.recipeArn()); + System.out.println("The recipe name is: " + recipe.name()); } } catch (PersonalizeException e) { @@ -58,5 +53,5 @@ public static void listAllRecipes(PersonalizeClient personalizeClient) { System.exit(1); } } - //snippet-end:[personalize.java2.list_recipes.main] + // snippet-end:[personalize.java2.list_recipes.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/ListSolutions.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/ListSolutions.java index 6f87da9de96..1b3a302b66e 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/ListSolutions.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/ListSolutions.java @@ -1,15 +1,9 @@ -//snippet-sourcedescription:[ListSolutions.java demonstrates how to list Amazon Personalize solutions.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Personalize] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.list_solutions.import] +// snippet-start:[personalize.java2.list_solutions.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; import software.amazon.awssdk.services.personalize.model.ListSolutionsRequest; @@ -17,10 +11,11 @@ import software.amazon.awssdk.services.personalize.model.SolutionSummary; import software.amazon.awssdk.services.personalize.model.PersonalizeException; import java.util.List; -//snippet-end:[personalize.java2.list_solutions.import] +// snippet-end:[personalize.java2.list_solutions.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -32,13 +27,13 @@ public static void main(String[] args) { final String USAGE = """ - Usage: - ListSolutions + Usage: + ListSolutions - Where: - datasetGroupArn - The ARN of the data set group. + Where: + datasetGroupArn - The ARN of the data set group. - """; + """; if (args.length < 1) { System.out.println(USAGE); @@ -48,26 +43,27 @@ public static void main(String[] args) { String datasetGroupArn = args[0]; Region region = Region.US_EAST_1; PersonalizeClient personalizeClient = PersonalizeClient.builder() - .region(region) - .build(); + .region(region) + .build(); listAllSolutions(personalizeClient, datasetGroupArn); personalizeClient.close(); } - //snippet-start:[personalize.java2.list_solutions.main] + + // snippet-start:[personalize.java2.list_solutions.main] public static void listAllSolutions(PersonalizeClient personalizeClient, String datasetGroupArn) { try { ListSolutionsRequest solutionsRequest = ListSolutionsRequest.builder() - .maxResults(10) - .datasetGroupArn(datasetGroupArn) - .build() ; + .maxResults(10) + .datasetGroupArn(datasetGroupArn) + .build(); ListSolutionsResponse response = personalizeClient.listSolutions(solutionsRequest); List solutions = response.solutions(); - for (SolutionSummary solution: solutions) { - System.out.println("The solution ARN is: "+solution.solutionArn()); - System.out.println("The solution name is: "+solution.name()); + for (SolutionSummary solution : solutions) { + System.out.println("The solution ARN is: " + solution.solutionArn()); + System.out.println("The solution name is: " + solution.name()); } } catch (PersonalizeException e) { @@ -75,5 +71,5 @@ public static void listAllSolutions(PersonalizeClient personalizeClient, String System.exit(1); } } - //snippet-end:[personalize.java2.list_solutions.main] + // snippet-end:[personalize.java2.list_solutions.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/PutEvents.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/PutEvents.java index 1a201506a03..ea19ab69536 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/PutEvents.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/PutEvents.java @@ -1,19 +1,9 @@ -//snippet-sourcedescription:[PutEvents.java demonstrates how to import real-time event data into Amazon Personalize.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon Personalize] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[5/19/2021] -//snippet-sourceauthor:[seashman - AWS] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.put_events.import] +// snippet-start:[personalize.java2.put_events.import] import java.time.Instant; import java.util.ArrayList; @@ -26,22 +16,22 @@ import software.amazon.awssdk.services.personalizeevents.model.PersonalizeEventsException; import software.amazon.awssdk.services.personalizeevents.model.PutEventsRequest; -//snippet-end:[personalize.java2.put_events.import] +// snippet-end:[personalize.java2.put_events.import] public class PutEvents { public static void main(String[] args) { final String USAGE = """ - Usage: - PutEvents + Usage: + PutEvents - Where: - trackingId - The identification number of the dataset group's event tracker.The ID is generated by a call to the CreateEventTracker API. - userId -The user associated with the event. - sessionId - The session ID associated with the user's visit. Your application generates the sessionId when a user first visits your website or uses your application. - itemId - The item's identification number. + Where: + trackingId - The identification number of the dataset group's event tracker.The ID is generated by a call to the CreateEventTracker API. + userId -The user associated with the event. + sessionId - The session ID associated with the user's visit. Your application generates the sessionId when a user first visits your website or uses your application. + itemId - The item's identification number. - """; + """; if (args.length != 4) { System.out.println(USAGE); @@ -65,18 +55,19 @@ public static void main(String[] args) { personalizeEventsClient.close(); } - //snippet-start:[personalize.java2.put_events.main] + // snippet-start:[personalize.java2.put_events.main] public static int putEvents(PersonalizeEventsClient personalizeEventsClient, - String trackingId, - String userId, - String itemId, - String sessionId) { + String trackingId, + String userId, + String itemId, + String sessionId) { int responseCode = 0; try { - // Build an event and a putEvents request with only the required information for a minimal schema. + // Build an event and a putEvents request with only the required information for + // a minimal schema. // Schema columns for this example would be itemId, userId, and timestamp. Event event = Event.builder() .sentAt(Instant.ofEpochMilli(System.currentTimeMillis() + 10 * 60 * 1000)) @@ -100,5 +91,5 @@ public static int putEvents(PersonalizeEventsClient personalizeEventsClient, } return responseCode; } - //snippet-end:[personalize.java2.put_events.main] + // snippet-end:[personalize.java2.put_events.main] } diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/PutItems.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/PutItems.java index 043a1e38404..4f5c74d2342 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/PutItems.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/PutItems.java @@ -1,19 +1,9 @@ -//snippet-sourcedescription:[PutItems.java demonstrates how to incrementally import items into Amazon Personalize.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon Personalize] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[7/13/2021] -//snippet-sourceauthor:[seashman - AWS] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.put_items.import] +// snippet-start:[personalize.java2.put_items.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalizeevents.PersonalizeEventsClient; @@ -23,10 +13,11 @@ import java.util.ArrayList; -//snippet-end:[personalize.java2.put_items.import] +// snippet-end:[personalize.java2.put_items.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -34,95 +25,94 @@ */ public class PutItems { - public static void main(String[] args) { - final String USAGE = """ - - Usage: - PutItems - - Where: - datasetArn - The ARN (Amazon Resource Name) for the item's destination dataset. - item1Id - The identification number of the first item. - item1propertyName - The metadata field name (in camel case) for the first item. - item1propertyValue - The metadata value for the first item. - item2Id - The identification number of the second item. - item2propertyName - The metadata field name (in camel case) for the second item. - item2propertyValue - The metadata value for the second item. - - """; - - if (args.length != 7) { - System.out.println(USAGE); - System.exit(1); + public static void main(String[] args) { + final String USAGE = """ + + Usage: + PutItems + + Where: + datasetArn - The ARN (Amazon Resource Name) for the item's destination dataset. + item1Id - The identification number of the first item. + item1propertyName - The metadata field name (in camel case) for the first item. + item1propertyValue - The metadata value for the first item. + item2Id - The identification number of the second item. + item2propertyName - The metadata field name (in camel case) for the second item. + item2propertyValue - The metadata value for the second item. + + """; + + if (args.length != 7) { + System.out.println(USAGE); + System.exit(1); + } + + String datasetArn = args[0]; + String item1Id = args[1]; + String item1PropertyName = args[2]; + String item1PropertyValue = args[3]; + String item2Id = args[4]; + String item2PropertyName = args[5]; + String item2PropertyValue = args[6]; + + // Change to the region where your resources are located + Region region = Region.US_WEST_2; + + // Build a personalize events client + PersonalizeEventsClient personalizeEventsClient = PersonalizeEventsClient.builder() + .region(region) + .build(); + int response = putItems(personalizeEventsClient, datasetArn, item1Id, + item1PropertyName, item1PropertyValue, item2Id, item2PropertyName, item2PropertyValue); + System.out.println("Response code: " + response); + personalizeEventsClient.close(); } - String datasetArn = args[0]; - String item1Id = args[1]; - String item1PropertyName = args[2]; - String item1PropertyValue = args[3]; - String item2Id = args[4]; - String item2PropertyName = args[5]; - String item2PropertyValue = args[6]; - - // Change to the region where your resources are located - Region region = Region.US_WEST_2; - - // Build a personalize events client - PersonalizeEventsClient personalizeEventsClient = PersonalizeEventsClient.builder() - .region(region) - .build(); - int response = putItems(personalizeEventsClient, datasetArn, item1Id, - item1PropertyName, item1PropertyValue, item2Id, item2PropertyName, item2PropertyValue); - System.out.println("Response code: " + response); - personalizeEventsClient.close(); - } - - //snippet-start:[personalize.java2.put_items.main] - public static int putItems(PersonalizeEventsClient personalizeEventsClient, - String datasetArn, - String item1Id, - String item1PropertyName, - String item1PropertyValue, - String item2Id, - String item2PropertyName, - String item2PropertyValue) { - - int responseCode = 0; - ArrayList items = new ArrayList<>(); - - try { - Item item1 = Item.builder() - .itemId(item1Id) - .properties(String.format("{\"%1$s\": \"%2$s\"}", - item1PropertyName, item1PropertyValue)) - .build(); - - items.add(item1); - - Item item2 = Item.builder() - .itemId(item2Id) - .properties(String.format("{\"%1$s\": \"%2$s\"}", - item2PropertyName, item2PropertyValue)) - .build(); - - items.add(item2); - - PutItemsRequest putItemsRequest = PutItemsRequest.builder() - .datasetArn(datasetArn) - .items(items) - .build(); - - responseCode = personalizeEventsClient.putItems(putItemsRequest).sdkHttpResponse().statusCode(); - System.out.println("Response code: " + responseCode); - return responseCode; - - } catch (PersonalizeEventsException e) { - System.out.println(e.awsErrorDetails().errorMessage()); + // snippet-start:[personalize.java2.put_items.main] + public static int putItems(PersonalizeEventsClient personalizeEventsClient, + String datasetArn, + String item1Id, + String item1PropertyName, + String item1PropertyValue, + String item2Id, + String item2PropertyName, + String item2PropertyValue) { + + int responseCode = 0; + ArrayList items = new ArrayList<>(); + + try { + Item item1 = Item.builder() + .itemId(item1Id) + .properties(String.format("{\"%1$s\": \"%2$s\"}", + item1PropertyName, item1PropertyValue)) + .build(); + + items.add(item1); + + Item item2 = Item.builder() + .itemId(item2Id) + .properties(String.format("{\"%1$s\": \"%2$s\"}", + item2PropertyName, item2PropertyValue)) + .build(); + + items.add(item2); + + PutItemsRequest putItemsRequest = PutItemsRequest.builder() + .datasetArn(datasetArn) + .items(items) + .build(); + + responseCode = personalizeEventsClient.putItems(putItemsRequest).sdkHttpResponse().statusCode(); + System.out.println("Response code: " + responseCode); + return responseCode; + + } catch (PersonalizeEventsException e) { + System.out.println(e.awsErrorDetails().errorMessage()); + } + return responseCode; } - return responseCode; - } - //snippet-end:[personalize.java2.put_items.main] + // snippet-end:[personalize.java2.put_items.main] } - diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/PutUsers.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/PutUsers.java index 770d78af6a0..7bddf255efd 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/PutUsers.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/PutUsers.java @@ -1,19 +1,9 @@ -//snippet-sourcedescription:[PutUsers.java demonstrates how to incrementally import users into Amazon Personalize.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon Personalize] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[5/26/2021] -//snippet-sourceauthor:[seashman - AWS] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.put_users.import] +// snippet-start:[personalize.java2.put_users.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalizeevents.PersonalizeEventsClient; @@ -23,10 +13,11 @@ import java.util.ArrayList; -//snippet-end:[personalize.java2.put_users.import] +// snippet-end:[personalize.java2.put_users.import] /** - * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials. + * To run this Java V2 code example, ensure that you have setup your development + * environment, including your credentials. * * For information, see this documentation topic: * @@ -35,96 +26,95 @@ public class PutUsers { - public static void main(String[] args) { - final String USAGE = """ - - Usage: - PutUsers - - Where: - datasetArn - The ARN (Amazon Resource Name) for the user's destination dataset. - user1Id - The identification number of the first user. - user1propertyName - The metadata field name (in camel case) for the first user. - user1propertyValue - The metadata value for the first user. - user2Id - The identification number of the second user. - user2propertyName - The metadata field name (in camel case) for the second user. - user2propertyValue - The metadata value for the second user. - - """; - - if (args.length != 7) { - System.out.println(USAGE); - System.exit(1); + public static void main(String[] args) { + final String USAGE = """ + + Usage: + PutUsers + + Where: + datasetArn - The ARN (Amazon Resource Name) for the user's destination dataset. + user1Id - The identification number of the first user. + user1propertyName - The metadata field name (in camel case) for the first user. + user1propertyValue - The metadata value for the first user. + user2Id - The identification number of the second user. + user2propertyName - The metadata field name (in camel case) for the second user. + user2propertyValue - The metadata value for the second user. + + """; + + if (args.length != 7) { + System.out.println(USAGE); + System.exit(1); + } + + String datasetArn = args[0]; + String user1Id = args[1]; + String user1PropertyName = args[2]; + String user1PropertyValue = args[3]; + String user2Id = args[4]; + String user2PropertyName = args[5]; + String user2PropertyValue = args[6]; + + // Change to the region where your resources are located + Region region = Region.US_WEST_2; + + // Build a personalize events client + PersonalizeEventsClient personalizeEventsClient = PersonalizeEventsClient.builder() + .region(region) + .build(); + int response = putUsers(personalizeEventsClient, datasetArn, + user1Id, user1PropertyName, user1PropertyValue, + user2Id, user2PropertyName, user2PropertyValue); + System.out.println("Response code: " + response); + personalizeEventsClient.close(); } - String datasetArn = args[0]; - String user1Id = args[1]; - String user1PropertyName = args[2]; - String user1PropertyValue = args[3]; - String user2Id = args[4]; - String user2PropertyName = args[5]; - String user2PropertyValue = args[6]; - - // Change to the region where your resources are located - Region region = Region.US_WEST_2; - - // Build a personalize events client - PersonalizeEventsClient personalizeEventsClient = PersonalizeEventsClient.builder() - .region(region) - .build(); - int response = putUsers(personalizeEventsClient, datasetArn, - user1Id, user1PropertyName, user1PropertyValue, - user2Id, user2PropertyName, user2PropertyValue); - System.out.println("Response code: " + response); - personalizeEventsClient.close(); - } - - //snippet-start:[personalize.java2.put_users.main] - public static int putUsers(PersonalizeEventsClient personalizeEventsClient, - String datasetArn, - String user1Id, - String user1PropertyName, - String user1PropertyValue, - String user2Id, - String user2PropertyName, - String user2PropertyValue) { - - int responseCode = 0; - ArrayList users = new ArrayList<>(); - - try { - User user1 = User.builder() - .userId(user1Id) - .properties(String.format("{\"%1$s\": \"%2$s\"}", - user1PropertyName, user1PropertyValue)) - .build(); - - users.add(user1); - - User user2 = User.builder() - .userId(user2Id) - .properties(String.format("{\"%1$s\": \"%2$s\"}", - user2PropertyName, user2PropertyValue)) - .build(); - - users.add(user2); - - PutUsersRequest putUsersRequest = PutUsersRequest.builder() - .datasetArn(datasetArn) - .users(users) - .build(); - - responseCode = personalizeEventsClient.putUsers(putUsersRequest).sdkHttpResponse().statusCode(); - System.out.println("Response code: " + responseCode); - return responseCode; - - } catch (PersonalizeEventsException e) { - System.out.println(e.awsErrorDetails().errorMessage()); + // snippet-start:[personalize.java2.put_users.main] + public static int putUsers(PersonalizeEventsClient personalizeEventsClient, + String datasetArn, + String user1Id, + String user1PropertyName, + String user1PropertyValue, + String user2Id, + String user2PropertyName, + String user2PropertyValue) { + + int responseCode = 0; + ArrayList users = new ArrayList<>(); + + try { + User user1 = User.builder() + .userId(user1Id) + .properties(String.format("{\"%1$s\": \"%2$s\"}", + user1PropertyName, user1PropertyValue)) + .build(); + + users.add(user1); + + User user2 = User.builder() + .userId(user2Id) + .properties(String.format("{\"%1$s\": \"%2$s\"}", + user2PropertyName, user2PropertyValue)) + .build(); + + users.add(user2); + + PutUsersRequest putUsersRequest = PutUsersRequest.builder() + .datasetArn(datasetArn) + .users(users) + .build(); + + responseCode = personalizeEventsClient.putUsers(putUsersRequest).sdkHttpResponse().statusCode(); + System.out.println("Response code: " + responseCode); + return responseCode; + + } catch (PersonalizeEventsException e) { + System.out.println(e.awsErrorDetails().errorMessage()); + } + return responseCode; } - return responseCode; - } - //snippet-end:[personalize.java2.put_users.main] + // snippet-end:[personalize.java2.put_users.main] } - diff --git a/javav2/example_code/personalize/src/main/java/com/example/personalize/UpdateCampaign.java b/javav2/example_code/personalize/src/main/java/com/example/personalize/UpdateCampaign.java index f21df4f51ae..af81f27a255 100644 --- a/javav2/example_code/personalize/src/main/java/com/example/personalize/UpdateCampaign.java +++ b/javav2/example_code/personalize/src/main/java/com/example/personalize/UpdateCampaign.java @@ -1,19 +1,9 @@ -//snippet-sourcedescription:[UpdateCampaign.java demonstrates how to update an Amazon Personalize campaign.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon Personalize] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[7/13/2021] -//snippet-sourceauthor:[seashman - AWS] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.personalize; -//snippet-start:[personalize.java2.update_campaign.import] +// snippet-start:[personalize.java2.update_campaign.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.personalize.PersonalizeClient; import software.amazon.awssdk.services.personalize.model.Campaign; @@ -21,20 +11,20 @@ import software.amazon.awssdk.services.personalize.model.UpdateCampaignRequest; import software.amazon.awssdk.services.personalize.model.DescribeCampaignRequest; import software.amazon.awssdk.services.personalize.model.DescribeCampaignResponse; -//snippet-end:[personalize.java2.update_campaign.import] +// snippet-end:[personalize.java2.update_campaign.import] public class UpdateCampaign { public static void main(String[] args) { final String USAGE = """ - Usage: - UpdateCampaign + Usage: + UpdateCampaign - Where: - campaignArn - The Amazon Resource Name (ARN) of the campaign to update. - solutionVersion - The Amazon Resource Name (ARN) of the new solution version to deploy. - minProvisionedTPS - Specifies the requested minimum provisioned transactions(recommendations) per second that Amazon Personalize will support. - """; + Where: + campaignArn - The Amazon Resource Name (ARN) of the campaign to update. + solutionVersion - The Amazon Resource Name (ARN) of the new solution version to deploy. + minProvisionedTPS - Specifies the requested minimum provisioned transactions(recommendations) per second that Amazon Personalize will support. + """; if (args.length != 3) { System.out.println(USAGE); @@ -45,8 +35,7 @@ public static void main(String[] args) { String solutionVersionArn = args[1]; Integer minProvisionedTPS = Integer.parseInt(args[2]); - - //Change the region to the region where your resources are located. + // Change the region to the region where your resources are located. Region region = Region.US_WEST_2; // Build a personalize client @@ -58,11 +47,11 @@ public static void main(String[] args) { personalizeClient.close(); } - //snippet-start:[personalize.java2.update_campaign.main] + // snippet-start:[personalize.java2.update_campaign.main] public static String updateCampaign(PersonalizeClient personalizeClient, - String campaignArn, - String solutionVersionArn, - Integer minProvisionedTPS) { + String campaignArn, + String solutionVersionArn, + Integer minProvisionedTPS) { try { // build the updateCampaignRequest @@ -91,6 +80,6 @@ public static String updateCampaign(PersonalizeClient personalizeClient, } return ""; } - //snippet-end:[personalize.java2.update_campaign.main] + // snippet-end:[personalize.java2.update_campaign.main] } \ No newline at end of file diff --git a/javav2/example_code/personalize/src/test/java/PersonalizeDomainTest.java b/javav2/example_code/personalize/src/test/java/PersonalizeDomainTest.java index f27816af766..0e846b75a15 100644 --- a/javav2/example_code/personalize/src/test/java/PersonalizeDomainTest.java +++ b/javav2/example_code/personalize/src/test/java/PersonalizeDomainTest.java @@ -1,174 +1,176 @@ -import com.example.personalize.CreateDataset; -import com.example.personalize.CreateDatasetImportJob; -import com.example.personalize.CreateDomainDatasetGroup; -import com.example.personalize.CreateDomainSchema; -import com.example.personalize.CreateRecommender; -import com.example.personalize.GetRecommendationsFromRecommender; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Order; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; -import org.junit.jupiter.api.TestMethodOrder; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.personalize.PersonalizeClient; -import software.amazon.awssdk.services.personalizeevents.PersonalizeEventsClient; -import software.amazon.awssdk.services.personalizeruntime.PersonalizeRuntimeClient; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -import static org.junit.jupiter.api.Assertions.*; - -@TestInstance(TestInstance.Lifecycle.PER_METHOD) -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) -public class PersonalizeDomainTest { - - private static PersonalizeRuntimeClient personalizeRuntimeClient; - private static PersonalizeClient personalizeClient; - private static PersonalizeEventsClient personalizeEventsClient; - - - private static String createDomainDatasetGroupName = ""; - private static String createDomainDatasetGroupDomain = ""; - - private static String createDomainSchemaName = ""; - private static String createDomainSchemaDomain = ""; - private static String createDomainSchemaLocation = ""; - - private static String newDatasetSchemaArn = ""; - private static String newDatasetName = ""; - private static String newDatasetType = ""; - private static String newDatasetDestinationDatasetGroupArn = ""; - - - private static String importJobDatasetArn = ""; - private static String domainDatasetImportJobName = ""; - private static String domainS3BucketPath = ""; - private static String domainRoleArn = ""; - - private static String createRecommenderName = ""; - private static String createRecommenderRecipeArn = ""; - private static String createRecommenderDatasetGroupArn = ""; - - private static String getRecommendationsRecommenderArn = ""; - private static String getRecommendationsUserId = ""; - - @BeforeAll - public static void setUp() throws IOException { - - //Change to the region where your Amazon Personalize resources are located. - Region region = Region.US_WEST_2; - - personalizeRuntimeClient = PersonalizeRuntimeClient.builder() - .region(region) - .build(); - personalizeClient = PersonalizeClient.builder() - .region(region) - .build(); - personalizeEventsClient = PersonalizeEventsClient.builder() - .region(region) - .build(); - try (InputStream input = PersonalizeDomainTest.class.getClassLoader().getResourceAsStream("domain-dsg-config.properties")) { - - Properties prop = new Properties(); - - if (input == null) { - System.out.println("Unable to find domain-dsg-config.properties"); - return; - } - - //load a properties file from class path, inside static method - prop.load(input); - - // Populate the data members required for all tests - - createDomainDatasetGroupName = prop.getProperty("createDomainDatasetGroupName"); - createDomainDatasetGroupDomain = prop.getProperty("createDomainDatasetGroupDomain"); - - createDomainSchemaName = prop.getProperty("createDomainSchemaName"); - createDomainSchemaDomain = prop.getProperty("createDomainSchemaDomain"); - createDomainSchemaLocation = prop.getProperty("createDomainSchemaLocation"); - - newDatasetName = prop.getProperty("newDatasetName"); - newDatasetType = prop.getProperty("newDatasetType"); - newDatasetSchemaArn = prop.getProperty("newDatasetSchemaArn"); - newDatasetDestinationDatasetGroupArn = prop.getProperty("newDatasetDestinationDatasetGroupArn"); - - domainDatasetImportJobName = prop.getProperty("domainDatasetImportJobName"); - domainS3BucketPath = prop.getProperty("domainS3BucketPath"); - domainRoleArn = prop.getProperty("domainRoleArn"); - importJobDatasetArn = prop.getProperty("importJobDatasetArn"); - - createRecommenderName = prop.getProperty("createRecommenderName"); - createRecommenderRecipeArn = prop.getProperty("createRecommenderRecipeArn"); - createRecommenderDatasetGroupArn = prop.getProperty("recommenderDatasetGroupArn"); - - getRecommendationsUserId = prop.getProperty("getRecommendationsUserId"); - getRecommendationsRecommenderArn = prop.getProperty("getRecommendationsRecommenderArn"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - } - @Test - @Order(1) - public void whenInitializingAWSService_thenNotNull() { - assertNotNull(personalizeRuntimeClient); - assertNotNull(personalizeClient); - assertNotNull(personalizeEventsClient); - System.out.println("Initialize clients test passed"); - } - @Test - @Order(2) - public void CreateDomainDatasetGroup() { - String domainDatasetGroupArn = CreateDomainDatasetGroup.createDomainDatasetGroup(personalizeClient, - createDomainDatasetGroupName, createDomainDatasetGroupDomain); - assertFalse(domainDatasetGroupArn.isEmpty()); - System.out.println("CreateDomainDatasetGroup test passed"); - } - @Test - @Order(3) - public void CreateDomainSchema() { - String domainSchemaArn = CreateDomainSchema.createDomainSchema(personalizeClient, - createDomainSchemaName, createDomainSchemaDomain, createDomainSchemaLocation); - assertFalse(domainSchemaArn.isEmpty()); - System.out.println("CreateDomainSchema test passed"); - } - @Test - @Order(4) - public void CreateDomainDataset() { - String datasetArn = CreateDataset.createDataset(personalizeClient, - newDatasetName, newDatasetDestinationDatasetGroupArn, newDatasetType, newDatasetSchemaArn); - assertFalse(datasetArn.isEmpty()); - System.out.println("CreateDomainDataset test passed"); - } - @Test - @Order(5) - public void CreateDatasetImportJob() { - String datasetImportJobArn = CreateDatasetImportJob.createPersonalizeDatasetImportJob(personalizeClient, - domainDatasetImportJobName, importJobDatasetArn, domainS3BucketPath, domainRoleArn); - assertFalse(datasetImportJobArn.isEmpty()); - System.out.println("CreateDatasetImportJob test passed"); - } - - @Test - @Order(6) - public void CreateRecommender() { - String recommenderArn = CreateRecommender.createRecommender(personalizeClient, - createRecommenderName, createRecommenderDatasetGroupArn, createRecommenderRecipeArn); - assertFalse(recommenderArn.isEmpty()); - System.out.println("CreateRecommender test passed"); - } - @Test - @Order(7) - public void GetRecommendations() { - GetRecommendationsFromRecommender.getRecs(personalizeRuntimeClient, getRecommendationsRecommenderArn, getRecommendationsUserId); - System.out.println("GetRecommendations test passed"); - } - - - - -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +import com.example.personalize.CreateDataset; +import com.example.personalize.CreateDatasetImportJob; +import com.example.personalize.CreateDomainDatasetGroup; +import com.example.personalize.CreateDomainSchema; +import com.example.personalize.CreateRecommender; +import com.example.personalize.GetRecommendationsFromRecommender; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.TestMethodOrder; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.personalize.PersonalizeClient; +import software.amazon.awssdk.services.personalizeevents.PersonalizeEventsClient; +import software.amazon.awssdk.services.personalizeruntime.PersonalizeRuntimeClient; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import static org.junit.jupiter.api.Assertions.*; + +@TestInstance(TestInstance.Lifecycle.PER_METHOD) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +public class PersonalizeDomainTest { + + private static PersonalizeRuntimeClient personalizeRuntimeClient; + private static PersonalizeClient personalizeClient; + private static PersonalizeEventsClient personalizeEventsClient; + + + private static String createDomainDatasetGroupName = ""; + private static String createDomainDatasetGroupDomain = ""; + + private static String createDomainSchemaName = ""; + private static String createDomainSchemaDomain = ""; + private static String createDomainSchemaLocation = ""; + + private static String newDatasetSchemaArn = ""; + private static String newDatasetName = ""; + private static String newDatasetType = ""; + private static String newDatasetDestinationDatasetGroupArn = ""; + + + private static String importJobDatasetArn = ""; + private static String domainDatasetImportJobName = ""; + private static String domainS3BucketPath = ""; + private static String domainRoleArn = ""; + + private static String createRecommenderName = ""; + private static String createRecommenderRecipeArn = ""; + private static String createRecommenderDatasetGroupArn = ""; + + private static String getRecommendationsRecommenderArn = ""; + private static String getRecommendationsUserId = ""; + + @BeforeAll + public static void setUp() throws IOException { + + //Change to the region where your Amazon Personalize resources are located. + Region region = Region.US_WEST_2; + + personalizeRuntimeClient = PersonalizeRuntimeClient.builder() + .region(region) + .build(); + personalizeClient = PersonalizeClient.builder() + .region(region) + .build(); + personalizeEventsClient = PersonalizeEventsClient.builder() + .region(region) + .build(); + try (InputStream input = PersonalizeDomainTest.class.getClassLoader().getResourceAsStream("domain-dsg-config.properties")) { + + Properties prop = new Properties(); + + if (input == null) { + System.out.println("Unable to find domain-dsg-config.properties"); + return; + } + + //load a properties file from class path, inside static method + prop.load(input); + + // Populate the data members required for all tests + + createDomainDatasetGroupName = prop.getProperty("createDomainDatasetGroupName"); + createDomainDatasetGroupDomain = prop.getProperty("createDomainDatasetGroupDomain"); + + createDomainSchemaName = prop.getProperty("createDomainSchemaName"); + createDomainSchemaDomain = prop.getProperty("createDomainSchemaDomain"); + createDomainSchemaLocation = prop.getProperty("createDomainSchemaLocation"); + + newDatasetName = prop.getProperty("newDatasetName"); + newDatasetType = prop.getProperty("newDatasetType"); + newDatasetSchemaArn = prop.getProperty("newDatasetSchemaArn"); + newDatasetDestinationDatasetGroupArn = prop.getProperty("newDatasetDestinationDatasetGroupArn"); + + domainDatasetImportJobName = prop.getProperty("domainDatasetImportJobName"); + domainS3BucketPath = prop.getProperty("domainS3BucketPath"); + domainRoleArn = prop.getProperty("domainRoleArn"); + importJobDatasetArn = prop.getProperty("importJobDatasetArn"); + + createRecommenderName = prop.getProperty("createRecommenderName"); + createRecommenderRecipeArn = prop.getProperty("createRecommenderRecipeArn"); + createRecommenderDatasetGroupArn = prop.getProperty("recommenderDatasetGroupArn"); + + getRecommendationsUserId = prop.getProperty("getRecommendationsUserId"); + getRecommendationsRecommenderArn = prop.getProperty("getRecommendationsRecommenderArn"); + + } catch (IOException ex) { + ex.printStackTrace(); + } + } + @Test + @Order(1) + public void whenInitializingAWSService_thenNotNull() { + assertNotNull(personalizeRuntimeClient); + assertNotNull(personalizeClient); + assertNotNull(personalizeEventsClient); + System.out.println("Initialize clients test passed"); + } + @Test + @Order(2) + public void CreateDomainDatasetGroup() { + String domainDatasetGroupArn = CreateDomainDatasetGroup.createDomainDatasetGroup(personalizeClient, + createDomainDatasetGroupName, createDomainDatasetGroupDomain); + assertFalse(domainDatasetGroupArn.isEmpty()); + System.out.println("CreateDomainDatasetGroup test passed"); + } + @Test + @Order(3) + public void CreateDomainSchema() { + String domainSchemaArn = CreateDomainSchema.createDomainSchema(personalizeClient, + createDomainSchemaName, createDomainSchemaDomain, createDomainSchemaLocation); + assertFalse(domainSchemaArn.isEmpty()); + System.out.println("CreateDomainSchema test passed"); + } + @Test + @Order(4) + public void CreateDomainDataset() { + String datasetArn = CreateDataset.createDataset(personalizeClient, + newDatasetName, newDatasetDestinationDatasetGroupArn, newDatasetType, newDatasetSchemaArn); + assertFalse(datasetArn.isEmpty()); + System.out.println("CreateDomainDataset test passed"); + } + @Test + @Order(5) + public void CreateDatasetImportJob() { + String datasetImportJobArn = CreateDatasetImportJob.createPersonalizeDatasetImportJob(personalizeClient, + domainDatasetImportJobName, importJobDatasetArn, domainS3BucketPath, domainRoleArn); + assertFalse(datasetImportJobArn.isEmpty()); + System.out.println("CreateDatasetImportJob test passed"); + } + + @Test + @Order(6) + public void CreateRecommender() { + String recommenderArn = CreateRecommender.createRecommender(personalizeClient, + createRecommenderName, createRecommenderDatasetGroupArn, createRecommenderRecipeArn); + assertFalse(recommenderArn.isEmpty()); + System.out.println("CreateRecommender test passed"); + } + @Test + @Order(7) + public void GetRecommendations() { + GetRecommendationsFromRecommender.getRecs(personalizeRuntimeClient, getRecommendationsRecommenderArn, getRecommendationsUserId); + System.out.println("GetRecommendations test passed"); + } + + + + +} diff --git a/javav2/example_code/personalize/src/test/java/PersonalizeTest.java b/javav2/example_code/personalize/src/test/java/PersonalizeTest.java index 5bc5c3f7428..8d327e0d6d3 100644 --- a/javav2/example_code/personalize/src/test/java/PersonalizeTest.java +++ b/javav2/example_code/personalize/src/test/java/PersonalizeTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.personalize.*; import com.google.gson.Gson; @@ -25,7 +23,7 @@ public class PersonalizeTest { private static PersonalizeRuntimeClient personalizeRuntimeClient; - private static PersonalizeClient personalizeClient; + private static PersonalizeClient personalizeClient; private static String datasetGroupArn = ""; private static String solutionArn = ""; private static String existingSolutionArn = ""; @@ -35,19 +33,19 @@ public class PersonalizeTest { private static String campaignName = ""; private static String campaignArn = ""; private static String userId = ""; - private static String existingCampaignName=""; + private static String existingCampaignName = ""; @BeforeAll public static void setUp() { personalizeRuntimeClient = PersonalizeRuntimeClient.builder() - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .region(Region.US_EAST_1) - .build(); + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .region(Region.US_EAST_1) + .build(); personalizeClient = PersonalizeClient.builder() - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .region(Region.US_EAST_1) - .build(); + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .region(Region.US_EAST_1) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -56,48 +54,55 @@ public static void setUp() { datasetGroupArn = values.getDatasetGroupArn(); solutionVersionArn = values.getSolutionVersionArn(); recipeArn = values.getRecipeArn(); - solutionName = values.getSolutionName()+ java.util.UUID.randomUUID();; + solutionName = values.getSolutionName() + java.util.UUID.randomUUID(); + ; userId = values.getUserId(); - campaignName= values.getCampaignName()+ java.util.UUID.randomUUID();; - existingSolutionArn= values.getExistingSolutionArn(); + campaignName = values.getCampaignName() + java.util.UUID.randomUUID(); + ; + existingSolutionArn = values.getExistingSolutionArn(); existingCampaignName = values.getExistingCampaignName(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. /* - - try (InputStream input = PersonalizeTest.class.getClassLoader().getResourceAsStream("config.properties")) { - - Properties prop = new Properties(); - - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - //load a properties file from class path, inside static method - prop.load(input); - - // Populate the data members required for all tests - datasetGroupArn = prop.getProperty("datasetGroupArn"); - solutionVersionArn = prop.getProperty("solutionVersionArn"); - recipeArn = prop.getProperty("recipeArn"); - solutionName = prop.getProperty("solutionName")+ java.util.UUID.randomUUID();; - userId = prop.getProperty("userId"); - campaignName= prop.getProperty("campaignName")+ java.util.UUID.randomUUID();; - existingSolutionArn= prop.getProperty("existingSolutionArn"); - existingCampaignName = prop.getProperty("existingCampaignName"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + * + * try (InputStream input = + * PersonalizeTest.class.getClassLoader().getResourceAsStream( + * "config.properties")) { + * + * Properties prop = new Properties(); + * + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * //load a properties file from class path, inside static method + * prop.load(input); + * + * // Populate the data members required for all tests + * datasetGroupArn = prop.getProperty("datasetGroupArn"); + * solutionVersionArn = prop.getProperty("solutionVersionArn"); + * recipeArn = prop.getProperty("recipeArn"); + * solutionName = prop.getProperty("solutionName")+ + * java.util.UUID.randomUUID();; + * userId = prop.getProperty("userId"); + * campaignName= prop.getProperty("campaignName")+ java.util.UUID.randomUUID();; + * existingSolutionArn= prop.getProperty("existingSolutionArn"); + * existingCampaignName = prop.getProperty("existingCampaignName"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @Tag("IntegrationTest") @Order(1) public void CreateSolution() { - solutionArn = CreateSolution.createPersonalizeSolution(personalizeClient, datasetGroupArn, solutionName, recipeArn); + solutionArn = CreateSolution.createPersonalizeSolution(personalizeClient, datasetGroupArn, solutionName, + recipeArn); assertFalse(solutionArn.isEmpty()); System.out.println("Test 1 passed"); } @@ -106,7 +111,7 @@ public void CreateSolution() { @Tag("IntegrationTest") @Order(2) public void ListSolutions() { - assertDoesNotThrow(() ->ListSolutions.listAllSolutions(personalizeClient, datasetGroupArn)); + assertDoesNotThrow(() -> ListSolutions.listAllSolutions(personalizeClient, datasetGroupArn)); System.out.println("Test 2 passed"); } @@ -114,7 +119,7 @@ public void ListSolutions() { @Tag("IntegrationTest") @Order(3) public void DescribeSolution() { - assertDoesNotThrow(() ->DescribeSolution.describeSpecificSolution(personalizeClient, solutionArn)); + assertDoesNotThrow(() -> DescribeSolution.describeSpecificSolution(personalizeClient, solutionArn)); System.out.println("Test 3 passed"); } @@ -132,7 +137,7 @@ public void CreateCampaign() { public void DescribeCampaign() throws InterruptedException { System.out.println("Wait 20 mins for resource to become available."); TimeUnit.MINUTES.sleep(20); - assertDoesNotThrow(() ->DescribeCampaign.describeSpecificCampaign(personalizeClient, campaignArn)); + assertDoesNotThrow(() -> DescribeCampaign.describeSpecificCampaign(personalizeClient, campaignArn)); System.out.println("Test 5 passed"); } @@ -140,7 +145,7 @@ public void DescribeCampaign() throws InterruptedException { @Tag("IntegrationTest") @Order(6) public void ListCampaigns() { - assertDoesNotThrow(() ->ListCampaigns.listAllCampaigns(personalizeClient, existingSolutionArn)); + assertDoesNotThrow(() -> ListCampaigns.listAllCampaigns(personalizeClient, existingSolutionArn)); System.out.println("Test 6 passed"); } @@ -148,7 +153,7 @@ public void ListCampaigns() { @Tag("IntegrationTest") @Order(7) public void DescribeRecipe() { - assertDoesNotThrow(() ->DescribeRecipe.describeSpecificRecipe(personalizeClient, recipeArn)); + assertDoesNotThrow(() -> DescribeRecipe.describeSpecificRecipe(personalizeClient, recipeArn)); System.out.println("Test 7 passed"); } @@ -156,7 +161,7 @@ public void DescribeRecipe() { @Tag("IntegrationTest") @Order(8) public void ListRecipes() { - assertDoesNotThrow(() ->ListRecipes.listAllRecipes(personalizeClient)); + assertDoesNotThrow(() -> ListRecipes.listAllRecipes(personalizeClient)); System.out.println("Test 8 passed"); } @@ -164,7 +169,7 @@ public void ListRecipes() { @Tag("IntegrationTest") @Order(9) public void ListDatasetGroups() { - assertDoesNotThrow(() ->ListDatasetGroups.listDSGroups(personalizeClient)); + assertDoesNotThrow(() -> ListDatasetGroups.listDSGroups(personalizeClient)); System.out.println("Test 9 passed"); } @@ -172,7 +177,7 @@ public void ListDatasetGroups() { @Tag("IntegrationTest") @Order(10) public void DeleteSolution() { - assertDoesNotThrow(() ->DeleteSolution.deleteGivenSolution(personalizeClient,solutionArn)); + assertDoesNotThrow(() -> DeleteSolution.deleteGivenSolution(personalizeClient, solutionArn)); System.out.println("Test 10 passed"); } @@ -180,7 +185,7 @@ public void DeleteSolution() { @Tag("IntegrationTest") @Order(11) public void GetRecommendations() { - assertDoesNotThrow(() ->GetRecommendations.getRecs(personalizeRuntimeClient, campaignArn, userId)); + assertDoesNotThrow(() -> GetRecommendations.getRecs(personalizeRuntimeClient, campaignArn, userId)); System.out.println("Test 11 passed"); } @@ -188,19 +193,20 @@ public void GetRecommendations() { @Tag("IntegrationTest") @Order(12) public void DeleteCampaign() { - assertDoesNotThrow(() ->DeleteCampaign.deleteSpecificCampaign(personalizeClient, campaignArn)); + assertDoesNotThrow(() -> DeleteCampaign.deleteSpecificCampaign(personalizeClient, campaignArn)); System.out.println("Test 12 passed"); } + private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/personalize"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); diff --git a/javav2/example_code/pinpoint/run_example.sh b/javav2/example_code/pinpoint/run_example.sh index c215eeda265..a4ce3e1249a 100644 --- a/javav2/example_code/pinpoint/run_example.sh +++ b/javav2/example_code/pinpoint/run_example.sh @@ -1,4 +1,6 @@ #!/bin/bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 if [[ -z $* ]] ; then echo 'Supply the name of one of the example classes as an argument.' echo 'If there are arguments to the class, put them in quotes after the class name.' diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/AddExampleEndpoints.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/AddExampleEndpoints.java index dfb74e350f8..078947aa038 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/AddExampleEndpoints.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/AddExampleEndpoints.java @@ -1,16 +1,10 @@ -//snippet-sourcedescription:[AddExampleEndpoints.java demonstrates how to update several existing endpoints in a single call to the API.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; -//snippet-start:[pinpoint.java2.update_batch.main] -//snippet-start:[pinpoint.java2.update_batch.import] +// snippet-start:[pinpoint.java2.update_batch.main] +// snippet-start:[pinpoint.java2.update_batch.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; import software.amazon.awssdk.services.pinpoint.model.UpdateEndpointsBatchResponse; @@ -24,10 +18,11 @@ import java.util.List; import java.util.ArrayList; import java.util.HashMap; -//snippet-end:[pinpoint.java2.update_batch.import] +// snippet-end:[pinpoint.java2.update_batch.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -35,109 +30,109 @@ */ public class AddExampleEndpoints { - public static void main(String[] args) { - final String usage = """ + public static void main(String[] args) { + final String usage = """ + + Usage: + + Where: + appId - The ID of the application. - Usage: + """; - Where: - appId - The ID of the application. + if (args.length != 1) { + System.out.println(usage); + System.exit(1); + } - """; + String applicationId = args[0]; + PinpointClient pinpoint = PinpointClient.builder() + .region(Region.US_EAST_1) + .build(); - if (args.length != 1) { - System.out.println(usage); - System.exit(1); + updateEndpointsViaBatch(pinpoint, applicationId); + pinpoint.close(); } - String applicationId = args[0]; - PinpointClient pinpoint = PinpointClient.builder() - .region(Region.US_EAST_1) - .build(); - - updateEndpointsViaBatch(pinpoint, applicationId); - pinpoint.close(); - } - - public static void updateEndpointsViaBatch(PinpointClient pinpoint, String applicationId) { - try { - List myList = new ArrayList<>(); - myList.add("music"); - myList.add("books"); - - Map myMap = new HashMap(); - myMap.put("attributes", myList); - - List myNames = new ArrayList(); - myList.add("Richard"); - myList.add("Roe"); - - Map myMap2 = new HashMap(); - myMap2.put("name", myNames); - - EndpointUser richardRoe = EndpointUser.builder() - .userId("example_user_1") - .userAttributes(myMap2) - .build(); - - // Create an EndpointBatchItem object for Richard Roe. - EndpointBatchItem richardRoesEmailEndpoint = EndpointBatchItem.builder() - .channelType(ChannelType.EMAIL) - .address("richard_roe@example.com") - .id("example_endpoint_1") - .attributes(myMap) - .user(richardRoe) - .build(); - - List myListMary = new ArrayList(); - myListMary.add("cooking"); - myListMary.add("politics"); - myListMary.add("finance"); - - Map myMapMary = new HashMap(); - myMapMary.put("interests", myListMary); - - List myNameMary = new ArrayList(); - myNameMary.add("Mary "); - myNameMary.add("Major"); - - Map maryName = new HashMap(); - myMapMary.put("name", myNameMary); - - EndpointUser maryMajor = EndpointUser.builder() - .userId("example_user_2") - .userAttributes(maryName) - .build(); - - // Create an EndpointBatchItem object for Mary Major. - EndpointBatchItem maryMajorsSmsEndpoint = EndpointBatchItem.builder() - .channelType(ChannelType.SMS) - .address("+16145550100") - .id("example_endpoint_2") - .attributes(myMapMary) - .user(maryMajor) - .build(); - - // Adds multiple endpoint definitions to a single request object. - EndpointBatchRequest endpointList = EndpointBatchRequest.builder() - .item(richardRoesEmailEndpoint) - .item(maryMajorsSmsEndpoint) - .build(); - - // Create the UpdateEndpointsBatchRequest. - UpdateEndpointsBatchRequest batchRequest = UpdateEndpointsBatchRequest.builder() - .applicationId(applicationId) - .endpointBatchRequest(endpointList) - .build(); - - // Updates the endpoints with Amazon Pinpoint. - UpdateEndpointsBatchResponse result = pinpoint.updateEndpointsBatch(batchRequest); - System.out.format("Update endpoints batch result: %s\n", result.messageBody().message()); - - } catch (PinpointException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + public static void updateEndpointsViaBatch(PinpointClient pinpoint, String applicationId) { + try { + List myList = new ArrayList<>(); + myList.add("music"); + myList.add("books"); + + Map myMap = new HashMap(); + myMap.put("attributes", myList); + + List myNames = new ArrayList(); + myList.add("Richard"); + myList.add("Roe"); + + Map myMap2 = new HashMap(); + myMap2.put("name", myNames); + + EndpointUser richardRoe = EndpointUser.builder() + .userId("example_user_1") + .userAttributes(myMap2) + .build(); + + // Create an EndpointBatchItem object for Richard Roe. + EndpointBatchItem richardRoesEmailEndpoint = EndpointBatchItem.builder() + .channelType(ChannelType.EMAIL) + .address("richard_roe@example.com") + .id("example_endpoint_1") + .attributes(myMap) + .user(richardRoe) + .build(); + + List myListMary = new ArrayList(); + myListMary.add("cooking"); + myListMary.add("politics"); + myListMary.add("finance"); + + Map myMapMary = new HashMap(); + myMapMary.put("interests", myListMary); + + List myNameMary = new ArrayList(); + myNameMary.add("Mary "); + myNameMary.add("Major"); + + Map maryName = new HashMap(); + myMapMary.put("name", myNameMary); + + EndpointUser maryMajor = EndpointUser.builder() + .userId("example_user_2") + .userAttributes(maryName) + .build(); + + // Create an EndpointBatchItem object for Mary Major. + EndpointBatchItem maryMajorsSmsEndpoint = EndpointBatchItem.builder() + .channelType(ChannelType.SMS) + .address("+16145550100") + .id("example_endpoint_2") + .attributes(myMapMary) + .user(maryMajor) + .build(); + + // Adds multiple endpoint definitions to a single request object. + EndpointBatchRequest endpointList = EndpointBatchRequest.builder() + .item(richardRoesEmailEndpoint) + .item(maryMajorsSmsEndpoint) + .build(); + + // Create the UpdateEndpointsBatchRequest. + UpdateEndpointsBatchRequest batchRequest = UpdateEndpointsBatchRequest.builder() + .applicationId(applicationId) + .endpointBatchRequest(endpointList) + .build(); + + // Updates the endpoints with Amazon Pinpoint. + UpdateEndpointsBatchResponse result = pinpoint.updateEndpointsBatch(batchRequest); + System.out.format("Update endpoints batch result: %s\n", result.messageBody().message()); + + } catch (PinpointException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } } - } } -//snippet-end:[pinpoint.java2.update_batch.main] +// snippet-end:[pinpoint.java2.update_batch.main] diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/AddExampleUser.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/AddExampleUser.java index 53d8a07df17..e6fd25b89e4 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/AddExampleUser.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/AddExampleUser.java @@ -1,15 +1,9 @@ -//snippet-sourcedescription:[AddExampleUser.java demonstrates how to update an existing endpoint.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; -//snippet-start:[pinpoint.java2.update_endpoint.import] +// snippet-start:[pinpoint.java2.update_endpoint.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; import software.amazon.awssdk.services.pinpoint.model.EndpointRequest; @@ -22,10 +16,11 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -//snippet-end:[pinpoint.java2.update_endpoint.import] +// snippet-end:[pinpoint.java2.update_endpoint.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -36,31 +31,31 @@ public class AddExampleUser { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - appId - The ID of the application to delete. + Where: + appId - The ID of the application to delete. - """; + """; if (args.length != 2) { System.out.println(usage); System.exit(1); - } + } String applicationId = args[0]; String endPointId = args[1]; PinpointClient pinpoint = PinpointClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); updatePinpointEndpoint(pinpoint, applicationId, endPointId); pinpoint.close(); } - //snippet-start:[pinpoint.java2.update_endpoint.main] - public static void updatePinpointEndpoint(PinpointClient pinpoint,String applicationId, String endPointId) { - try{ + // snippet-start:[pinpoint.java2.update_endpoint.main] + public static void updatePinpointEndpoint(PinpointClient pinpoint, String applicationId, String endPointId) { + try { List wangXiList = new ArrayList<>(); wangXiList.add("cooking"); wangXiList.add("running"); @@ -74,27 +69,27 @@ public static void updatePinpointEndpoint(PinpointClient pinpoint,String applica myNameWang.add("Xiulan"); Map wangName = new HashMap<>(); - wangName.put("name",myNameWang ); + wangName.put("name", myNameWang); EndpointUser wangMajor = EndpointUser.builder() - .userId("example_user_10") - .userAttributes(wangName) - .build(); + .userId("example_user_10") + .userAttributes(wangName) + .build(); // Create an EndpointBatchItem object for Mary Major. EndpointRequest wangXiulanEndpoint = EndpointRequest.builder() - .channelType(ChannelType.EMAIL) - .address("wang_xiulan@example.com") - .attributes(myMapWang) - .user(wangMajor) - .build(); + .channelType(ChannelType.EMAIL) + .address("wang_xiulan@example.com") + .attributes(myMapWang) + .user(wangMajor) + .build(); // Adds multiple endpoint definitions to a single request object. UpdateEndpointRequest endpointList = UpdateEndpointRequest.builder() - .applicationId(applicationId) - .endpointRequest(wangXiulanEndpoint) - .endpointId(endPointId) - .build(); + .applicationId(applicationId) + .endpointRequest(wangXiulanEndpoint) + .endpointId(endPointId) + .build(); UpdateEndpointResponse result = pinpoint.updateEndpoint(endpointList); System.out.format("Update endpoint result: %s\n", result.messageBody().message()); @@ -104,5 +99,5 @@ public static void updatePinpointEndpoint(PinpointClient pinpoint,String applica System.exit(1); } } - //snippet-end:[pinpoint.java2.update_endpoint.main] + // snippet-end:[pinpoint.java2.update_endpoint.main] } diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateApp.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateApp.java index 619695d70cf..79d895922e7 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateApp.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateApp.java @@ -1,25 +1,21 @@ -//snippet-sourcedescription:[CreateApp.java demonstrates hc in the Amazon Pinpoint dashboard.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.pinpoint; -//snippet-start:[pinpoint.java2.createapp.main] -//snippet-start:[pinpoint.java2.createapp.import] +// snippet-start:[pinpoint.java2.createapp.main] +// snippet-start:[pinpoint.java2.createapp.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; import software.amazon.awssdk.services.pinpoint.model.CreateAppRequest; import software.amazon.awssdk.services.pinpoint.model.CreateAppResponse; import software.amazon.awssdk.services.pinpoint.model.CreateApplicationRequest; import software.amazon.awssdk.services.pinpoint.model.PinpointException; -//snippet-end:[pinpoint.java2.createapp.import] +// snippet-end:[pinpoint.java2.createapp.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,12 +25,12 @@ public class CreateApp { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - appName - The name of the application to create. + Where: + appName - The name of the application to create. - """; + """; if (args.length != 1) { System.out.println(usage); @@ -44,8 +40,8 @@ public static void main(String[] args) { System.out.println("Creating an application with name: " + appName); PinpointClient pinpoint = PinpointClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); String appID = createApplication(pinpoint, appName); System.out.println("App ID is: " + appID); @@ -55,12 +51,12 @@ public static void main(String[] args) { public static String createApplication(PinpointClient pinpoint, String appName) { try { CreateApplicationRequest appRequest = CreateApplicationRequest.builder() - .name(appName) - .build(); + .name(appName) + .build(); CreateAppRequest request = CreateAppRequest.builder() - .createApplicationRequest(appRequest) - .build(); + .createApplicationRequest(appRequest) + .build(); CreateAppResponse result = pinpoint.createApp(request); return result.applicationResponse().id(); @@ -72,4 +68,4 @@ public static String createApplication(PinpointClient pinpoint, String appName) return ""; } } - //snippet-end:[pinpoint.java2.createapp.main] +// snippet-end:[pinpoint.java2.createapp.main] diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateCampaign.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateCampaign.java index 9ae98aced3e..2c3cff26819 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateCampaign.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateCampaign.java @@ -1,16 +1,10 @@ -//snippet-sourcedescription:[CreateCampaign.java demonstrates how to create a campaign for an application in Amazon Pinpoint.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; -//snippet-start:[pinpoint.java2.createcampaign.main] -//snippet-start:[pinpoint.java2.createcampaign.import] +// snippet-start:[pinpoint.java2.createcampaign.main] +// snippet-start:[pinpoint.java2.createcampaign.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; import software.amazon.awssdk.services.pinpoint.model.CampaignResponse; @@ -22,10 +16,11 @@ import software.amazon.awssdk.services.pinpoint.model.CreateCampaignResponse; import software.amazon.awssdk.services.pinpoint.model.CreateCampaignRequest; import software.amazon.awssdk.services.pinpoint.model.PinpointException; -//snippet-end:[pinpoint.java2.createcampaign.import] +// snippet-end:[pinpoint.java2.createcampaign.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -36,12 +31,12 @@ public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - appId - The ID of the application to create the campaign in. - segmentId - The ID of the segment to create the campaign from. - """; + Where: + appId - The ID of the application to create the campaign in. + segmentId - The ID of the segment to create the campaign from. + """; if (args.length != 2) { System.out.println(usage); @@ -51,8 +46,8 @@ public static void main(String[] args) { String appId = args[0]; String segmentId = args[1]; PinpointClient pinpoint = PinpointClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); createPinCampaign(pinpoint, appId, segmentId); pinpoint.close(); @@ -68,31 +63,30 @@ public static CampaignResponse createCampaign(PinpointClient client, String appI try { Schedule schedule = Schedule.builder() - .startTime("IMMEDIATE") - .build(); + .startTime("IMMEDIATE") + .build(); Message defaultMessage = Message.builder() - .action(Action.OPEN_APP) - .body("My message body.") - .title("My message title.") - .build(); + .action(Action.OPEN_APP) + .body("My message body.") + .title("My message title.") + .build(); MessageConfiguration messageConfiguration = MessageConfiguration.builder() - .defaultMessage(defaultMessage) - .build(); + .defaultMessage(defaultMessage) + .build(); WriteCampaignRequest request = WriteCampaignRequest.builder() - .description("My description") - .schedule(schedule) - .name("MyCampaign") - .segmentId(segmentID) - .messageConfiguration(messageConfiguration) - .build(); + .description("My description") + .schedule(schedule) + .name("MyCampaign") + .segmentId(segmentID) + .messageConfiguration(messageConfiguration) + .build(); CreateCampaignResponse result = client.createCampaign(CreateCampaignRequest.builder() - .applicationId(appID) - .writeCampaignRequest(request).build() - ); + .applicationId(appID) + .writeCampaignRequest(request).build()); System.out.println("Campaign ID: " + result.campaignResponse().id()); return result.campaignResponse(); @@ -105,4 +99,4 @@ public static CampaignResponse createCampaign(PinpointClient client, String appI return null; } } -//snippet-end:[pinpoint.java2.createcampaign.main] +// snippet-end:[pinpoint.java2.createcampaign.main] diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateEmailTemplate.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateEmailTemplate.java index da2d5581cd2..bce1b1be635 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateEmailTemplate.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateEmailTemplate.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; import software.amazon.awssdk.regions.Region; diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateSegment.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateSegment.java index 1f154c2c8d2..5979445c5ae 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateSegment.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/CreateSegment.java @@ -1,16 +1,10 @@ -//snippet-sourcedescription:[CreateSegment.java demonstrates how to create a segment for a campaign in Amazon Pinpoint.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; -//snippet-start:[pinpoint.java2.createsegment.main] -//snippet-start:[pinpoint.java2.createsegment.import] +// snippet-start:[pinpoint.java2.createsegment.main] +// snippet-start:[pinpoint.java2.createsegment.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; import software.amazon.awssdk.services.pinpoint.model.AttributeDimension; @@ -27,95 +21,96 @@ import software.amazon.awssdk.services.pinpoint.model.PinpointException; import java.util.HashMap; import java.util.Map; -//snippet-end:[pinpoint.java2.createsegment.import] +// snippet-end:[pinpoint.java2.createsegment.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateSegment { - public static void main(String[] args) { - final String usage = """ + public static void main(String[] args) { + final String usage = """ + + Usage: + + Where: + appId - The application ID to create a segment for. - Usage: + """; - Where: - appId - The application ID to create a segment for. + if (args.length != 1) { + System.out.println(usage); + System.exit(1); + } - """; + String appId = args[0]; + PinpointClient pinpoint = PinpointClient.builder() + .region(Region.US_EAST_1) + .build(); - if (args.length != 1) { - System.out.println(usage); - System.exit(1); + SegmentResponse result = createSegment(pinpoint, appId); + System.out.println("Segment " + result.name() + " created."); + System.out.println(result.segmentType()); + pinpoint.close(); } - String appId = args[0]; - PinpointClient pinpoint = PinpointClient.builder() - .region(Region.US_EAST_1) - .build(); - - SegmentResponse result = createSegment(pinpoint, appId); - System.out.println("Segment " + result.name() + " created."); - System.out.println(result.segmentType()); - pinpoint.close(); - } - - public static SegmentResponse createSegment(PinpointClient client, String appId) { - try { - Map segmentAttributes = new HashMap<>(); - segmentAttributes.put("Team", AttributeDimension.builder() - .attributeType(AttributeType.INCLUSIVE) - .values("Lakers") - .build()); - - RecencyDimension recencyDimension = RecencyDimension.builder() - .duration("DAY_30") - .recencyType("ACTIVE") - .build(); - - SegmentBehaviors segmentBehaviors = SegmentBehaviors.builder() - .recency(recencyDimension) - .build(); - - SegmentDemographics segmentDemographics = SegmentDemographics - .builder() - .build(); - - SegmentLocation segmentLocation = SegmentLocation - .builder() - .build(); - - SegmentDimensions dimensions = SegmentDimensions - .builder() - .attributes(segmentAttributes) - .behavior(segmentBehaviors) - .demographic(segmentDemographics) - .location(segmentLocation) - .build(); - - WriteSegmentRequest writeSegmentRequest = WriteSegmentRequest.builder() - .name("MySegment") - .dimensions(dimensions) - .build(); - - CreateSegmentRequest createSegmentRequest = CreateSegmentRequest.builder() - .applicationId(appId) - .writeSegmentRequest(writeSegmentRequest) - .build(); - - CreateSegmentResponse createSegmentResult = client.createSegment(createSegmentRequest); - System.out.println("Segment ID: " + createSegmentResult.segmentResponse().id()); - System.out.println("Done"); - return createSegmentResult.segmentResponse(); - - } catch (PinpointException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + public static SegmentResponse createSegment(PinpointClient client, String appId) { + try { + Map segmentAttributes = new HashMap<>(); + segmentAttributes.put("Team", AttributeDimension.builder() + .attributeType(AttributeType.INCLUSIVE) + .values("Lakers") + .build()); + + RecencyDimension recencyDimension = RecencyDimension.builder() + .duration("DAY_30") + .recencyType("ACTIVE") + .build(); + + SegmentBehaviors segmentBehaviors = SegmentBehaviors.builder() + .recency(recencyDimension) + .build(); + + SegmentDemographics segmentDemographics = SegmentDemographics + .builder() + .build(); + + SegmentLocation segmentLocation = SegmentLocation + .builder() + .build(); + + SegmentDimensions dimensions = SegmentDimensions + .builder() + .attributes(segmentAttributes) + .behavior(segmentBehaviors) + .demographic(segmentDemographics) + .location(segmentLocation) + .build(); + + WriteSegmentRequest writeSegmentRequest = WriteSegmentRequest.builder() + .name("MySegment") + .dimensions(dimensions) + .build(); + + CreateSegmentRequest createSegmentRequest = CreateSegmentRequest.builder() + .applicationId(appId) + .writeSegmentRequest(writeSegmentRequest) + .build(); + + CreateSegmentResponse createSegmentResult = client.createSegment(createSegmentRequest); + System.out.println("Segment ID: " + createSegmentResult.segmentResponse().id()); + System.out.println("Done"); + return createSegmentResult.segmentResponse(); + + } catch (PinpointException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + return null; } - return null; - } } - //snippet-end:[pinpoint.java2.createsegment.main] \ No newline at end of file +// snippet-end:[pinpoint.java2.createsegment.main] \ No newline at end of file diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/DeleteApp.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/DeleteApp.java index 24b6f43b99f..6ab072962c3 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/DeleteApp.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/DeleteApp.java @@ -1,25 +1,20 @@ -//snippet-sourcedescription:[DeleteApp.java demonstrates how to delete an application in the Amazon Pinpoint dashboard.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; -//snippet-start:[pinpoint.java2.deleteapp.main] -//snippet-start:[pinpoint.java2.deleteapp.import] +// snippet-start:[pinpoint.java2.deleteapp.main] +// snippet-start:[pinpoint.java2.deleteapp.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; import software.amazon.awssdk.services.pinpoint.model.DeleteAppRequest; import software.amazon.awssdk.services.pinpoint.model.DeleteAppResponse; import software.amazon.awssdk.services.pinpoint.model.PinpointException; -//snippet-end:[pinpoint.java2.deleteapp.import] +// snippet-end:[pinpoint.java2.deleteapp.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,12 +24,12 @@ public class DeleteApp { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - appId - The ID of the application to delete. + Where: + appId - The ID of the application to delete. - """; + """; if (args.length != 1) { System.out.println(usage); @@ -44,8 +39,8 @@ public static void main(String[] args) { String appId = args[0]; System.out.println("Deleting an application with ID: " + appId); PinpointClient pinpoint = PinpointClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); deletePinApp(pinpoint, appId); System.out.println("Done"); @@ -55,8 +50,8 @@ public static void main(String[] args) { public static void deletePinApp(PinpointClient pinpoint, String appId) { try { DeleteAppRequest appRequest = DeleteAppRequest.builder() - .applicationId(appId) - .build(); + .applicationId(appId) + .build(); DeleteAppResponse result = pinpoint.deleteApp(appRequest); String appName = result.applicationResponse().name(); @@ -68,5 +63,4 @@ public static void deletePinApp(PinpointClient pinpoint, String appId) { } } } -//snippet-end:[pinpoint.java2.deleteapp.main] - +// snippet-end:[pinpoint.java2.deleteapp.main] diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/DeleteEndpoint.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/DeleteEndpoint.java index fa1c4810e09..d0d558ba9f6 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/DeleteEndpoint.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/DeleteEndpoint.java @@ -1,25 +1,20 @@ -//snippet-sourcedescription:[DeleteEndpoint.java demonstrates how to delete an endpoint.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; -//snippet-start:[pinpoint.java2.deleteendpoint.main] -//snippet-start:[pinpoint.java2.deleteendpoint.import] +// snippet-start:[pinpoint.java2.deleteendpoint.main] +// snippet-start:[pinpoint.java2.deleteendpoint.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; import software.amazon.awssdk.services.pinpoint.model.DeleteEndpointRequest; import software.amazon.awssdk.services.pinpoint.model.DeleteEndpointResponse; import software.amazon.awssdk.services.pinpoint.model.PinpointException; -//snippet-end:[pinpoint.java2.deleteendpoint.import] +// snippet-end:[pinpoint.java2.deleteendpoint.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,12 +24,12 @@ public class DeleteEndpoint { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - appId - The id of the application to delete. - endpointId - The id of the endpoint to delete. - """; + Where: + appId - The id of the application to delete. + endpointId - The id of the endpoint to delete. + """; if (args.length != 2) { System.out.println(usage); @@ -45,8 +40,8 @@ public static void main(String[] args) { String endpointId = args[1]; System.out.println("Deleting an endpoint with id: " + endpointId); PinpointClient pinpoint = PinpointClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); deletePinEncpoint(pinpoint, appId, endpointId); pinpoint.close(); @@ -55,9 +50,9 @@ public static void main(String[] args) { public static void deletePinEncpoint(PinpointClient pinpoint, String appId, String endpointId) { try { DeleteEndpointRequest appRequest = DeleteEndpointRequest.builder() - .applicationId(appId) - .endpointId(endpointId) - .build(); + .applicationId(appId) + .endpointId(endpointId) + .build(); DeleteEndpointResponse result = pinpoint.deleteEndpoint(appRequest); String id = result.endpointResponse().id(); @@ -70,4 +65,4 @@ public static void deletePinEncpoint(PinpointClient pinpoint, String appId, Stri System.out.println("Done"); } } - //snippet-end:[pinpoint.java2.deleteendpoint.main] +// snippet-end:[pinpoint.java2.deleteendpoint.main] diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/ExportEndpoints.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/ExportEndpoints.java index 82f0e1c980f..2a974711eb2 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/ExportEndpoints.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/ExportEndpoints.java @@ -1,15 +1,10 @@ -//snippet-sourcedescription:[ExportEndpoints.java demonstrates how to export endpoints to an Amazon Simple Storage Service (Amazon S3) bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; -//snippet-start:[pinpoint.java2.export_endpoint.main] -//snippet-start:[pinpoint.java2.export_endpoint.import] +// snippet-start:[pinpoint.java2.export_endpoint.main] +// snippet-start:[pinpoint.java2.export_endpoint.import] import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; @@ -36,11 +31,13 @@ import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; -//snippet-end:[pinpoint.java2.export_endpoint.import] +// snippet-end:[pinpoint.java2.export_endpoint.import] /** - * To run this code example, you need to create an AWS Identity and Access Management (IAM) role with the correct policy as described in this documentation: - * https://docs.aws.amazon.com/pinpoint/latest/developerguide/audience-data-export.html + * To run this code example, you need to create an AWS Identity and Access + * Management (IAM) role with the correct policy as described in this + * documentation: + * https://docs.aws.amazon.com/pinpoint/latest/developerguide/audience-data-export.html * * Also, set up your development environment, including your credentials. * @@ -53,18 +50,18 @@ public class ExportEndpoints { public static void main(String[] args) { final String usage = """ - This program performs the following steps: + This program performs the following steps: - 1. Exports the endpoints to an Amazon S3 bucket. - 2. Downloads the exported endpoints files from Amazon S3. - 3. Parses the endpoints files to obtain the endpoint IDs and prints them. - Usage: ExportEndpoints + 1. Exports the endpoints to an Amazon S3 bucket. + 2. Downloads the exported endpoints files from Amazon S3. + 3. Parses the endpoints files to obtain the endpoint IDs and prints them. + Usage: ExportEndpoints - Where: - applicationId - The ID of the Amazon Pinpoint application that has the endpoint. - s3BucketName - The name of the Amazon S3 bucket to export the JSON file to.\s - iamExportRoleArn - The ARN of an IAM role that grants Amazon Pinpoint write permissions to the S3 bucket. path - The path where the files downloaded from the Amazon S3 bucket are written (for example, C:/AWS/). - """; + Where: + applicationId - The ID of the Amazon Pinpoint application that has the endpoint. + s3BucketName - The name of the Amazon S3 bucket to export the JSON file to.\s + iamExportRoleArn - The ARN of an IAM role that grants Amazon Pinpoint write permissions to the S3 bucket. path - The path where the files downloaded from the Amazon S3 bucket are written (for example, C:/AWS/). + """; if (args.length != 4) { System.out.println(usage); @@ -79,12 +76,12 @@ public static void main(String[] args) { Region region = Region.US_EAST_1; PinpointClient pinpoint = PinpointClient.builder() - .region(region) - .build(); + .region(region) + .build(); S3Client s3Client = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); exportAllEndpoints(pinpoint, s3Client, applicationId, s3BucketName, path, iamExportRoleArn); pinpoint.close(); @@ -92,15 +89,17 @@ public static void main(String[] args) { } public static void exportAllEndpoints(PinpointClient pinpoint, - S3Client s3Client, - String applicationId, - String s3BucketName, - String path, - String iamExportRoleArn) { + S3Client s3Client, + String applicationId, + String s3BucketName, + String path, + String iamExportRoleArn) { try { - List objectKeys = exportEndpointsToS3(pinpoint, s3Client, s3BucketName, iamExportRoleArn, applicationId); - List endpointFileKeys = objectKeys.stream().filter(o -> o.endsWith(".gz")).collect(Collectors.toList()); + List objectKeys = exportEndpointsToS3(pinpoint, s3Client, s3BucketName, iamExportRoleArn, + applicationId); + List endpointFileKeys = objectKeys.stream().filter(o -> o.endsWith(".gz")) + .collect(Collectors.toList()); downloadFromS3(s3Client, path, s3BucketName, endpointFileKeys); } catch (PinpointException e) { @@ -109,7 +108,8 @@ public static void exportAllEndpoints(PinpointClient pinpoint, } } - public static List exportEndpointsToS3(PinpointClient pinpoint, S3Client s3Client, String s3BucketName, String iamExportRoleArn, String applicationId) { + public static List exportEndpointsToS3(PinpointClient pinpoint, S3Client s3Client, String s3BucketName, + String iamExportRoleArn, String applicationId) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH_mm:ss.SSS_z"); String endpointsKeyPrefix = "exports/" + applicationId + "_" + dateFormat.format(new Date()); @@ -120,17 +120,17 @@ public static List exportEndpointsToS3(PinpointClient pinpoint, S3Client try { // Defines the export job that Amazon Pinpoint runs. ExportJobRequest jobRequest = ExportJobRequest.builder() - .roleArn(iamExportRoleArn) - .s3UrlPrefix(s3UrlPrefix) - .build(); + .roleArn(iamExportRoleArn) + .s3UrlPrefix(s3UrlPrefix) + .build(); CreateExportJobRequest exportJobRequest = CreateExportJobRequest.builder() - .applicationId(applicationId) - .exportJobRequest(jobRequest) - .build(); + .applicationId(applicationId) + .exportJobRequest(jobRequest) + .build(); System.out.format("Exporting endpoints from Amazon Pinpoint application %s to Amazon S3 " + - "bucket %s . . .\n", applicationId, s3BucketName); + "bucket %s . . .\n", applicationId, s3BucketName); CreateExportJobResponse exportResult = pinpoint.createExportJob(exportJobRequest); String jobId = exportResult.exportJobResponse().id(); @@ -138,9 +138,9 @@ public static List exportEndpointsToS3(PinpointClient pinpoint, S3Client printExportJobStatus(pinpoint, applicationId, jobId); ListObjectsV2Request v2Request = ListObjectsV2Request.builder() - .bucket(s3BucketName) - .prefix(endpointsKeyPrefix) - .build(); + .bucket(s3BucketName) + .prefix(endpointsKeyPrefix) + .build(); // Create a list of object keys. ListObjectsV2Response v2Response = s3Client.listObjectsV2(v2Request); @@ -160,8 +160,8 @@ public static List exportEndpointsToS3(PinpointClient pinpoint, S3Client } private static void printExportJobStatus(PinpointClient pinpointClient, - String applicationId, - String jobId) { + String applicationId, + String jobId) { GetExportJobResponse getExportJobResult; String status; @@ -169,9 +169,9 @@ private static void printExportJobStatus(PinpointClient pinpointClient, try { // Checks the job status until the job completes or fails. GetExportJobRequest exportJobRequest = GetExportJobRequest.builder() - .jobId(jobId) - .applicationId(applicationId) - .build(); + .jobId(jobId) + .applicationId(applicationId) + .build(); do { getExportJobResult = pinpointClient.getExportJob(exportJobRequest); @@ -201,9 +201,9 @@ public static void downloadFromS3(S3Client s3Client, String path, String s3Bucke try { for (String key : objectKeys) { GetObjectRequest objectRequest = GetObjectRequest.builder() - .bucket(s3BucketName) - .key(key) - .build(); + .bucket(s3BucketName) + .key(key) + .build(); ResponseBytes objectBytes = s3Client.getObjectAsBytes(objectRequest); byte[] data = objectBytes.asByteArray(); @@ -223,4 +223,4 @@ public static void downloadFromS3(S3Client s3Client, String path, String s3Bucke } } } -//snippet-end:[pinpoint.java2.export_endpoint.main] \ No newline at end of file +// snippet-end:[pinpoint.java2.export_endpoint.main] \ No newline at end of file diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/GetSegmentById.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/GetSegmentById.java index 26021ec4f61..acab366ebaf 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/GetSegmentById.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/GetSegmentById.java @@ -1,25 +1,20 @@ -//snippet-sourcedescription:[GetSegmentById.java demonstrates how to get a segment using its id value.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; -//snippet-start:[pinpoint.java2.segment_id.main] -//snippet-start:[pinpoint.java2.segment_id.import] +// snippet-start:[pinpoint.java2.segment_id.main] +// snippet-start:[pinpoint.java2.segment_id.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; import software.amazon.awssdk.services.pinpoint.model.GetSegmentRequest; import software.amazon.awssdk.services.pinpoint.model.GetSegmentResponse; import software.amazon.awssdk.services.pinpoint.model.PinpointException; -//snippet-end:[pinpoint.java2.segment_id.import] +// snippet-end:[pinpoint.java2.segment_id.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,14 +25,14 @@ public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - appId - The id of the application. + Where: + appId - The id of the application. - segmentId - The id of the segment. + segmentId - The id of the segment. - """; + """; if (args.length != 2) { System.out.println(usage); @@ -47,8 +42,8 @@ public static void main(String[] args) { String appId = args[0]; String segmentId = args[1]; PinpointClient pinpoint = PinpointClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); System.out.println("Name of the segment is " + getSegmentById(pinpoint, appId, segmentId)); pinpoint.close(); @@ -57,9 +52,9 @@ public static void main(String[] args) { private static String getSegmentById(PinpointClient client, String applicationId, String segmentId) { try { GetSegmentRequest request = GetSegmentRequest.builder() - .applicationId(applicationId) - .segmentId(segmentId) - .build(); + .applicationId(applicationId) + .segmentId(segmentId) + .build(); GetSegmentResponse segmentResponse = client.getSegment(request); return segmentResponse.segmentResponse().name(); @@ -71,4 +66,4 @@ private static String getSegmentById(PinpointClient client, String applicationId return null; } } -//snippet-end:[pinpoint.java2.segment_id.main] +// snippet-end:[pinpoint.java2.segment_id.main] diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/GetTemplateByName.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/GetTemplateByName.java index a2f73958be4..c6da7f9c048 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/GetTemplateByName.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/GetTemplateByName.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[GetTemplateByName.java demonstrates how to get a template.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; @@ -16,7 +10,8 @@ import software.amazon.awssdk.services.pinpoint.model.GetEmailTemplateRequest; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,8 +23,8 @@ public static void main(String[] args) { // Change "MyNewTemplate-1" to the name of the template to retrieve. String templateName = "MyNewTemplate-1"; PinpointClient pinpoint = PinpointClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); EmailTemplateResponse templateResponse = getTemplateByName(pinpoint, templateName); System.out.println("Response : " + templateResponse); @@ -39,9 +34,8 @@ public static void main(String[] args) { private static EmailTemplateResponse getTemplateByName(PinpointClient client, String templateName) { try { EmailTemplateResponse response = client.getEmailTemplate(GetEmailTemplateRequest.builder() - .templateName(templateName) - .build()). - emailTemplateResponse(); + .templateName(templateName) + .build()).emailTemplateResponse(); return response; } catch (PinpointException e) { diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/ImportSegment.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/ImportSegment.java index 1a73caab42c..18b78936e79 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/ImportSegment.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/ImportSegment.java @@ -1,14 +1,10 @@ -//snippet-sourcedescription:[ImportSegment.java demonstrates how to how to import a segment into Amazon Pinpoint.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.pinpoint; -//snippet-start:[pinpoint.java2.importsegment.main] -//snippet-start:[pinpoint.java2.importsegment.import] +// snippet-start:[pinpoint.java2.importsegment.main] +// snippet-start:[pinpoint.java2.importsegment.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; import software.amazon.awssdk.services.pinpoint.model.CreateImportJobRequest; @@ -17,10 +13,11 @@ import software.amazon.awssdk.services.pinpoint.model.Format; import software.amazon.awssdk.services.pinpoint.model.CreateImportJobResponse; import software.amazon.awssdk.services.pinpoint.model.PinpointException; -//snippet-end:[pinpoint.java2.importsegment.import] +// snippet-end:[pinpoint.java2.importsegment.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,14 +27,14 @@ public class ImportSegment { public static void main(String[] args) { final String usage = """ - Usage: \s + Usage: \s - Where: - appId - The application ID to create a segment for. - bucket - The name of the Amazon S3 bucket that contains the segment definitons. - key - The key of the S3 object. - roleArn - ARN of the role that allows Amazon Pinpoint to access S3. You need to set trust management for this to work. See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html - """; + Where: + appId - The application ID to create a segment for. + bucket - The name of the Amazon S3 bucket that contains the segment definitons. + key - The key of the S3 object. + roleArn - ARN of the role that allows Amazon Pinpoint to access S3. You need to set trust management for this to work. See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html + """; if (args.length != 4) { System.out.println(usage); @@ -50,8 +47,8 @@ public static void main(String[] args) { String roleArn = args[3]; PinpointClient pinpoint = PinpointClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); ImportJobResponse response = createImportSegment(pinpoint, appId, bucket, key, roleArn); System.out.println("Import job for " + bucket + " submitted."); @@ -60,26 +57,25 @@ public static void main(String[] args) { pinpoint.close(); } - public static ImportJobResponse createImportSegment(PinpointClient client, - String appId, - String bucket, - String key, - String roleArn) { + String appId, + String bucket, + String key, + String roleArn) { try { ImportJobRequest importRequest = ImportJobRequest.builder() - .defineSegment(true) - .registerEndpoints(true) - .roleArn(roleArn) - .format(Format.JSON) - .s3Url("s3://" + bucket + "/" + key) - .build(); + .defineSegment(true) + .registerEndpoints(true) + .roleArn(roleArn) + .format(Format.JSON) + .s3Url("s3://" + bucket + "/" + key) + .build(); CreateImportJobRequest jobRequest = CreateImportJobRequest.builder() - .importJobRequest(importRequest) - .applicationId(appId) - .build(); + .importJobRequest(importRequest) + .applicationId(appId) + .build(); CreateImportJobResponse jobResponse = client.createImportJob(jobRequest); return jobResponse.importJobResponse(); @@ -91,4 +87,4 @@ public static ImportJobResponse createImportSegment(PinpointClient client, return null; } } -//snippet-end:[pinpoint.java2.importsegment.main] \ No newline at end of file +// snippet-end:[pinpoint.java2.importsegment.main] \ No newline at end of file diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/ListEndpointIds.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/ListEndpointIds.java index 866f170980d..4ecaad6566f 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/ListEndpointIds.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/ListEndpointIds.java @@ -1,15 +1,10 @@ -//snippet-sourcedescription:[ListEndpointIds.java demonstrates how to retrieve information about all the endpoints that are associated with a specific user ID.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.pinpoint; -//snippet-start:[pinpoint.java2.list_endpoints.main] -//snippet-start:[pinpoint.java2.list_endpoints.import] +// snippet-start:[pinpoint.java2.list_endpoints.main] +// snippet-start:[pinpoint.java2.list_endpoints.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; import software.amazon.awssdk.services.pinpoint.model.EndpointResponse; @@ -17,10 +12,11 @@ import software.amazon.awssdk.services.pinpoint.model.GetUserEndpointsResponse; import software.amazon.awssdk.services.pinpoint.model.PinpointException; import java.util.List; -//snippet-end:[pinpoint.java2.list_endpoints.import] +// snippet-end:[pinpoint.java2.list_endpoints.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,11 +26,11 @@ public class ListEndpointIds { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - applicationId - The ID of the Amazon Pinpoint application that has the endpoint. - userId - The user id applicable to the endpoints"""; + Where: + applicationId - The ID of the Amazon Pinpoint application that has the endpoint. + userId - The user id applicable to the endpoints"""; if (args.length != 2) { System.out.println(usage); @@ -44,22 +40,22 @@ public static void main(String[] args) { String applicationId = args[0]; String userId = args[1]; PinpointClient pinpoint = PinpointClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); listAllEndpoints(pinpoint, applicationId, userId); pinpoint.close(); } public static void listAllEndpoints(PinpointClient pinpoint, - String applicationId, - String userId) { + String applicationId, + String userId) { try { GetUserEndpointsRequest endpointsRequest = GetUserEndpointsRequest.builder() - .userId(userId) - .applicationId(applicationId) - .build(); + .userId(userId) + .applicationId(applicationId) + .build(); GetUserEndpointsResponse response = pinpoint.getUserEndpoints(endpointsRequest); List endpoints = response.endpointsResponse().item(); @@ -76,4 +72,4 @@ public static void listAllEndpoints(PinpointClient pinpoint, } } } -//snippet-end:[pinpoint.java2.list_endpoints.main] +// snippet-end:[pinpoint.java2.list_endpoints.main] diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/ListSegments.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/ListSegments.java index 7f6d415aad4..297f94f4588 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/ListSegments.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/ListSegments.java @@ -1,17 +1,10 @@ -//snippet-sourcedescription:[ListSegements.java demonstrates how to list segments in an application.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; -//snippet-start:[pinpoint.java2.listsegments.main] -//snippet-start:[pinpoint.java2.listsegments.import] +// snippet-start:[pinpoint.java2.listsegments.main] +// snippet-start:[pinpoint.java2.listsegments.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; import software.amazon.awssdk.services.pinpoint.model.GetSegmentsRequest; @@ -19,10 +12,11 @@ import software.amazon.awssdk.services.pinpoint.model.PinpointException; import software.amazon.awssdk.services.pinpoint.model.SegmentResponse; import java.util.List; -//snippet-end:[pinpoint.java2.listsegments.import] +// snippet-end:[pinpoint.java2.listsegments.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,12 +26,12 @@ public class ListSegments { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - appId - The ID of the application that contains a segment. + Where: + appId - The ID of the application that contains a segment. - """; + """; if (args.length != 1) { System.out.println(usage); @@ -46,8 +40,8 @@ public static void main(String[] args) { String appId = args[0]; PinpointClient pinpoint = PinpointClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); listSegs(pinpoint, appId); pinpoint.close(); @@ -56,13 +50,14 @@ public static void main(String[] args) { public static void listSegs(PinpointClient pinpoint, String appId) { try { GetSegmentsRequest request = GetSegmentsRequest.builder() - .applicationId(appId) - .build(); + .applicationId(appId) + .build(); GetSegmentsResponse response = pinpoint.getSegments(request); List segments = response.segmentsResponse().item(); for (SegmentResponse segment : segments) { - System.out.println("Segement " + segment.id() + " " + segment.name() + " " + segment.lastModifiedDate()); + System.out + .println("Segement " + segment.id() + " " + segment.name() + " " + segment.lastModifiedDate()); } } catch (PinpointException e) { @@ -71,4 +66,4 @@ public static void listSegs(PinpointClient pinpoint, String appId) { } } } -//snippet-end:[pinpoint.java2.listsegments.main] \ No newline at end of file +// snippet-end:[pinpoint.java2.listsegments.main] \ No newline at end of file diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/LookUpEndpoint.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/LookUpEndpoint.java index bc171765cb5..57d225b697a 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/LookUpEndpoint.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/LookUpEndpoint.java @@ -1,15 +1,10 @@ -//snippet-sourcedescription:[LookUpEndpoint.java demonstrates how to display information about an existing endpoint in Amazon Pinpoint.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; -//snippet-start:[pinpoint.java2.lookup.main] -//snippet-start:[pinpoint.java2.lookup.import] +// snippet-start:[pinpoint.java2.lookup.main] +// snippet-start:[pinpoint.java2.lookup.import] import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -19,10 +14,11 @@ import software.amazon.awssdk.services.pinpoint.model.GetEndpointResponse; import software.amazon.awssdk.services.pinpoint.model.PinpointException; import software.amazon.awssdk.services.pinpoint.model.GetEndpointRequest; -//snippet-end:[pinpoint.java2.lookup.import] +// snippet-end:[pinpoint.java2.lookup.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,12 +28,12 @@ public class LookUpEndpoint { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - appId - The ID of the application to delete. - endpoint - The ID of the endpoint.\s - """; + Where: + appId - The ID of the application to delete. + endpoint - The ID of the endpoint.\s + """; if (args.length != 2) { System.out.println(usage); @@ -48,8 +44,8 @@ public static void main(String[] args) { String endpoint = args[1]; System.out.println("Looking up an endpoint point with ID: " + endpoint); PinpointClient pinpoint = PinpointClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); lookupPinpointEndpoint(pinpoint, appId, endpoint); pinpoint.close(); @@ -58,18 +54,18 @@ public static void main(String[] args) { public static void lookupPinpointEndpoint(PinpointClient pinpoint, String appId, String endpoint) { try { GetEndpointRequest appRequest = GetEndpointRequest.builder() - .applicationId(appId) - .endpointId(endpoint) - .build(); + .applicationId(appId) + .endpointId(endpoint) + .build(); GetEndpointResponse result = pinpoint.getEndpoint(appRequest); EndpointResponse endResponse = result.endpointResponse(); // Uses the Google Gson library to pretty print the endpoint JSON. Gson gson = new GsonBuilder() - .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE) - .setPrettyPrinting() - .create(); + .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE) + .setPrettyPrinting() + .create(); String endpointJson = gson.toJson(endResponse); System.out.println(endpointJson); @@ -81,5 +77,4 @@ public static void lookupPinpointEndpoint(PinpointClient pinpoint, String appId, System.out.println("Done"); } } -//snippet-end:[pinpoint.java2.lookup.main] - +// snippet-end:[pinpoint.java2.lookup.main] diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendEmailMessage.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendEmailMessage.java index 9fc3fe672c6..c42b6915487 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendEmailMessage.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendEmailMessage.java @@ -1,16 +1,10 @@ -//snippet-sourcedescription:[SendEmailMessage.java demonstrates how to send an email message.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; -//snippet-start:[pinpoint.java2.send_email.main] -//snippet-start:[pinpoint.java2.send_email.import] +// snippet-start:[pinpoint.java2.send_email.main] +// snippet-start:[pinpoint.java2.send_email.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; import software.amazon.awssdk.services.pinpoint.model.AddressConfiguration; @@ -32,10 +26,11 @@ import java.util.HashMap; import java.util.Map; -//snippet-end:[pinpoint.java2.send_email.import] +// snippet-end:[pinpoint.java2.send_email.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -43,9 +38,9 @@ */ public class SendEmailMessage { - // The character encoding the you want to use for the subject line and - // message body of the email. - public static String charset = "UTF-8"; + // The character encoding the you want to use for the subject line and + // message body of the email. + public static String charset = "UTF-8"; // The body of the email for recipients whose email clients support HTML content. static final String body = """ @@ -55,10 +50,10 @@ Amazon Pinpoint test (AWS SDK for Java 2.x) """; - public static void main(String[] args) { - final String usage = """ + public static void main(String[] args) { + final String usage = """ - Usage: + Usage: Where: subject - The email subject to use. @@ -122,4 +117,4 @@ public static void sendEmail(PinpointEmailClient pinpointEmailClient, String sub } } } -//snippet-end:[pinpoint.java2.send_email.main] +// snippet-end:[pinpoint.java2.send_email.main] diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendEmailMessageCC.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendEmailMessageCC.java index 3cc0a220c48..86da9191ec0 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendEmailMessageCC.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendEmailMessageCC.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[SendEmailMessageCC.java demonstrates how to send an email message which includes CC values.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendMessage.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendMessage.java index 3673cbf89e9..3ec4110bfe1 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendMessage.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendMessage.java @@ -1,16 +1,10 @@ -//snippet-sourcedescription:[SendMessage.java demonstrates how to send an SMS message.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; -//snippet-start:[pinpoint.java2.sendmsg.main] -//snippet-start:[pinpoint.java2.sendmsg.import] +// snippet-start:[pinpoint.java2.sendmsg.main] +// snippet-start:[pinpoint.java2.sendmsg.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; import software.amazon.awssdk.services.pinpoint.model.DirectMessageConfiguration; @@ -24,10 +18,11 @@ import software.amazon.awssdk.services.pinpoint.model.PinpointException; import java.util.HashMap; import java.util.Map; -//snippet-end:[pinpoint.java2.sendmsg.import] +// snippet-end:[pinpoint.java2.sendmsg.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -35,92 +30,94 @@ */ public class SendMessage { - // The type of SMS message that you want to send. If you plan to send - // time-sensitive content, specify TRANSACTIONAL. If you plan to send - // marketing-related content, specify PROMOTIONAL. - public static String messageType = "TRANSACTIONAL"; - - // The registered keyword associated with the originating short code. - public static String registeredKeyword = "myKeyword"; - - // The sender ID to use when sending the message. Support for sender ID - // varies by country or region. For more information, see - // https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-countries.html - public static String senderId = "MySenderID"; - - public static void main(String[] args) { - final String usage = """ - - Usage: \s - - Where: - message - The body of the message to send. - appId - The Amazon Pinpoint project/application ID to use when you send this message. - originationNumber - The phone number or short code that you specify has to be associated with your Amazon Pinpoint account. For best results, specify long codes in E.164 format (for example, +1-555-555-5654). - destinationNumber - The recipient's phone number. For best results, you should specify the phone number in E.164 format (for example, +1-555-555-5654).\s - """; - - if (args.length != 4) { - System.out.println(usage); - System.exit(1); + // The type of SMS message that you want to send. If you plan to send + // time-sensitive content, specify TRANSACTIONAL. If you plan to send + // marketing-related content, specify PROMOTIONAL. + public static String messageType = "TRANSACTIONAL"; + + // The registered keyword associated with the originating short code. + public static String registeredKeyword = "myKeyword"; + + // The sender ID to use when sending the message. Support for sender ID + // varies by country or region. For more information, see + // https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-countries.html + public static String senderId = "MySenderID"; + + public static void main(String[] args) { + final String usage = """ + + Usage: \s + + Where: + message - The body of the message to send. + appId - The Amazon Pinpoint project/application ID to use when you send this message. + originationNumber - The phone number or short code that you specify has to be associated with your Amazon Pinpoint account. For best results, specify long codes in E.164 format (for example, +1-555-555-5654). + destinationNumber - The recipient's phone number. For best results, you should specify the phone number in E.164 format (for example, +1-555-555-5654).\s + """; + + if (args.length != 4) { + System.out.println(usage); + System.exit(1); + } + + String message = args[0]; + String appId = args[1]; + String originationNumber = args[2]; + String destinationNumber = args[3]; + System.out.println("Sending a message"); + PinpointClient pinpoint = PinpointClient.builder() + .region(Region.US_EAST_1) + .build(); + + sendSMSMessage(pinpoint, message, appId, originationNumber, destinationNumber); + pinpoint.close(); } - String message = args[0]; - String appId = args[1]; - String originationNumber = args[2]; - String destinationNumber = args[3]; - System.out.println("Sending a message"); - PinpointClient pinpoint = PinpointClient.builder() - .region(Region.US_EAST_1) - .build(); - - sendSMSMessage(pinpoint, message, appId, originationNumber, destinationNumber); - pinpoint.close(); - } - - public static void sendSMSMessage(PinpointClient pinpoint, String message, String appId, String originationNumber, String destinationNumber) { - try { - Map addressMap = new HashMap(); - AddressConfiguration addConfig = AddressConfiguration.builder() - .channelType(ChannelType.SMS) - .build(); - - addressMap.put(destinationNumber, addConfig); - SMSMessage smsMessage = SMSMessage.builder() - .body(message) - .messageType(messageType) - .originationNumber(originationNumber) - .senderId(senderId) - .keyword(registeredKeyword) - .build(); - - // Create a DirectMessageConfiguration object. - DirectMessageConfiguration direct = DirectMessageConfiguration.builder() - .smsMessage(smsMessage) - .build(); - - MessageRequest msgReq = MessageRequest.builder() - .addresses(addressMap) - .messageConfiguration(direct) - .build(); - - // create a SendMessagesRequest object - SendMessagesRequest request = SendMessagesRequest.builder() - .applicationId(appId) - .messageRequest(msgReq) - .build(); - - SendMessagesResponse response = pinpoint.sendMessages(request); - MessageResponse msg1 = response.messageResponse(); - Map map1 = msg1.result(); - - //Write out the result of sendMessage. - map1.forEach((k, v) -> System.out.println((k + ":" + v))); - - } catch (PinpointException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + public static void sendSMSMessage(PinpointClient pinpoint, String message, String appId, + String originationNumber, + String destinationNumber) { + try { + Map addressMap = new HashMap(); + AddressConfiguration addConfig = AddressConfiguration.builder() + .channelType(ChannelType.SMS) + .build(); + + addressMap.put(destinationNumber, addConfig); + SMSMessage smsMessage = SMSMessage.builder() + .body(message) + .messageType(messageType) + .originationNumber(originationNumber) + .senderId(senderId) + .keyword(registeredKeyword) + .build(); + + // Create a DirectMessageConfiguration object. + DirectMessageConfiguration direct = DirectMessageConfiguration.builder() + .smsMessage(smsMessage) + .build(); + + MessageRequest msgReq = MessageRequest.builder() + .addresses(addressMap) + .messageConfiguration(direct) + .build(); + + // create a SendMessagesRequest object + SendMessagesRequest request = SendMessagesRequest.builder() + .applicationId(appId) + .messageRequest(msgReq) + .build(); + + SendMessagesResponse response = pinpoint.sendMessages(request); + MessageResponse msg1 = response.messageResponse(); + Map map1 = msg1.result(); + + // Write out the result of sendMessage. + map1.forEach((k, v) -> System.out.println((k + ":" + v))); + + } catch (PinpointException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } } - } } -//snippet-end:[pinpoint.java2.sendmsg.main] +// snippet-end:[pinpoint.java2.sendmsg.main] diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendMessageBatch.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendMessageBatch.java index f80ee2ae0bb..19f372a9892 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendMessageBatch.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendMessageBatch.java @@ -1,16 +1,10 @@ -//snippet-sourcedescription:[SendMessageBatch.java demonstrates how to send batch SMS messages.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; -//snippet-start:[pinpoint.java2.sendmsg.batch.main] -//snippet-start:[pinpoint.java2.sendmsg.batch.import] +// snippet-start:[pinpoint.java2.sendmsg.batch.main] +// snippet-start:[pinpoint.java2.sendmsg.batch.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; import software.amazon.awssdk.services.pinpoint.model.DirectMessageConfiguration; @@ -24,10 +18,11 @@ import software.amazon.awssdk.services.pinpoint.model.PinpointException; import java.util.HashMap; import java.util.Map; -//snippet-end:[pinpoint.java2.sendmsg.batch.import] +// snippet-end:[pinpoint.java2.sendmsg.batch.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -35,97 +30,99 @@ */ public class SendMessageBatch { - // The type of SMS message that you want to send. If you plan to send - // time-sensitive content, specify TRANSACTIONAL. If you plan to send - // marketing-related content, specify PROMOTIONAL. - public static String messageType = "TRANSACTIONAL"; - - // The registered keyword associated with the originating short code. - public static String registeredKeyword = "myKeyword"; - - // The sender ID to use when sending the message. Support for sender ID - // varies by country or region. For more information, see - // https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-countries.html - public static String senderId = "MySenderID"; - - public static void main(String[] args) { - final String usage = """ - - Usage: \s - - Where: - message - The body of the message to send. - appId - The Amazon Pinpoint project/application ID to use when you send this message. - originationNumber - The phone number or short code that you specify has to be associated with your Amazon Pinpoint account. For best results, specify long codes in E.164 format (for example, +1-555-555-5654). - destinationNumber - The recipient's phone number. For best results, you should specify the phone number in E.164 format (for example, +1-555-555-5654). - destinationNumber1 - The second recipient's phone number. For best results, you should specify the phone number in E.164 format (for example, +1-555-555-5654).\s - """; - - if (args.length != 5) { - System.out.println(usage); - System.exit(1); + // The type of SMS message that you want to send. If you plan to send + // time-sensitive content, specify TRANSACTIONAL. If you plan to send + // marketing-related content, specify PROMOTIONAL. + public static String messageType = "TRANSACTIONAL"; + + // The registered keyword associated with the originating short code. + public static String registeredKeyword = "myKeyword"; + + // The sender ID to use when sending the message. Support for sender ID + // varies by country or region. For more information, see + // https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-countries.html + public static String senderId = "MySenderID"; + + public static void main(String[] args) { + final String usage = """ + + Usage: \s + + Where: + message - The body of the message to send. + appId - The Amazon Pinpoint project/application ID to use when you send this message. + originationNumber - The phone number or short code that you specify has to be associated with your Amazon Pinpoint account. For best results, specify long codes in E.164 format (for example, +1-555-555-5654). + destinationNumber - The recipient's phone number. For best results, you should specify the phone number in E.164 format (for example, +1-555-555-5654). + destinationNumber1 - The second recipient's phone number. For best results, you should specify the phone number in E.164 format (for example, +1-555-555-5654).\s + """; + + if (args.length != 5) { + System.out.println(usage); + System.exit(1); + } + + String message = args[0]; + String appId = args[1]; + String originationNumber = args[2]; + String destinationNumber = args[3]; + String destinationNumber1 = args[4]; + System.out.println("Sending a message"); + PinpointClient pinpoint = PinpointClient.builder() + .region(Region.US_EAST_1) + .build(); + + sendSMSMessage(pinpoint, message, appId, originationNumber, destinationNumber, destinationNumber1); + pinpoint.close(); } - String message = args[0]; - String appId = args[1]; - String originationNumber = args[2]; - String destinationNumber = args[3]; - String destinationNumber1 = args[4]; - System.out.println("Sending a message"); - PinpointClient pinpoint = PinpointClient.builder() - .region(Region.US_EAST_1) - .build(); - - sendSMSMessage(pinpoint, message, appId, originationNumber, destinationNumber, destinationNumber1); - pinpoint.close(); - } - - public static void sendSMSMessage(PinpointClient pinpoint, String message, String appId, String originationNumber, String destinationNumber, String destinationNumber1) { - try { - Map addressMap = new HashMap(); - AddressConfiguration addConfig = AddressConfiguration.builder() - .channelType(ChannelType.SMS) - .build(); - - // Add an entry to the Map object for each number to whom you want to send a message. - addressMap.put(destinationNumber, addConfig); - addressMap.put(destinationNumber1, addConfig); - SMSMessage smsMessage = SMSMessage.builder() - .body(message) - .messageType(messageType) - .originationNumber(originationNumber) - .senderId(senderId) - .keyword(registeredKeyword) - .build(); - - // Create a DirectMessageConfiguration object. - DirectMessageConfiguration direct = DirectMessageConfiguration.builder() - .smsMessage(smsMessage) - .build(); - - MessageRequest msgReq = MessageRequest.builder() - .addresses(addressMap) - .messageConfiguration(direct) - .build(); - - // Create a SendMessagesRequest object. - SendMessagesRequest request = SendMessagesRequest.builder() - .applicationId(appId) - .messageRequest(msgReq) - .build(); - - SendMessagesResponse response = pinpoint.sendMessages(request); - MessageResponse msg1 = response.messageResponse(); - Map map1 = msg1.result(); - - // Write out the result of sendMessage. - map1.forEach((k, v) -> System.out.println((k + ":" + v))); - - } catch (PinpointException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + public static void sendSMSMessage(PinpointClient pinpoint, String message, String appId, + String originationNumber, + String destinationNumber, String destinationNumber1) { + try { + Map addressMap = new HashMap(); + AddressConfiguration addConfig = AddressConfiguration.builder() + .channelType(ChannelType.SMS) + .build(); + + // Add an entry to the Map object for each number to whom you want to send a + // message. + addressMap.put(destinationNumber, addConfig); + addressMap.put(destinationNumber1, addConfig); + SMSMessage smsMessage = SMSMessage.builder() + .body(message) + .messageType(messageType) + .originationNumber(originationNumber) + .senderId(senderId) + .keyword(registeredKeyword) + .build(); + + // Create a DirectMessageConfiguration object. + DirectMessageConfiguration direct = DirectMessageConfiguration.builder() + .smsMessage(smsMessage) + .build(); + + MessageRequest msgReq = MessageRequest.builder() + .addresses(addressMap) + .messageConfiguration(direct) + .build(); + + // Create a SendMessagesRequest object. + SendMessagesRequest request = SendMessagesRequest.builder() + .applicationId(appId) + .messageRequest(msgReq) + .build(); + + SendMessagesResponse response = pinpoint.sendMessages(request); + MessageResponse msg1 = response.messageResponse(); + Map map1 = msg1.result(); + + // Write out the result of sendMessage. + map1.forEach((k, v) -> System.out.println((k + ":" + v))); + + } catch (PinpointException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } } - } } -//snippet-end:[pinpoint.java2.sendmsg.batch.main] - +// snippet-end:[pinpoint.java2.sendmsg.batch.main] diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendVoiceMessage.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendVoiceMessage.java index 344b091eaa1..69f727e52e3 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendVoiceMessage.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/SendVoiceMessage.java @@ -1,15 +1,10 @@ -//snippet-sourcedescription:[SendVoiceMessage.java demonstrates how to send a voice message to a phone.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; -//snippet-start:[pinpoint.java2.send_voice_message.main] -//snippet-start:[pinpoint.java2.send_voice_message.import] +// snippet-start:[pinpoint.java2.send_voice_message.main] +// snippet-start:[pinpoint.java2.send_voice_message.import] import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpointsmsvoice.PinpointSmsVoiceClient; @@ -21,10 +16,11 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -//snippet-end:[pinpoint.java2.send_voice_message.import] +// snippet-end:[pinpoint.java2.send_voice_message.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,88 +28,90 @@ */ public class SendVoiceMessage { - // The Amazon Polly voice that you want to use to send the message. For a list - // of voices, see https://docs.aws.amazon.com/polly/latest/dg/voicelist.html - static final String voiceName = "Matthew"; - - // The language to use when sending the message. For a list of supported - // languages, see https://docs.aws.amazon.com/polly/latest/dg/SupportedLanguage.html - static final String languageCode = "en-US"; - - // The content of the message. This example uses SSML to customize and control - // certain aspects of the message, such as by adding pauses and changing - // phonation. The message can't contain any line breaks. - static final String ssmlMessage = "This is a test message sent from " - + "Amazon Pinpoint " - + "using the AWS " - + "SDK for Java. " - + "Thank " - + "you for listening."; - - public static void main(String[] args) { - - final String usage = """ - - Usage: \s - - Where: - originationNumber - The phone number or short code that you specify has to be associated with your Amazon Pinpoint account. For best results, specify long codes in E.164 format (for example, +1-555-555-5654). - destinationNumber - The recipient's phone number. For best results, you should specify the phone number in E.164 format (for example, +1-555-555-5654).\s - """; - - if (args.length != 2) { - System.out.println(usage); - System.exit(1); + // The Amazon Polly voice that you want to use to send the message. For a list + // of voices, see https://docs.aws.amazon.com/polly/latest/dg/voicelist.html + static final String voiceName = "Matthew"; + + // The language to use when sending the message. For a list of supported + // languages, see + // https://docs.aws.amazon.com/polly/latest/dg/SupportedLanguage.html + static final String languageCode = "en-US"; + + // The content of the message. This example uses SSML to customize and control + // certain aspects of the message, such as by adding pauses and changing + // phonation. The message can't contain any line breaks. + static final String ssmlMessage = "This is a test message sent from " + + "Amazon Pinpoint " + + "using the AWS " + + "SDK for Java. " + + "Thank " + + "you for listening."; + + public static void main(String[] args) { + + final String usage = """ + + Usage: \s + + Where: + originationNumber - The phone number or short code that you specify has to be associated with your Amazon Pinpoint account. For best results, specify long codes in E.164 format (for example, +1-555-555-5654). + destinationNumber - The recipient's phone number. For best results, you should specify the phone number in E.164 format (for example, +1-555-555-5654).\s + """; + + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } + + String originationNumber = args[0]; + String destinationNumber = args[1]; + System.out.println("Sending a voice message"); + + // Set the content type to application/json. + List listVal = new ArrayList<>(); + listVal.add("application/json"); + Map> values = new HashMap<>(); + values.put("Content-Type", listVal); + + ClientOverrideConfiguration config2 = ClientOverrideConfiguration.builder() + .headers(values) + .build(); + + PinpointSmsVoiceClient client = PinpointSmsVoiceClient.builder() + .overrideConfiguration(config2) + .region(Region.US_EAST_1) + .build(); + + sendVoiceMsg(client, originationNumber, destinationNumber); + client.close(); } - String originationNumber = args[0]; - String destinationNumber = args[1]; - System.out.println("Sending a voice message"); - - // Set the content type to application/json. - List listVal = new ArrayList<>(); - listVal.add("application/json"); - Map> values = new HashMap<>(); - values.put("Content-Type", listVal); - - ClientOverrideConfiguration config2 = ClientOverrideConfiguration.builder() - .headers(values) - .build(); - - PinpointSmsVoiceClient client = PinpointSmsVoiceClient.builder() - .overrideConfiguration(config2) - .region(Region.US_EAST_1) - .build(); - - sendVoiceMsg(client, originationNumber, destinationNumber); - client.close(); - } - - public static void sendVoiceMsg(PinpointSmsVoiceClient client, String originationNumber, String destinationNumber) { - try { - SSMLMessageType ssmlMessageType = SSMLMessageType.builder() - .languageCode(languageCode) - .text(ssmlMessage) - .voiceId(voiceName) - .build(); - - VoiceMessageContent content = VoiceMessageContent.builder() - .ssmlMessage(ssmlMessageType) - .build(); - - SendVoiceMessageRequest voiceMessageRequest = SendVoiceMessageRequest.builder() - .destinationPhoneNumber(destinationNumber) - .originationPhoneNumber(originationNumber) - .content(content) - .build(); - - client.sendVoiceMessage(voiceMessageRequest); - System.out.println("The message was sent successfully."); - - } catch (PinpointSmsVoiceException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + public static void sendVoiceMsg(PinpointSmsVoiceClient client, String originationNumber, + String destinationNumber) { + try { + SSMLMessageType ssmlMessageType = SSMLMessageType.builder() + .languageCode(languageCode) + .text(ssmlMessage) + .voiceId(voiceName) + .build(); + + VoiceMessageContent content = VoiceMessageContent.builder() + .ssmlMessage(ssmlMessageType) + .build(); + + SendVoiceMessageRequest voiceMessageRequest = SendVoiceMessageRequest.builder() + .destinationPhoneNumber(destinationNumber) + .originationPhoneNumber(originationNumber) + .content(content) + .build(); + + client.sendVoiceMessage(voiceMessageRequest); + System.out.println("The message was sent successfully."); + + } catch (PinpointSmsVoiceException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } } - } } -//snippet-end:[pinpoint.java2.send_voice_message.main] +// snippet-end:[pinpoint.java2.send_voice_message.main] diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/UpdateChannel.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/UpdateChannel.java index d146417dc5e..921ebc02434 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/UpdateChannel.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/UpdateChannel.java @@ -1,14 +1,10 @@ -//snippet-sourcedescription:[UpdateChannel.java demonstrates how to update a channel for an Amazon Pinpoint application.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.pinpoint; -//snippet-start:[pinpoint.java2.updatechannel.main] -//snippet-start:[pinpoint.java2.updatechannel.import] +// snippet-start:[pinpoint.java2.updatechannel.main] +// snippet-start:[pinpoint.java2.updatechannel.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; import software.amazon.awssdk.services.pinpoint.model.SMSChannelResponse; @@ -17,10 +13,11 @@ import software.amazon.awssdk.services.pinpoint.model.SMSChannelRequest; import software.amazon.awssdk.services.pinpoint.model.UpdateSmsChannelRequest; import software.amazon.awssdk.services.pinpoint.model.UpdateSmsChannelResponse; -//snippet-end:[pinpoint.java2.updatechannel.import] +// snippet-end:[pinpoint.java2.updatechannel.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,12 +27,12 @@ public class UpdateChannel { public static void main(String[] args) { final String usage = """ - Usage: CreateChannel + Usage: CreateChannel - Where: - appId - The name of the application whose channel is updated. + Where: + appId - The name of the application whose channel is updated. - """; + """; if (args.length != 1) { System.out.println(usage); @@ -44,8 +41,8 @@ public static void main(String[] args) { String appId = args[0]; PinpointClient pinpoint = PinpointClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); SMSChannelResponse getResponse = getSMSChannel(pinpoint, appId); toggleSmsChannel(pinpoint, appId, getResponse); @@ -55,8 +52,8 @@ public static void main(String[] args) { private static SMSChannelResponse getSMSChannel(PinpointClient client, String appId) { try { GetSmsChannelRequest request = GetSmsChannelRequest.builder() - .applicationId(appId) - .build(); + .applicationId(appId) + .build(); SMSChannelResponse response = client.getSmsChannel(request).smsChannelResponse(); System.out.println("Channel state is " + response.enabled()); @@ -73,13 +70,13 @@ private static void toggleSmsChannel(PinpointClient client, String appId, SMSCha boolean enabled = !getResponse.enabled(); try { SMSChannelRequest request = SMSChannelRequest.builder() - .enabled(enabled) - .build(); + .enabled(enabled) + .build(); UpdateSmsChannelRequest updateRequest = UpdateSmsChannelRequest.builder() - .smsChannelRequest(request) - .applicationId(appId) - .build(); + .smsChannelRequest(request) + .applicationId(appId) + .build(); UpdateSmsChannelResponse result = client.updateSmsChannel(updateRequest); System.out.println("Channel state: " + result.smsChannelResponse().enabled()); @@ -90,4 +87,4 @@ private static void toggleSmsChannel(PinpointClient client, String appId, SMSCha } } } -//snippet-end:[pinpoint.java2.updatechannel.main] \ No newline at end of file +// snippet-end:[pinpoint.java2.updatechannel.main] \ No newline at end of file diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/UpdateEmailChannel.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/UpdateEmailChannel.java index 6149fdbb638..fcea4795261 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/UpdateEmailChannel.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/UpdateEmailChannel.java @@ -1,20 +1,18 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; -//snippet-start:[pinpoint.java2.updateemailchannel.import] +// snippet-start:[pinpoint.java2.updateemailchannel.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; import software.amazon.awssdk.services.pinpoint.model.*; -//snippet-end:[pinpoint.java2.updateemailchannel.import] +// snippet-end:[pinpoint.java2.updateemailchannel.import] public class UpdateEmailChannel { - //snippet-start:[pinpoint.java2.updateemailchannel.main] + // snippet-start:[pinpoint.java2.updateemailchannel.main] public static void main(String[] args) { - //TODO: Provide ApplicationId/ProjectId + // TODO: Provide ApplicationId/ProjectId String appId = ""; PinpointClient pinpoint = PinpointClient.builder() .region(Region.US_EAST_1) @@ -25,13 +23,13 @@ public static void main(String[] args) { System.out.println("Response : " + getResponse); pinpoint.close(); } - //snippet-end:[pinpoint.java2.updateemailchannel.main] + // snippet-end:[pinpoint.java2.updateemailchannel.main] - //snippet-start:[pinpoint.java2.updateemailchannel.helper] + // snippet-start:[pinpoint.java2.updateemailchannel.helper] private static EmailChannelResponse getEmailChannel(PinpointClient client, String appId) { try { - //TODO: Update personal identity and from address + // TODO: Update personal identity and from address UpdateEmailChannelRequest updateRequest = UpdateEmailChannelRequest.builder() .applicationId(appId) .emailChannelRequest(EmailChannelRequest.builder() @@ -52,5 +50,5 @@ private static EmailChannelResponse getEmailChannel(PinpointClient client, Strin } return null; } - //snippet-end:[pinpoint.java2.updateemailchannel.helper] + // snippet-end:[pinpoint.java2.updateemailchannel.helper] } diff --git a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/UpdateEndpoint.java b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/UpdateEndpoint.java index 2417b3f4508..fb4990908ae 100644 --- a/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/UpdateEndpoint.java +++ b/javav2/example_code/pinpoint/src/main/java/com/example/pinpoint/UpdateEndpoint.java @@ -1,16 +1,10 @@ -//snippet-sourcedescription:[CreateEndpoint.java demonstrates how to update an endpoint for an application in Amazon Pinpoint.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon Pinpoint] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.pinpoint; -//snippet-start:[pinpoint.java2.createendpoint.main] -//snippet-start:[pinpoint.java2.createendpoint.import] +// snippet-start:[pinpoint.java2.createendpoint.main] +// snippet-start:[pinpoint.java2.createendpoint.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.pinpoint.PinpointClient; import software.amazon.awssdk.services.pinpoint.model.EndpointResponse; @@ -31,11 +25,11 @@ import java.util.HashMap; import java.util.Map; import java.util.Date; -//snippet-end:[pinpoint.java2.createendpoint.import] - +// snippet-end:[pinpoint.java2.createendpoint.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -45,12 +39,12 @@ public class UpdateEndpoint { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - appId - The ID of the application to create an endpoint for. + Where: + appId - The ID of the application to create an endpoint for. - """; + """; if (args.length != 1) { System.out.println(usage); @@ -59,15 +53,15 @@ public static void main(String[] args) { String appId = args[0]; PinpointClient pinpoint = PinpointClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); EndpointResponse response = createEndpoint(pinpoint, appId); System.out.println("Got Endpoint: " + response.id()); pinpoint.close(); } - //snippet-start:[pinpoint.java2.createendpoint.helper] + // snippet-start:[pinpoint.java2.createendpoint.helper] public static EndpointResponse createEndpoint(PinpointClient client, String appId) { String endpointId = UUID.randomUUID().toString(); System.out.println("Endpoint ID: " + endpointId); @@ -75,18 +69,18 @@ public static EndpointResponse createEndpoint(PinpointClient client, String appI try { EndpointRequest endpointRequest = createEndpointRequestData(); UpdateEndpointRequest updateEndpointRequest = UpdateEndpointRequest.builder() - .applicationId(appId) - .endpointId(endpointId) - .endpointRequest(endpointRequest) - .build(); + .applicationId(appId) + .endpointId(endpointId) + .endpointRequest(endpointRequest) + .build(); UpdateEndpointResponse updateEndpointResponse = client.updateEndpoint(updateEndpointRequest); System.out.println("Update Endpoint Response: " + updateEndpointResponse.messageBody()); GetEndpointRequest getEndpointRequest = GetEndpointRequest.builder() - .applicationId(appId) - .endpointId(endpointId) - .build(); + .applicationId(appId) + .endpointId(endpointId) + .build(); GetEndpointResponse getEndpointResponse = client.getEndpoint(getEndpointRequest); System.out.println(getEndpointResponse.endpointResponse().address()); @@ -114,47 +108,48 @@ private static EndpointRequest createEndpointRequestData() { customAttributes.put("team", favoriteTeams); EndpointDemographic demographic = EndpointDemographic.builder() - .appVersion("1.0") - .make("apple") - .model("iPhone") - .modelVersion("7") - .platform("ios") - .platformVersion("10.1.1") - .timezone("America/Los_Angeles") - .build(); + .appVersion("1.0") + .make("apple") + .model("iPhone") + .modelVersion("7") + .platform("ios") + .platformVersion("10.1.1") + .timezone("America/Los_Angeles") + .build(); EndpointLocation location = EndpointLocation.builder() - .city("Los Angeles") - .country("US") - .latitude(34.0) - .longitude(-118.2) - .postalCode("90068") - .region("CA") - .build(); + .city("Los Angeles") + .country("US") + .latitude(34.0) + .longitude(-118.2) + .postalCode("90068") + .region("CA") + .build(); Map metrics = new HashMap<>(); metrics.put("health", 100.00); metrics.put("luck", 75.00); EndpointUser user = EndpointUser.builder() - .userId(UUID.randomUUID().toString()) - .build(); + .userId(UUID.randomUUID().toString()) + .build(); - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); // Quoted "Z" to indicate UTC, no timezone offset + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); // Quoted "Z" to indicate UTC, no timezone + // offset String nowAsISO = df.format(new Date()); return EndpointRequest.builder() - .address(UUID.randomUUID().toString()) - .attributes(customAttributes) - .channelType("APNS") - .demographic(demographic) - .effectiveDate(nowAsISO) - .location(location) - .metrics(metrics) - .optOut("NONE") - .requestId(UUID.randomUUID().toString()) - .user(user) - .build(); + .address(UUID.randomUUID().toString()) + .attributes(customAttributes) + .channelType("APNS") + .demographic(demographic) + .effectiveDate(nowAsISO) + .location(location) + .metrics(metrics) + .optOut("NONE") + .requestId(UUID.randomUUID().toString()) + .user(user) + .build(); } catch (PinpointException e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -162,6 +157,6 @@ private static EndpointRequest createEndpointRequestData() { } return null; } - //snippet-end:[pinpoint.java2.createendpoint.helper] + // snippet-end:[pinpoint.java2.createendpoint.helper] } - //snippet-end:[pinpoint.java2.createendpoint.main] \ No newline at end of file +// snippet-end:[pinpoint.java2.createendpoint.main] \ No newline at end of file diff --git a/javav2/example_code/pinpoint/src/test/java/AmazonPinpointTest.java b/javav2/example_code/pinpoint/src/test/java/AmazonPinpointTest.java index b6a67fe795a..de577805810 100644 --- a/javav2/example_code/pinpoint/src/test/java/AmazonPinpointTest.java +++ b/javav2/example_code/pinpoint/src/test/java/AmazonPinpointTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.google.gson.Gson; import org.junit.jupiter.api.*; @@ -38,9 +36,9 @@ public class AmazonPinpointTest { private static String appId = ""; private static String endpointId2 = ""; private static String bucket = ""; - private static String path= ""; - private static String roleArn= ""; - private static String segmentId= ""; + private static String path = ""; + private static String roleArn = ""; + private static String segmentId = ""; private static String userId = ""; private static String s3BucketName = ""; private static String iamExportRoleArn = ""; @@ -57,9 +55,9 @@ public class AmazonPinpointTest { @BeforeAll public static void setUp() throws IOException { pinpoint = PinpointClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); pinpointEmailClient = PinpointEmailClient.builder() .region(Region.US_EAST_1) @@ -67,9 +65,9 @@ public static void setUp() throws IOException { .build(); s3Client = S3Client.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Set the content type to application/json. List listVal = new ArrayList<>(); @@ -82,64 +80,67 @@ public static void setUp() throws IOException { .build(); voiceClient = PinpointSmsVoiceClient.builder() - .overrideConfiguration(config2) - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .overrideConfiguration(config2) + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); String json = getSecretValues(); SecretValues valuesOb = gson.fromJson(json, SecretValues.class); appName = valuesOb.getAppName(); - bucket= valuesOb.getBucket(); + bucket = valuesOb.getBucket(); path = valuesOb.getPath(); - roleArn= valuesOb.getRoleArn(); + roleArn = valuesOb.getRoleArn(); userId = valuesOb.getUserId(); s3BucketName = valuesOb.getS3BucketName(); iamExportRoleArn = valuesOb.getIamExportRoleArn(); - existingApplicationId= valuesOb.getExistingApplicationId(); + existingApplicationId = valuesOb.getExistingApplicationId(); subject = valuesOb.getSubject(); senderAddress = valuesOb.getSenderAddress(); toAddress = valuesOb.getToAddress(); - originationNumber= valuesOb.getOriginationNumber(); - destinationNumber= valuesOb.getDestinationNumber(); + originationNumber = valuesOb.getOriginationNumber(); + destinationNumber = valuesOb.getDestinationNumber(); destinationNumber1 = valuesOb.getDestinationNumber1(); - message= valuesOb.getMessage(); - - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - - try (InputStream input = AmazonPinpointTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - // Populate the data members required for all tests - prop.load(input); - appName = prop.getProperty("appName"); - bucket= prop.getProperty("bucket"); - path= prop.getProperty("path"); - roleArn= prop.getProperty("roleArn"); - userId = prop.getProperty("userId"); - s3BucketName = prop.getProperty("s3BucketName"); - s3BucketName = prop.getProperty("s3BucketName"); - iamExportRoleArn = prop.getProperty("iamExportRoleArn"); - existingApplicationId= prop.getProperty("existingApplicationId"); - subject = prop.getProperty("subject"); - senderAddress = prop.getProperty("senderAddress"); - toAddress = prop.getProperty("toAddress"); - originationNumber= prop.getProperty("originationNumber"); - destinationNumber= prop.getProperty("destinationNumber"); - destinationNumber1 = prop.getProperty("destinationNumber1"); - message= prop.getProperty("message"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + message = valuesOb.getMessage(); + + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * + * try (InputStream input = + * AmazonPinpointTest.class.getClassLoader().getResourceAsStream( + * "config.properties")) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * // Populate the data members required for all tests + * prop.load(input); + * appName = prop.getProperty("appName"); + * bucket= prop.getProperty("bucket"); + * path= prop.getProperty("path"); + * roleArn= prop.getProperty("roleArn"); + * userId = prop.getProperty("userId"); + * s3BucketName = prop.getProperty("s3BucketName"); + * s3BucketName = prop.getProperty("s3BucketName"); + * iamExportRoleArn = prop.getProperty("iamExportRoleArn"); + * existingApplicationId= prop.getProperty("existingApplicationId"); + * subject = prop.getProperty("subject"); + * senderAddress = prop.getProperty("senderAddress"); + * toAddress = prop.getProperty("toAddress"); + * originationNumber= prop.getProperty("originationNumber"); + * destinationNumber= prop.getProperty("destinationNumber"); + * destinationNumber1 = prop.getProperty("destinationNumber1"); + * message= prop.getProperty("message"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @@ -156,7 +157,7 @@ public void CreateApp() { @Order(2) public void UpdateEndpoint() { EndpointResponse response = UpdateEndpoint.createEndpoint(pinpoint, appId); - endpointId2 = response.id() ; + endpointId2 = response.id(); assertFalse(endpointId2.isEmpty()); System.out.println("UpdateEndpoint test passed"); } @@ -165,7 +166,7 @@ public void UpdateEndpoint() { @Tag("IntegrationTest") @Order(3) public void LookUpEndpoint() { - assertDoesNotThrow(() ->LookUpEndpoint.lookupPinpointEndpoint(pinpoint, appId, endpointId2)); + assertDoesNotThrow(() -> LookUpEndpoint.lookupPinpointEndpoint(pinpoint, appId, endpointId2)); System.out.println("LookUpEndpoint test passed"); } @@ -173,7 +174,7 @@ public void LookUpEndpoint() { @Tag("IntegrationTest") @Order(5) public void AddExampleUser() { - assertDoesNotThrow(() ->AddExampleUser.updatePinpointEndpoint(pinpoint,appId,endpointId2)); + assertDoesNotThrow(() -> AddExampleUser.updatePinpointEndpoint(pinpoint, appId, endpointId2)); System.out.println("AddExampleUser test passed"); } @@ -181,7 +182,7 @@ public void AddExampleUser() { @Tag("IntegrationTest") @Order(6) public void AddExampleEndpoints() { - assertDoesNotThrow(() -> AddExampleEndpoints.updateEndpointsViaBatch(pinpoint,appId)); + assertDoesNotThrow(() -> AddExampleEndpoints.updateEndpointsViaBatch(pinpoint, appId)); System.out.println("AddExampleEndpoints test passed"); } @@ -189,7 +190,7 @@ public void AddExampleEndpoints() { @Tag("IntegrationTest") @Order(7) public void DeleteEndpoint() { - assertDoesNotThrow(() ->DeleteEndpoint.deletePinEncpoint(pinpoint, appId, endpointId2)); + assertDoesNotThrow(() -> DeleteEndpoint.deletePinEncpoint(pinpoint, appId, endpointId2)); System.out.println("DeleteEndpoint test passed"); } @@ -197,15 +198,17 @@ public void DeleteEndpoint() { @Tag("IntegrationTest") @Order(8) public void SendMessage() { - assertDoesNotThrow(() ->SendMessage.sendSMSMessage(pinpoint, message, existingApplicationId, originationNumber, destinationNumber)); - System.out.println("SendMessage test passed"); + assertDoesNotThrow(() -> SendMessage.sendSMSMessage(pinpoint, message, existingApplicationId, originationNumber, + destinationNumber)); + System.out.println("SendMessage test passed"); } @Test @Tag("IntegrationTest") @Order(9) - public void ImportSegments() { - assertDoesNotThrow(() -> SendMessageBatch.sendSMSMessage(pinpoint, message, "2fdc4442c6a2483f85eaf7a943054815", originationNumber, destinationNumber, destinationNumber)); + public void ImportSegments() { + assertDoesNotThrow(() -> SendMessageBatch.sendSMSMessage(pinpoint, message, "2fdc4442c6a2483f85eaf7a943054815", + originationNumber, destinationNumber, destinationNumber)); System.out.println("ImportSegments test passed"); } @@ -221,25 +224,26 @@ public void ListSegments() { @Tag("IntegrationTest") @Order(11) public void CreateSegment() { - SegmentResponse createSegmentResult = CreateSegment.createSegment(pinpoint, existingApplicationId); - segmentId = createSegmentResult.id(); + SegmentResponse createSegmentResult = CreateSegment.createSegment(pinpoint, existingApplicationId); + segmentId = createSegmentResult.id(); assertFalse(segmentId.isEmpty()); System.out.println("CreateSegment test passed"); - } + } @Test @Tag("IntegrationTest") @Order(12) public void CreateCampaign() { - assertDoesNotThrow(() -> CreateCampaign.createPinCampaign(pinpoint, existingApplicationId, segmentId)); - System.out.println("CreateCampaign test passed"); + assertDoesNotThrow(() -> CreateCampaign.createPinCampaign(pinpoint, existingApplicationId, segmentId)); + System.out.println("CreateCampaign test passed"); } @Test @Tag("IntegrationTest") @Order(13) public void ExportEndpoints() { - assertDoesNotThrow(() -> ExportEndpoints.exportAllEndpoints(pinpoint, s3Client, existingApplicationId, s3BucketName, filePath, iamExportRoleArn)); + assertDoesNotThrow(() -> ExportEndpoints.exportAllEndpoints(pinpoint, s3Client, existingApplicationId, + s3BucketName, filePath, iamExportRoleArn)); System.out.println("ExportEndpoints test passed"); } @@ -249,41 +253,42 @@ public void ExportEndpoints() { public void SendEmailMessage() { assertDoesNotThrow(() -> SendEmailMessage.sendEmail(pinpointEmailClient, subject, senderAddress, toAddress)); System.out.println("SendEmailMessage test passed"); - } + } @Test @Tag("IntegrationTest") @Order(15) - public void SendVoiceMessage() { - assertDoesNotThrow(() ->SendVoiceMessage.sendVoiceMsg(voiceClient, originationNumber, destinationNumber)); + public void SendVoiceMessage() { + assertDoesNotThrow(() -> SendVoiceMessage.sendVoiceMsg(voiceClient, originationNumber, destinationNumber)); System.out.println("SendVoiceMessage test passed"); - } + } @Test @Tag("IntegrationTest") @Order(16) - public void ListEndpointIds() { - assertDoesNotThrow(() ->ListEndpointIds.listAllEndpoints(pinpoint, existingApplicationId, userId)); + public void ListEndpointIds() { + assertDoesNotThrow(() -> ListEndpointIds.listAllEndpoints(pinpoint, existingApplicationId, userId)); System.out.println("ListEndpointIds test passed"); - } + } @Test @Tag("IntegrationTest") @Order(17) public void DeleteApp() { - assertDoesNotThrow(() ->DeleteApp.deletePinApp(pinpoint, appId)); - System.out.println("DeleteApp test passed"); + assertDoesNotThrow(() -> DeleteApp.deletePinApp(pinpoint, appId)); + System.out.println("DeleteApp test passed"); } + public static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/pinpoint"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -319,6 +324,7 @@ class SecretValues { private String destinationNumber1; private String message; + public String getAppName() { return appName; } @@ -381,4 +387,3 @@ public String getMessage() { } } - diff --git a/javav2/example_code/polly/src/main/java/com/example/polly/DescribeVoicesSample.java b/javav2/example_code/polly/src/main/java/com/example/polly/DescribeVoicesSample.java index 636d3492643..50b98c739ac 100644 --- a/javav2/example_code/polly/src/main/java/com/example/polly/DescribeVoicesSample.java +++ b/javav2/example_code/polly/src/main/java/com/example/polly/DescribeVoicesSample.java @@ -1,11 +1,5 @@ -// snippet-sourcedescription:[DescribeVoicesSample Produces a list of all voices available for use when requesting speech synthesis with Amazon Polly..] -//snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Polly] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.polly; @@ -21,7 +15,8 @@ // snippet-end:[polly.java2.describe_voice.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,8 +25,8 @@ public class DescribeVoicesSample { public static void main(String args[]) { PollyClient polly = PollyClient.builder() - .region(Region.US_WEST_2) - .build(); + .region(Region.US_WEST_2) + .build(); describeVoice(polly); polly.close(); @@ -40,8 +35,8 @@ public static void main(String args[]) { public static void describeVoice(PollyClient polly) { try { DescribeVoicesRequest voicesRequest = DescribeVoicesRequest.builder() - .languageCode("en-US") - .build(); + .languageCode("en-US") + .build(); DescribeVoicesResponse enUsVoicesResult = polly.describeVoices(voicesRequest); List voices = enUsVoicesResult.voices(); diff --git a/javav2/example_code/polly/src/main/java/com/example/polly/ListLexicons.java b/javav2/example_code/polly/src/main/java/com/example/polly/ListLexicons.java index d84b97f6108..6979ef4b9c1 100644 --- a/javav2/example_code/polly/src/main/java/com/example/polly/ListLexicons.java +++ b/javav2/example_code/polly/src/main/java/com/example/polly/ListLexicons.java @@ -1,11 +1,5 @@ -// snippet-sourcedescription:[ListLexicons demonstrates how to produce a list of pronunciation lexicons stored in an AWS Region.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Polly] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.polly; @@ -16,12 +10,13 @@ import software.amazon.awssdk.services.polly.model.ListLexiconsResponse; import software.amazon.awssdk.services.polly.model.ListLexiconsRequest; import software.amazon.awssdk.services.polly.model.LexiconDescription; -import software.amazon.awssdk.services.polly.model.PollyException ; +import software.amazon.awssdk.services.polly.model.PollyException; import java.util.List; // snippet-end:[polly.java2.list_icons.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,8 +25,8 @@ public class ListLexicons { public static void main(String args[]) { PollyClient polly = PollyClient.builder() - .region(Region.US_WEST_2) - .build(); + .region(Region.US_WEST_2) + .build(); listLexicons(polly); polly.close(); @@ -40,7 +35,7 @@ public static void main(String args[]) { public static void listLexicons(PollyClient client) { try { ListLexiconsRequest listLexiconsRequest = ListLexiconsRequest.builder() - .build(); + .build(); ListLexiconsResponse listLexiconsResult = client.listLexicons(listLexiconsRequest); List lexiconDescription = listLexiconsResult.lexicons(); diff --git a/javav2/example_code/polly/src/main/java/com/example/polly/PollyDemo.java b/javav2/example_code/polly/src/main/java/com/example/polly/PollyDemo.java index fd6198d4afd..65f154ef3df 100644 --- a/javav2/example_code/polly/src/main/java/com/example/polly/PollyDemo.java +++ b/javav2/example_code/polly/src/main/java/com/example/polly/PollyDemo.java @@ -1,11 +1,5 @@ -// snippet-sourcedescription:[PollyDemo demonstrates how to convert text into speech.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Polly] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.polly; @@ -30,7 +24,8 @@ // snippet-end:[polly.java2.demo.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -38,13 +33,14 @@ */ public class PollyDemo { private static final String SAMPLE = "Congratulations. You have successfully built this working demo " + - " of Amazon Polly in Java Version 2. Have fun building voice enabled apps with Amazon Polly (that's me!), and always " + - " look at the AWS website for tips and tricks on using Amazon Polly and other great services from AWS"; + " of Amazon Polly in Java Version 2. Have fun building voice enabled apps with Amazon Polly (that's me!), and always " + + + " look at the AWS website for tips and tricks on using Amazon Polly and other great services from AWS"; public static void main(String args[]) { PollyClient polly = PollyClient.builder() - .region(Region.US_WEST_2) - .build(); + .region(Region.US_WEST_2) + .build(); talkPolly(polly); polly.close(); @@ -53,16 +49,17 @@ public static void main(String args[]) { public static void talkPolly(PollyClient polly) { try { DescribeVoicesRequest describeVoiceRequest = DescribeVoicesRequest.builder() - .engine("standard") - .build(); + .engine("standard") + .build(); DescribeVoicesResponse describeVoicesResult = polly.describeVoices(describeVoiceRequest); Voice voice = describeVoicesResult.voices().stream() - .filter(v -> v.name().equals("Joanna")) - .findFirst() - .orElseThrow(() -> new RuntimeException("Voice not found")); + .filter(v -> v.name().equals("Joanna")) + .findFirst() + .orElseThrow(() -> new RuntimeException("Voice not found")); InputStream stream = synthesize(polly, SAMPLE, voice, OutputFormat.MP3); - AdvancedPlayer player = new AdvancedPlayer(stream, javazoom.jl.player.FactoryRegistry.systemRegistry().createAudioDevice()); + AdvancedPlayer player = new AdvancedPlayer(stream, + javazoom.jl.player.FactoryRegistry.systemRegistry().createAudioDevice()); player.setPlayBackListener(new PlaybackListener() { public void playbackStarted(PlaybackEvent evt) { System.out.println("Playback started"); @@ -83,12 +80,13 @@ public void playbackFinished(PlaybackEvent evt) { } } - public static InputStream synthesize(PollyClient polly, String text, Voice voice, OutputFormat format) throws IOException { + public static InputStream synthesize(PollyClient polly, String text, Voice voice, OutputFormat format) + throws IOException { SynthesizeSpeechRequest synthReq = SynthesizeSpeechRequest.builder() - .text(text) - .voiceId(voice.id()) - .outputFormat(format) - .build(); + .text(text) + .voiceId(voice.id()) + .outputFormat(format) + .build(); ResponseInputStream synthRes = polly.synthesizeSpeech(synthReq); return synthRes; diff --git a/javav2/example_code/polly/src/test/java/AWSPollyTest.java b/javav2/example_code/polly/src/test/java/AWSPollyTest.java index 980a513e8bb..0c6fc0a9ed3 100644 --- a/javav2/example_code/polly/src/test/java/AWSPollyTest.java +++ b/javav2/example_code/polly/src/test/java/AWSPollyTest.java @@ -1,44 +1,46 @@ -import com.example.polly.DescribeVoicesSample; -import com.example.polly.ListLexicons; -import com.example.polly.PollyDemo; -import org.junit.jupiter.api.*; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; -import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.polly.PollyClient; -import java.io.*; - -@TestInstance(TestInstance.Lifecycle.PER_METHOD) -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) - -public class AWSPollyTest { - private static PollyClient polly; - - @BeforeAll - public static void setUp() { - polly = PollyClient.builder() - .region(Region.US_WEST_2) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); - } - - @Test - @Tag("IntegrationTest") - @Order(1) - public void describeVoicesSample() { - assertDoesNotThrow(() ->DescribeVoicesSample.describeVoice(polly)); - System.out.println("describeVoicesSample test passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(2) - public void listLexicons() { - assertDoesNotThrow(() ->ListLexicons.listLexicons(polly)); - System.out.println("listLexicons test passed"); - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +import com.example.polly.DescribeVoicesSample; +import com.example.polly.ListLexicons; +import com.example.polly.PollyDemo; +import org.junit.jupiter.api.*; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; +import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.polly.PollyClient; +import java.io.*; + +@TestInstance(TestInstance.Lifecycle.PER_METHOD) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) + +public class AWSPollyTest { + private static PollyClient polly; + + @BeforeAll + public static void setUp() { + polly = PollyClient.builder() + .region(Region.US_WEST_2) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); + } + + @Test + @Tag("IntegrationTest") + @Order(1) + public void describeVoicesSample() { + assertDoesNotThrow(() ->DescribeVoicesSample.describeVoice(polly)); + System.out.println("describeVoicesSample test passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(2) + public void listLexicons() { + assertDoesNotThrow(() ->ListLexicons.listLexicons(polly)); + System.out.println("listLexicons test passed"); + } +} diff --git a/javav2/example_code/quicksight/src/main/java/com/example/quicksight/DescribeAnalysis.java b/javav2/example_code/quicksight/src/main/java/com/example/quicksight/DescribeAnalysis.java index c806e18b0d3..fc3fe5ef6a3 100644 --- a/javav2/example_code/quicksight/src/main/java/com/example/quicksight/DescribeAnalysis.java +++ b/javav2/example_code/quicksight/src/main/java/com/example/quicksight/DescribeAnalysis.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeAnalysis.java demonstrates how to obtain a summary of the metadata for an analysis.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon QuickSight] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.quicksight; @@ -19,7 +13,8 @@ // snippet-end:[quicksight.java2.describe_analysis.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,13 +24,13 @@ public class DescribeAnalysis { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - account - The ID of the AWS account that contains the analysis. - queueName - The ID of the Amazon QuickSight Analysis that you're describing. + Where: + account - The ID of the AWS account that contains the analysis. + queueName - The ID of the Amazon QuickSight Analysis that you're describing. - """; + """; if (args.length != 2) { System.out.println(usage); @@ -45,8 +40,8 @@ public static void main(String[] args) { String account = args[0]; String analysisId = args[1]; QuickSightClient qsClient = QuickSightClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); describeSpecificAnalysis(qsClient, account, analysisId); qsClient.close(); @@ -55,9 +50,9 @@ public static void main(String[] args) { public static void describeSpecificAnalysis(QuickSightClient qsClient, String account, String analysisId) { try { DescribeAnalysisRequest analysisRequest = DescribeAnalysisRequest.builder() - .awsAccountId(account) - .analysisId(analysisId) - .build(); + .awsAccountId(account) + .analysisId(analysisId) + .build(); DescribeAnalysisResponse analysisResponse = qsClient.describeAnalysis(analysisRequest); System.out.println("The Analysis ARN value is " + analysisResponse.analysis().arn()); @@ -72,4 +67,3 @@ public static void describeSpecificAnalysis(QuickSightClient qsClient, String ac } } // snippet-end:[quicksight.java2.describe_analysis.main] - diff --git a/javav2/example_code/quicksight/src/main/java/com/example/quicksight/DescribeDashboard.java b/javav2/example_code/quicksight/src/main/java/com/example/quicksight/DescribeDashboard.java index a92df6c8edb..c53bd3b96e4 100644 --- a/javav2/example_code/quicksight/src/main/java/com/example/quicksight/DescribeDashboard.java +++ b/javav2/example_code/quicksight/src/main/java/com/example/quicksight/DescribeDashboard.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeAnalysis.java demonstrates how to obtain information about a dashboard.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon QuickSight] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.quicksight; @@ -19,7 +13,8 @@ // snippet-end:[quicksight.java2.describe_dashboard.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,12 +25,12 @@ public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - account - The ID of the AWS account. - dashboardId - The ID of the Amazon QuickSight Dashboard to describe. - """; + Where: + account - The ID of the AWS account. + dashboardId - The ID of the Amazon QuickSight Dashboard to describe. + """; if (args.length != 2) { System.out.println(usage); @@ -45,8 +40,8 @@ public static void main(String[] args) { String account = args[0]; String dashboardId = args[1]; QuickSightClient qsClient = QuickSightClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); describeSpecificDashboard(qsClient, account, dashboardId); qsClient.close(); @@ -55,9 +50,9 @@ public static void main(String[] args) { public static void describeSpecificDashboard(QuickSightClient qsClient, String account, String dashboardId) { try { DescribeDashboardRequest analysesRequest = DescribeDashboardRequest.builder() - .awsAccountId(account) - .dashboardId(dashboardId) - .build(); + .awsAccountId(account) + .dashboardId(dashboardId) + .build(); DescribeDashboardResponse res = qsClient.describeDashboard(analysesRequest); System.out.println("The display name is " + res.dashboard().name()); @@ -69,4 +64,3 @@ public static void describeSpecificDashboard(QuickSightClient qsClient, String a } } // snippet-end:[quicksight.java2.describe_dashboard.main] - diff --git a/javav2/example_code/quicksight/src/main/java/com/example/quicksight/DescribeTemplate.java b/javav2/example_code/quicksight/src/main/java/com/example/quicksight/DescribeTemplate.java index 92008a68a8a..6eaa4733c7d 100644 --- a/javav2/example_code/quicksight/src/main/java/com/example/quicksight/DescribeTemplate.java +++ b/javav2/example_code/quicksight/src/main/java/com/example/quicksight/DescribeTemplate.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeTemplate.java demonstrates how to obtain information about a template.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon QuickSight] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.quicksight; @@ -19,7 +13,8 @@ // snippet-end:[quicksight.java2.describe_template.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,12 +25,12 @@ public class DescribeTemplate { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - account - The ID of the AWS account. - templateId - The ID of the Amazon QuickSight template to describe. - """; + Where: + account - The ID of the AWS account. + templateId - The ID of the Amazon QuickSight template to describe. + """; if (args.length != 2) { System.out.println(usage); @@ -45,8 +40,8 @@ public static void main(String[] args) { String account = args[0]; String templateId = args[1]; QuickSightClient qsClient = QuickSightClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); describeSpecificTemplate(qsClient, account, templateId); qsClient.close(); @@ -55,9 +50,9 @@ public static void main(String[] args) { public static void describeSpecificTemplate(QuickSightClient qsClient, String account, String templateId) { try { DescribeTemplateRequest temRequest = DescribeTemplateRequest.builder() - .awsAccountId(account) - .templateId(templateId) - .build(); + .awsAccountId(account) + .templateId(templateId) + .build(); DescribeTemplateResponse templateResponse = qsClient.describeTemplate(temRequest); System.out.println("The template ARN is " + templateResponse.template().arn()); @@ -68,6 +63,4 @@ public static void describeSpecificTemplate(QuickSightClient qsClient, String ac } } } - // snippet-end:[quicksight.java2.describe_template.main] - - +// snippet-end:[quicksight.java2.describe_template.main] diff --git a/javav2/example_code/quicksight/src/main/java/com/example/quicksight/ListAnalyses.java b/javav2/example_code/quicksight/src/main/java/com/example/quicksight/ListAnalyses.java index eaebb1d3253..b19c20580df 100644 --- a/javav2/example_code/quicksight/src/main/java/com/example/quicksight/ListAnalyses.java +++ b/javav2/example_code/quicksight/src/main/java/com/example/quicksight/ListAnalyses.java @@ -1,12 +1,5 @@ -//snippet-sourcedescription:[ListAnalyses.java demonstrates how to list Amazon QuickSight analyses.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon QuickSight] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.quicksight; @@ -22,7 +15,8 @@ // snippet-end:[quicksight.java2.list_analyses.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,12 +26,12 @@ public class ListAnalyses { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - account - The ID of the AWS account. + Where: + account - The ID of the AWS account. - """; + """; if (args.length != 1) { System.out.println(usage); @@ -46,8 +40,8 @@ public static void main(String[] args) { String account = args[0]; QuickSightClient qsClient = QuickSightClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); listAllAnAnalyses(qsClient, account); qsClient.close(); @@ -56,9 +50,9 @@ public static void main(String[] args) { public static void listAllAnAnalyses(QuickSightClient qsClient, String account) { try { ListAnalysesRequest analysesRequest = ListAnalysesRequest.builder() - .awsAccountId(account) - .maxResults(20) - .build(); + .awsAccountId(account) + .maxResults(20) + .build(); ListAnalysesResponse res = qsClient.listAnalyses(analysesRequest); List analysisList = res.analysisSummaryList(); diff --git a/javav2/example_code/quicksight/src/main/java/com/example/quicksight/ListDashboards.java b/javav2/example_code/quicksight/src/main/java/com/example/quicksight/ListDashboards.java index 48535ba0a0f..242d9374a51 100644 --- a/javav2/example_code/quicksight/src/main/java/com/example/quicksight/ListDashboards.java +++ b/javav2/example_code/quicksight/src/main/java/com/example/quicksight/ListDashboards.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[ListDashboards.java demonstrates how to list Amazon QuickSight dashboards.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon QuickSight] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.quicksight; // snippet-start:[quicksight.java2.list_dashboards.main] @@ -20,7 +15,8 @@ // snippet-end:[quicksight.java2.list_dashboards.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,12 +26,12 @@ public class ListDashboards { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - account - The ID of the AWS account. + Where: + account - The ID of the AWS account. - """; + """; if (args.length != 1) { System.out.println(usage); @@ -44,8 +40,8 @@ public static void main(String[] args) { String account = args[0]; QuickSightClient qsClient = QuickSightClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); listAllDashboards(qsClient, account); qsClient.close(); @@ -54,9 +50,9 @@ public static void main(String[] args) { public static void listAllDashboards(QuickSightClient qsClient, String account) { try { ListDashboardsRequest dashboardsRequest = ListDashboardsRequest.builder() - .awsAccountId(account) - .maxResults(20) - .build(); + .awsAccountId(account) + .maxResults(20) + .build(); ListDashboardsResponse res = qsClient.listDashboards(dashboardsRequest); List dashboards = res.dashboardSummaryList(); diff --git a/javav2/example_code/quicksight/src/main/java/com/example/quicksight/ListDataSets.java b/javav2/example_code/quicksight/src/main/java/com/example/quicksight/ListDataSets.java index a96e4c9ccec..74b326ecad0 100644 --- a/javav2/example_code/quicksight/src/main/java/com/example/quicksight/ListDataSets.java +++ b/javav2/example_code/quicksight/src/main/java/com/example/quicksight/ListDataSets.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[ListDataSets.java demonstrates how to list Amazon QuickSight datasets.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon QuickSight] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.quicksight; // snippet-start:[quicksight.java2.list_datasets.main] @@ -20,7 +15,8 @@ // snippet-end:[quicksight.java2.list_datasets.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,12 +26,12 @@ public class ListDataSets { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - account - The ID of the AWS account. + Where: + account - The ID of the AWS account. - """; + """; if (args.length != 1) { System.out.println(usage); @@ -44,8 +40,8 @@ public static void main(String[] args) { String account = args[0]; QuickSightClient qsClient = QuickSightClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); listAllDataSets(qsClient, account); qsClient.close(); @@ -54,9 +50,9 @@ public static void main(String[] args) { public static void listAllDataSets(QuickSightClient qsClient, String account) { try { ListDataSetsRequest datasetRequest = ListDataSetsRequest.builder() - .awsAccountId(account) - .maxResults(20) - .build(); + .awsAccountId(account) + .maxResults(20) + .build(); ListDataSetsResponse res = qsClient.listDataSets(datasetRequest); List dataSets = res.dataSetSummaries(); @@ -72,4 +68,3 @@ public static void listAllDataSets(QuickSightClient qsClient, String account) { } } // snippet-end:[quicksight.java2.list_datasets.main] - diff --git a/javav2/example_code/quicksight/src/main/java/com/example/quicksight/ListTemplates.java b/javav2/example_code/quicksight/src/main/java/com/example/quicksight/ListTemplates.java index 2951c6d1121..aa89e6d887b 100644 --- a/javav2/example_code/quicksight/src/main/java/com/example/quicksight/ListTemplates.java +++ b/javav2/example_code/quicksight/src/main/java/com/example/quicksight/ListTemplates.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[ListTemplates.java demonstrates how to list Amazon QuickSight templates.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon QuickSight] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.quicksight; @@ -21,7 +15,8 @@ // snippet-end:[quicksight.java2.list_templates.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,12 +26,12 @@ public class ListTemplates { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - account - The ID of the AWS account. + Where: + account - The ID of the AWS account. - """; + """; if (args.length != 1) { System.out.println(usage); @@ -45,8 +40,8 @@ public static void main(String[] args) { String account = args[0]; QuickSightClient qsClient = QuickSightClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); listAllTemplates(qsClient, account); qsClient.close(); @@ -55,9 +50,9 @@ public static void main(String[] args) { public static void listAllTemplates(QuickSightClient qsClient, String account) { try { ListTemplatesRequest templateRequest = ListTemplatesRequest.builder() - .awsAccountId(account) - .maxResults(20) - .build(); + .awsAccountId(account) + .maxResults(20) + .build(); ListTemplatesResponse res = qsClient.listTemplates(templateRequest); List templateSummaries = res.templateSummaryList(); @@ -74,4 +69,3 @@ public static void listAllTemplates(QuickSightClient qsClient, String account) { } } // snippet-end:[quicksight.java2.list_templates.main] - diff --git a/javav2/example_code/quicksight/src/main/java/com/example/quicksight/ListThemes.java b/javav2/example_code/quicksight/src/main/java/com/example/quicksight/ListThemes.java index 605388decb9..d025eca7729 100644 --- a/javav2/example_code/quicksight/src/main/java/com/example/quicksight/ListThemes.java +++ b/javav2/example_code/quicksight/src/main/java/com/example/quicksight/ListThemes.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[ListThemes.java demonstrates how to list Amazon QuickSight themes.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon QuickSight] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.quicksight; // snippet-start:[quicksight.java2.list_themes.main] @@ -20,7 +15,8 @@ // snippet-end:[quicksight.java2.list_themes.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,12 +26,12 @@ public class ListThemes { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - account - The ID of the AWS account. + Where: + account - The ID of the AWS account. - """; + """; if (args.length != 1) { System.out.println(usage); @@ -44,8 +40,8 @@ public static void main(String[] args) { String account = args[0]; QuickSightClient qsClient = QuickSightClient.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); listAllThemes(qsClient, account); qsClient.close(); @@ -54,8 +50,8 @@ public static void main(String[] args) { public static void listAllThemes(QuickSightClient qsClient, String account) { try { ListThemesRequest themeRequest = ListThemesRequest.builder() - .awsAccountId(account) - .build(); + .awsAccountId(account) + .build(); ListThemesResponse analysisResponse = qsClient.listThemes(themeRequest); List themes = analysisResponse.themeSummaryList(); @@ -73,6 +69,3 @@ public static void listAllThemes(QuickSightClient qsClient, String account) { } } // snippet-end:[quicksight.java2.list_themes.main] - - - diff --git a/javav2/example_code/quicksight/src/main/java/com/example/quicksight/UpdateDashboard.java b/javav2/example_code/quicksight/src/main/java/com/example/quicksight/UpdateDashboard.java index f2a679d9922..f334e284dd4 100644 --- a/javav2/example_code/quicksight/src/main/java/com/example/quicksight/UpdateDashboard.java +++ b/javav2/example_code/quicksight/src/main/java/com/example/quicksight/UpdateDashboard.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[UpdateDashboard.java demonstrates how to update an Amazon QuickSight dashboard.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon QuickSight] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.quicksight; @@ -42,104 +36,106 @@ */ public class UpdateDashboard { - public static void main(String[] args) { - final String usage = """ - - Usage: - - Where: - account - The account to use. - dashboardId - The dashboard id value to use. - dataSetArn - The ARN of the dataset. - analysisArn - The ARN of an existing analysis - """; - - if (args.length != 4) { - System.out.println(usage); - System.exit(1); + public static void main(String[] args) { + final String usage = """ + + Usage: + + Where: + account - The account to use. + dashboardId - The dashboard id value to use. + dataSetArn - The ARN of the dataset. + analysisArn - The ARN of an existing analysis + """; + + if (args.length != 4) { + System.out.println(usage); + System.exit(1); + } + + String account = args[0]; + String dashboardId = args[1]; + String dataSetArn = args[2]; + String analysisArn = args[3]; + QuickSightClient qsClient = QuickSightClient.builder() + .region(Region.US_EAST_1) + .build(); + + updateSpecificDashboard(qsClient, account, dashboardId, dataSetArn, analysisArn); + qsClient.close(); } - String account = args[0]; - String dashboardId = args[1]; - String dataSetArn = args[2]; - String analysisArn = args[3]; - QuickSightClient qsClient = QuickSightClient.builder() - .region(Region.US_EAST_1) - .build(); - - updateSpecificDashboard(qsClient, account, dashboardId, dataSetArn, analysisArn); - qsClient.close(); - } - - public static void updateSpecificDashboard(QuickSightClient qsClient, String account, String dashboardId, String dataSetArn, String analysisArn) { - try { - DataSetReference dataSetReference = DataSetReference.builder() - .dataSetArn(dataSetArn) - .dataSetPlaceholder("Dataset placeholder2") - .build(); - - // Get a template ARN to use. - String arn = getTemplateARN(qsClient, account, dataSetArn, analysisArn); - DashboardSourceTemplate sourceTemplate = DashboardSourceTemplate.builder() - .dataSetReferences(dataSetReference) - .arn(arn) - .build(); - - DashboardSourceEntity sourceEntity = DashboardSourceEntity.builder() - .sourceTemplate(sourceTemplate) - .build(); - - UpdateDashboardRequest dashboardRequest = UpdateDashboardRequest.builder() - .awsAccountId(account) - .dashboardId(dashboardId) - .name("UpdateTest") - .sourceEntity(sourceEntity) - .themeArn("arn:aws:quicksight::aws:theme/MIDNIGHT") - .build(); - - UpdateDashboardResponse response = qsClient.updateDashboard(dashboardRequest); - System.out.println("Dashboard " + response.dashboardId() + " has been updated"); - - } catch (QuickSightException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + public static void updateSpecificDashboard(QuickSightClient qsClient, String account, String dashboardId, + String dataSetArn, String analysisArn) { + try { + DataSetReference dataSetReference = DataSetReference.builder() + .dataSetArn(dataSetArn) + .dataSetPlaceholder("Dataset placeholder2") + .build(); + + // Get a template ARN to use. + String arn = getTemplateARN(qsClient, account, dataSetArn, analysisArn); + DashboardSourceTemplate sourceTemplate = DashboardSourceTemplate.builder() + .dataSetReferences(dataSetReference) + .arn(arn) + .build(); + + DashboardSourceEntity sourceEntity = DashboardSourceEntity.builder() + .sourceTemplate(sourceTemplate) + .build(); + + UpdateDashboardRequest dashboardRequest = UpdateDashboardRequest.builder() + .awsAccountId(account) + .dashboardId(dashboardId) + .name("UpdateTest") + .sourceEntity(sourceEntity) + .themeArn("arn:aws:quicksight::aws:theme/MIDNIGHT") + .build(); + + UpdateDashboardResponse response = qsClient.updateDashboard(dashboardRequest); + System.out.println("Dashboard " + response.dashboardId() + " has been updated"); + + } catch (QuickSightException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } } - } - - private static String getTemplateARN(QuickSightClient qsClient, String account, String dataset, String analysisArn) { - String arn = null; - try { - DataSetReference setReference = DataSetReference.builder() - .dataSetArn(dataset) - .dataSetPlaceholder("Dataset placeholder2") - .build(); - - TemplateSourceAnalysis templateSourceAnalysis = TemplateSourceAnalysis.builder() - .dataSetReferences(setReference) - .arn(analysisArn) - .build(); - - TemplateSourceEntity sourceEntity = TemplateSourceEntity.builder() - .sourceAnalysis(templateSourceAnalysis) - .build(); - - UUID uuid = UUID.randomUUID(); - String templateGUID = uuid.toString(); - CreateTemplateRequest createTemplateRequest = CreateTemplateRequest.builder() - .awsAccountId(account) - .name("NewTemplate") - .sourceEntity(sourceEntity) - .templateId(templateGUID) // Specify a GUID value - .build(); - - CreateTemplateResponse response = qsClient.createTemplate(createTemplateRequest); - arn = response.arn(); - - } catch (QuickSightException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + + private static String getTemplateARN(QuickSightClient qsClient, String account, String dataset, + String analysisArn) { + String arn = null; + try { + DataSetReference setReference = DataSetReference.builder() + .dataSetArn(dataset) + .dataSetPlaceholder("Dataset placeholder2") + .build(); + + TemplateSourceAnalysis templateSourceAnalysis = TemplateSourceAnalysis.builder() + .dataSetReferences(setReference) + .arn(analysisArn) + .build(); + + TemplateSourceEntity sourceEntity = TemplateSourceEntity.builder() + .sourceAnalysis(templateSourceAnalysis) + .build(); + + UUID uuid = UUID.randomUUID(); + String templateGUID = uuid.toString(); + CreateTemplateRequest createTemplateRequest = CreateTemplateRequest.builder() + .awsAccountId(account) + .name("NewTemplate") + .sourceEntity(sourceEntity) + .templateId(templateGUID) // Specify a GUID value + .build(); + + CreateTemplateResponse response = qsClient.createTemplate(createTemplateRequest); + arn = response.arn(); + + } catch (QuickSightException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + return arn; } - return arn; - } } // snippet-end:[quicksight.java2.update_dashboard.main] \ No newline at end of file diff --git a/javav2/example_code/quicksight/src/test/java/QuickSightTest.java b/javav2/example_code/quicksight/src/test/java/QuickSightTest.java index 40683dda0b9..7b3cb0179f8 100644 --- a/javav2/example_code/quicksight/src/test/java/QuickSightTest.java +++ b/javav2/example_code/quicksight/src/test/java/QuickSightTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.google.gson.Gson; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; @@ -32,9 +30,9 @@ public class QuickSightTest { @BeforeAll public static void setUp() { qsClient = QuickSightClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -47,34 +45,37 @@ public static void setUp() { dataSetArn = values.getDataSetArn(); analysisArn = values.getAnalysisArn(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - - try (InputStream input = QuickSightTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - prop.load(input); - account = prop.getProperty("account"); - analysisId = prop.getProperty("analysisId"); - dashboardId = prop.getProperty("dashboardId"); - templateId = prop.getProperty("templateId"); - dataSetArn = prop.getProperty("dataSetArn"); - analysisArn = prop.getProperty("analysisArn"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * + * try (InputStream input = + * QuickSightTest.class.getClassLoader().getResourceAsStream("config.properties" + * )) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * prop.load(input); + * account = prop.getProperty("account"); + * analysisId = prop.getProperty("analysisId"); + * dashboardId = prop.getProperty("dashboardId"); + * templateId = prop.getProperty("templateId"); + * dataSetArn = prop.getProperty("dataSetArn"); + * analysisArn = prop.getProperty("analysisArn"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @Tag("IntegrationTest") @Order(1) public void DescribeAnalysis() { - assertDoesNotThrow(() ->DescribeAnalysis.describeSpecificAnalysis(qsClient, account, analysisId)); + assertDoesNotThrow(() -> DescribeAnalysis.describeSpecificAnalysis(qsClient, account, analysisId)); System.out.println("DescribeAnalysis test passed"); } @@ -82,7 +83,7 @@ public void DescribeAnalysis() { @Tag("IntegrationTest") @Order(2) public void DescribeDashboard() { - assertDoesNotThrow(() ->DescribeDashboard.describeSpecificDashboard(qsClient, account, dashboardId)); + assertDoesNotThrow(() -> DescribeDashboard.describeSpecificDashboard(qsClient, account, dashboardId)); System.out.println("DescribeDashboard test passed"); } @@ -90,7 +91,7 @@ public void DescribeDashboard() { @Tag("IntegrationTest") @Order(3) public void DescribeTemplate() { - assertDoesNotThrow(() ->DescribeTemplate.describeSpecificTemplate(qsClient, account, templateId)); + assertDoesNotThrow(() -> DescribeTemplate.describeSpecificTemplate(qsClient, account, templateId)); System.out.println("DescribeTemplate test passed"); } @@ -98,7 +99,7 @@ public void DescribeTemplate() { @Tag("IntegrationTest") @Order(4) public void ListThemes() { - assertDoesNotThrow(() ->ListThemes.listAllThemes(qsClient, account)); + assertDoesNotThrow(() -> ListThemes.listAllThemes(qsClient, account)); System.out.println("ListThemes test passed"); } @@ -106,7 +107,7 @@ public void ListThemes() { @Tag("IntegrationTest") @Order(6) public void ListAnalyses() { - assertDoesNotThrow(() ->ListAnalyses.listAllAnAnalyses(qsClient, account)); + assertDoesNotThrow(() -> ListAnalyses.listAllAnAnalyses(qsClient, account)); System.out.println("ListAnalyses test passed"); } @@ -114,7 +115,7 @@ public void ListAnalyses() { @Tag("IntegrationTest") @Order(7) public void ListDashboards() { - assertDoesNotThrow(() ->ListDashboards.listAllDashboards(qsClient, account)); + assertDoesNotThrow(() -> ListDashboards.listAllDashboards(qsClient, account)); System.out.println("ListDashboards test passed"); } @@ -122,7 +123,7 @@ public void ListDashboards() { @Tag("IntegrationTest") @Order(8) public void ListTemplates() { - assertDoesNotThrow(() ->ListTemplates.listAllTemplates(qsClient, account)); + assertDoesNotThrow(() -> ListTemplates.listAllTemplates(qsClient, account)); System.out.println("ListTemplates test passed"); } @@ -130,19 +131,21 @@ public void ListTemplates() { @Tag("IntegrationTest") @Order(9) public void UpdateDashboard() { - assertDoesNotThrow(() ->UpdateDashboard.updateSpecificDashboard(qsClient, account, dashboardId, dataSetArn, analysisArn)); + assertDoesNotThrow( + () -> UpdateDashboard.updateSpecificDashboard(qsClient, account, dashboardId, dataSetArn, analysisArn)); System.out.println("UpdateDashboard test passed"); } + private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/quicksight"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -186,4 +189,3 @@ public String getAnalysisArn() { } } } - diff --git a/javav2/example_code/rds/src/main/java/com/example/rds/AuroraScenario.java b/javav2/example_code/rds/src/main/java/com/example/rds/AuroraScenario.java index c5be8654ef4..5be98ee2e96 100644 --- a/javav2/example_code/rds/src/main/java/com/example/rds/AuroraScenario.java +++ b/javav2/example_code/rds/src/main/java/com/example/rds/AuroraScenario.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[AuroraScenario.java demonstrates how to perform multiple operations on Aurora Clusters by using an Amazon Relational Database Service (RDS) service client.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Relational Database Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rds; @@ -56,28 +50,37 @@ // snippet-start:[rds.java2.scenario.aurora.main] /** - * Before running this Java (v2) code example, set up your development environment, including your credentials. + * Before running this Java (v2) code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * This example requires an AWS Secrets Manager secret that contains the database credentials. If you do not create a + * This example requires an AWS Secrets Manager secret that contains the + * database credentials. If you do not create a * secret, this example will not work. For details, see: * * https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_how-services-use-secrets_RS.html * * This Java example performs the following tasks: * - * 1. Gets available engine families for Amazon Aurora MySQL-Compatible Edition by calling the DescribeDbEngineVersions(Engine='aurora-mysql') method. - * 2. Selects an engine family and creates a custom DB cluster parameter group by invoking the describeDBClusterParameters method. - * 3. Gets the parameter groups by invoking the describeDBClusterParameterGroups method. - * 4. Gets parameters in the group by invoking the describeDBClusterParameters method. - * 5. Modifies the auto_increment_offset parameter by invoking the modifyDbClusterParameterGroupRequest method. + * 1. Gets available engine families for Amazon Aurora MySQL-Compatible Edition + * by calling the DescribeDbEngineVersions(Engine='aurora-mysql') method. + * 2. Selects an engine family and creates a custom DB cluster parameter group + * by invoking the describeDBClusterParameters method. + * 3. Gets the parameter groups by invoking the describeDBClusterParameterGroups + * method. + * 4. Gets parameters in the group by invoking the describeDBClusterParameters + * method. + * 5. Modifies the auto_increment_offset parameter by invoking the + * modifyDbClusterParameterGroupRequest method. * 6. Gets and displays the updated parameters. - * 7. Gets a list of allowed engine versions by invoking the describeDbEngineVersions method. - * 8. Creates an Aurora DB cluster database cluster that contains a MySQL database. - * 9. Waits for DB instance to be ready. + * 7. Gets a list of allowed engine versions by invoking the + * describeDbEngineVersions method. + * 8. Creates an Aurora DB cluster database cluster that contains a MySQL + * database. + * 9. Waits for DB instance to be ready. * 10. Gets a list of instance classes available for the selected engine. * 11. Creates a database instance in the cluster. * 12. Waits for DB instance to be ready. @@ -89,20 +92,24 @@ public class AuroraScenario { public static long sleepTime = 20; public static final String DASHES = new String(new char[80]).replace("\0", "-"); + public static void main(String[] args) throws InterruptedException { final String usage = "\n" + - "Usage:\n" + - " " + - "Where:\n" + - " dbClusterGroupName - The name of the DB cluster parameter group. \n"+ - " dbParameterGroupFamily - The DB cluster parameter group family name (for example, aurora-mysql5.7). \n"+ - " dbInstanceClusterIdentifier - The instance cluster identifier value.\n"+ - " dbInstanceIdentifier - The database instance identifier.\n"+ - " dbName - The database name.\n"+ - " dbSnapshotIdentifier - The snapshot identifier.\n"+ - " secretName - The name of the AWS Secrets Manager secret that contains the database credentials\"\n" ;; - - if (args.length != 7) { + "Usage:\n" + + " " + + + "Where:\n" + + " dbClusterGroupName - The name of the DB cluster parameter group. \n" + + " dbParameterGroupFamily - The DB cluster parameter group family name (for example, aurora-mysql5.7). \n" + + + " dbInstanceClusterIdentifier - The instance cluster identifier value.\n" + + " dbInstanceIdentifier - The database instance identifier.\n" + + " dbName - The database name.\n" + + " dbSnapshotIdentifier - The snapshot identifier.\n" + + " secretName - The name of the AWS Secrets Manager secret that contains the database credentials\"\n"; + ; + + if (args.length != 7) { System.out.println(usage); System.exit(1); } @@ -123,8 +130,8 @@ public static void main(String[] args) throws InterruptedException { Region region = Region.US_WEST_2; RdsClient rdsClient = RdsClient.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.println(DASHES); System.out.println("Welcome to the Amazon Aurora example scenario."); @@ -167,12 +174,13 @@ public static void main(String[] args) throws InterruptedException { System.out.println(DASHES); System.out.println("8. Create an Aurora DB cluster database"); - String arnClusterVal = createDBCluster(rdsClient, dbClusterGroupName, dbName, dbInstanceClusterIdentifier, username, userPassword) ; - System.out.println("The ARN of the cluster is "+arnClusterVal); + String arnClusterVal = createDBCluster(rdsClient, dbClusterGroupName, dbName, dbInstanceClusterIdentifier, + username, userPassword); + System.out.println("The ARN of the cluster is " + arnClusterVal); System.out.println(DASHES); System.out.println(DASHES); - System.out.println("9. Wait for DB instance to be ready" ); + System.out.println("9. Wait for DB instance to be ready"); waitForInstanceReady(rdsClient, dbInstanceClusterIdentifier); System.out.println(DASHES); @@ -183,12 +191,13 @@ public static void main(String[] args) throws InterruptedException { System.out.println(DASHES); System.out.println("11. Create a database instance in the cluster."); - String clusterDBARN = createDBInstanceCluster(rdsClient, dbInstanceIdentifier, dbInstanceClusterIdentifier, instanceClass); - System.out.println("The ARN of the database is "+clusterDBARN); + String clusterDBARN = createDBInstanceCluster(rdsClient, dbInstanceIdentifier, dbInstanceClusterIdentifier, + instanceClass); + System.out.println("The ARN of the database is " + clusterDBARN); System.out.println(DASHES); System.out.println(DASHES); - System.out.println("12. Wait for DB instance to be ready" ); + System.out.println("12. Wait for DB instance to be ready"); waitDBInstanceReady(rdsClient, dbInstanceIdentifier); System.out.println(DASHES); @@ -198,12 +207,12 @@ public static void main(String[] args) throws InterruptedException { System.out.println(DASHES); System.out.println(DASHES); - System.out.println("14. Wait for DB snapshot to be ready" ); + System.out.println("14. Wait for DB snapshot to be ready"); waitForSnapshotReady(rdsClient, dbSnapshotIdentifier, dbInstanceClusterIdentifier); System.out.println(DASHES); System.out.println(DASHES); - System.out.println("14. Delete the DB instance" ); + System.out.println("14. Delete the DB instance"); deleteDatabaseInstance(rdsClient, dbInstanceIdentifier); System.out.println(DASHES); @@ -218,7 +227,7 @@ public static void main(String[] args) throws InterruptedException { System.out.println(DASHES); System.out.println(DASHES); - System.out.println("The Scenario has successfully completed." ); + System.out.println("The Scenario has successfully completed."); System.out.println(DASHES); rdsClient.close(); } @@ -226,27 +235,28 @@ public static void main(String[] args) throws InterruptedException { private static SecretsManagerClient getSecretClient() { Region region = Region.US_WEST_2; return SecretsManagerClient.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); } private static String getSecretValues(String secretName) { SecretsManagerClient secretClient = getSecretClient(); GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); } // snippet-start:[rds.java2.scenario.cluster.del_paragroup.main] - public static void deleteDBClusterGroup( RdsClient rdsClient, String dbClusterGroupName, String clusterDBARN) throws InterruptedException { + public static void deleteDBClusterGroup(RdsClient rdsClient, String dbClusterGroupName, String clusterDBARN) + throws InterruptedException { try { boolean isDataDel = false; boolean didFind; - String instanceARN ; + String instanceARN; // Make sure that the database has been deleted. while (!isDataDel) { @@ -255,27 +265,28 @@ public static void deleteDBClusterGroup( RdsClient rdsClient, String dbClusterGr int listSize = instanceList.size(); didFind = false; int index = 1; - for (DBInstance instance: instanceList) { + for (DBInstance instance : instanceList) { instanceARN = instance.dbInstanceArn(); if (instanceARN.compareTo(clusterDBARN) == 0) { System.out.println(clusterDBARN + " still exists"); - didFind = true ; + didFind = true; } if ((index == listSize) && (!didFind)) { // Went through the entire list and did not find the database ARN. isDataDel = true; } Thread.sleep(sleepTime * 1000); - index ++; + index++; } } - DeleteDbClusterParameterGroupRequest clusterParameterGroupRequest = DeleteDbClusterParameterGroupRequest.builder() - .dbClusterParameterGroupName(dbClusterGroupName) - .build(); + DeleteDbClusterParameterGroupRequest clusterParameterGroupRequest = DeleteDbClusterParameterGroupRequest + .builder() + .dbClusterParameterGroupName(dbClusterGroupName) + .build(); rdsClient.deleteDBClusterParameterGroup(clusterParameterGroupRequest); - System.out.println(dbClusterGroupName +" was deleted."); + System.out.println(dbClusterGroupName + " was deleted."); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); @@ -288,12 +299,12 @@ public static void deleteDBClusterGroup( RdsClient rdsClient, String dbClusterGr public static void deleteCluster(RdsClient rdsClient, String dbInstanceClusterIdentifier) { try { DeleteDbClusterRequest deleteDbClusterRequest = DeleteDbClusterRequest.builder() - .dbClusterIdentifier(dbInstanceClusterIdentifier) - .skipFinalSnapshot(true) - .build(); + .dbClusterIdentifier(dbInstanceClusterIdentifier) + .skipFinalSnapshot(true) + .build(); rdsClient.deleteDBCluster(deleteDbClusterRequest); - System.out.println(dbInstanceClusterIdentifier +" was deleted!"); + System.out.println(dbInstanceClusterIdentifier + " was deleted!"); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); @@ -303,13 +314,13 @@ public static void deleteCluster(RdsClient rdsClient, String dbInstanceClusterId // snippet-end:[rds.java2.scenario.cluster.del.main] // snippet-start:[rds.java2.scenario.cluster.del.instance.main] - public static void deleteDatabaseInstance( RdsClient rdsClient, String dbInstanceIdentifier) { + public static void deleteDatabaseInstance(RdsClient rdsClient, String dbInstanceIdentifier) { try { DeleteDbInstanceRequest deleteDbInstanceRequest = DeleteDbInstanceRequest.builder() - .dbInstanceIdentifier(dbInstanceIdentifier) - .deleteAutomatedBackups(true) - .skipFinalSnapshot(true) - .build(); + .dbInstanceIdentifier(dbInstanceIdentifier) + .deleteAutomatedBackups(true) + .skipFinalSnapshot(true) + .build(); DeleteDbInstanceResponse response = rdsClient.deleteDBInstance(deleteDbInstanceRequest); System.out.println("The status of the database is " + response.dbInstance().dbInstanceStatus()); @@ -322,19 +333,20 @@ public static void deleteDatabaseInstance( RdsClient rdsClient, String dbInstanc // snippet-end:[rds.java2.scenario.cluster.del.instance.main] // snippet-start:[rds.java2.scenario.cluster.wait.snapshot.main] - public static void waitForSnapshotReady(RdsClient rdsClient, String dbSnapshotIdentifier, String dbInstanceClusterIdentifier) { + public static void waitForSnapshotReady(RdsClient rdsClient, String dbSnapshotIdentifier, + String dbInstanceClusterIdentifier) { try { boolean snapshotReady = false; String snapshotReadyStr; System.out.println("Waiting for the snapshot to become available."); DescribeDbClusterSnapshotsRequest snapshotsRequest = DescribeDbClusterSnapshotsRequest.builder() - .dbClusterSnapshotIdentifier(dbSnapshotIdentifier) - .dbClusterIdentifier(dbInstanceClusterIdentifier) - .build(); + .dbClusterSnapshotIdentifier(dbSnapshotIdentifier) + .dbClusterIdentifier(dbInstanceClusterIdentifier) + .build(); while (!snapshotReady) { - DescribeDbClusterSnapshotsResponse response = rdsClient.describeDBClusterSnapshots (snapshotsRequest); + DescribeDbClusterSnapshotsResponse response = rdsClient.describeDBClusterSnapshots(snapshotsRequest); List snapshotList = response.dbClusterSnapshots(); for (DBClusterSnapshot snapshot : snapshotList) { snapshotReadyStr = snapshot.status(); @@ -354,15 +366,16 @@ public static void waitForSnapshotReady(RdsClient rdsClient, String dbSnapshotId System.exit(1); } } - // snippet-end:[rds.java2.scenario.cluster.wait.snapshot.main] + // snippet-end:[rds.java2.scenario.cluster.wait.snapshot.main] // snippet-start:[rds.java2.scenario.cluster.create.snapshot.main] - public static void createDBClusterSnapshot(RdsClient rdsClient, String dbInstanceClusterIdentifier, String dbSnapshotIdentifier) { + public static void createDBClusterSnapshot(RdsClient rdsClient, String dbInstanceClusterIdentifier, + String dbSnapshotIdentifier) { try { CreateDbClusterSnapshotRequest snapshotRequest = CreateDbClusterSnapshotRequest.builder() - .dbClusterIdentifier(dbInstanceClusterIdentifier) - .dbClusterSnapshotIdentifier(dbSnapshotIdentifier) - .build(); + .dbClusterIdentifier(dbInstanceClusterIdentifier) + .dbClusterSnapshotIdentifier(dbSnapshotIdentifier) + .build(); CreateDbClusterSnapshotResponse response = rdsClient.createDBClusterSnapshot(snapshotRequest); System.out.println("The Snapshot ARN is " + response.dbClusterSnapshot().dbClusterSnapshotArn()); @@ -381,10 +394,10 @@ public static void waitDBInstanceReady(RdsClient rdsClient, String dbInstanceIde System.out.println("Waiting for instance to become available."); try { DescribeDbInstancesRequest instanceRequest = DescribeDbInstancesRequest.builder() - .dbInstanceIdentifier(dbInstanceIdentifier) - .build(); + .dbInstanceIdentifier(dbInstanceIdentifier) + .build(); - String endpoint=""; + String endpoint = ""; while (!instanceReady) { DescribeDbInstancesResponse response = rdsClient.describeDBInstances(instanceRequest); List instanceList = response.dbInstances(); @@ -399,7 +412,7 @@ public static void waitDBInstanceReady(RdsClient rdsClient, String dbInstanceIde } } } - System.out.println("Database instance is available! The connection endpoint is "+ endpoint); + System.out.println("Database instance is available! The connection endpoint is " + endpoint); } catch (RdsException | InterruptedException e) { System.err.println(e.getMessage()); @@ -410,16 +423,16 @@ public static void waitDBInstanceReady(RdsClient rdsClient, String dbInstanceIde // snippet-start:[rds.java2.scenario.cluster.create.instance.main] public static String createDBInstanceCluster(RdsClient rdsClient, - String dbInstanceIdentifier, - String dbInstanceClusterIdentifier, - String instanceClass){ + String dbInstanceIdentifier, + String dbInstanceClusterIdentifier, + String instanceClass) { try { CreateDbInstanceRequest instanceRequest = CreateDbInstanceRequest.builder() - .dbInstanceIdentifier(dbInstanceIdentifier) - .dbClusterIdentifier(dbInstanceClusterIdentifier) - .engine("aurora-mysql") - .dbInstanceClass(instanceClass) - .build() ; + .dbInstanceIdentifier(dbInstanceIdentifier) + .dbClusterIdentifier(dbInstanceClusterIdentifier) + .engine("aurora-mysql") + .dbInstanceClass(instanceClass) + .build(); CreateDbInstanceResponse response = rdsClient.createDBInstance(instanceRequest); System.out.print("The status is " + response.dbInstance().dbInstanceStatus()); @@ -435,19 +448,21 @@ public static String createDBInstanceCluster(RdsClient rdsClient, // snippet-start:[rds.java2.scenario.cluster.list.instances.main] public static String getListInstanceClasses(RdsClient rdsClient) { - try{ - DescribeOrderableDbInstanceOptionsRequest optionsRequest = DescribeOrderableDbInstanceOptionsRequest.builder() - .engine("aurora-mysql") - .maxRecords(20) - .build(); + try { + DescribeOrderableDbInstanceOptionsRequest optionsRequest = DescribeOrderableDbInstanceOptionsRequest + .builder() + .engine("aurora-mysql") + .maxRecords(20) + .build(); - DescribeOrderableDbInstanceOptionsResponse response = rdsClient.describeOrderableDBInstanceOptions(optionsRequest); + DescribeOrderableDbInstanceOptionsResponse response = rdsClient + .describeOrderableDBInstanceOptions(optionsRequest); List instanceOptions = response.orderableDBInstanceOptions(); String instanceClass = ""; - for (OrderableDBInstanceOption instanceOption: instanceOptions) { + for (OrderableDBInstanceOption instanceOption : instanceOptions) { instanceClass = instanceOption.dbInstanceClass(); - System.out.println("The instance class is " +instanceOption.dbInstanceClass()); - System.out.println("The engine version is " +instanceOption.engineVersion()); + System.out.println("The instance class is " + instanceOption.dbInstanceClass()); + System.out.println("The engine version is " + instanceOption.engineVersion()); } return instanceClass; @@ -467,8 +482,8 @@ public static void waitForInstanceReady(RdsClient rdsClient, String dbClusterIde System.out.println("Waiting for instance to become available."); try { DescribeDbClustersRequest instanceRequest = DescribeDbClustersRequest.builder() - .dbClusterIdentifier(dbClusterIdentifier) - .build(); + .dbClusterIdentifier(dbClusterIdentifier) + .build(); while (!instanceReady) { DescribeDbClustersResponse response = rdsClient.describeDBClusters(instanceRequest); @@ -493,16 +508,17 @@ public static void waitForInstanceReady(RdsClient rdsClient, String dbClusterIde // snippet-end:[rds.java2.scenario.cluster.wait.instances.main] // snippet-start:[rds.java2.scenario.cluster.create.main] - public static String createDBCluster(RdsClient rdsClient, String dbParameterGroupFamily, String dbName, String dbClusterIdentifier, String userName, String password) { + public static String createDBCluster(RdsClient rdsClient, String dbParameterGroupFamily, String dbName, + String dbClusterIdentifier, String userName, String password) { try { CreateDbClusterRequest clusterRequest = CreateDbClusterRequest.builder() - .databaseName(dbName) - .dbClusterIdentifier(dbClusterIdentifier) - .dbClusterParameterGroupName(dbParameterGroupFamily) - .engine("aurora-mysql") - .masterUsername(userName) - .masterUserPassword(password) - .build(); + .databaseName(dbName) + .dbClusterIdentifier(dbClusterIdentifier) + .dbClusterParameterGroupName(dbParameterGroupFamily) + .engine("aurora-mysql") + .masterUsername(userName) + .masterUserPassword(password) + .build(); CreateDbClusterResponse response = rdsClient.createDBCluster(clusterRequest); return response.dbCluster().dbClusterArn(); @@ -515,21 +531,20 @@ public static String createDBCluster(RdsClient rdsClient, String dbParameterGrou } // snippet-end:[rds.java2.scenario.cluster.create.main] - // snippet-start:[rds.java2.scenario.cluster.getengs.main] // Get a list of allowed engine versions. public static void getAllowedEngines(RdsClient rdsClient, String dbParameterGroupFamily) { try { DescribeDbEngineVersionsRequest versionsRequest = DescribeDbEngineVersionsRequest.builder() - .dbParameterGroupFamily(dbParameterGroupFamily) - .engine("aurora-mysql") - .build(); + .dbParameterGroupFamily(dbParameterGroupFamily) + .engine("aurora-mysql") + .build(); DescribeDbEngineVersionsResponse response = rdsClient.describeDBEngineVersions(versionsRequest); List dbEngines = response.dbEngineVersions(); - for (DBEngineVersion dbEngine: dbEngines) { - System.out.println("The engine version is " +dbEngine.engineVersion()); - System.out.println("The engine description is " +dbEngine.dbEngineDescription()); + for (DBEngineVersion dbEngine : dbEngines) { + System.out.println("The engine version is " + dbEngine.engineVersion()); + System.out.println("The engine description is " + dbEngine.dbEngineDescription()); } } catch (RdsException e) { @@ -544,20 +559,21 @@ public static void getAllowedEngines(RdsClient rdsClient, String dbParameterGrou public static void modifyDBClusterParas(RdsClient rdsClient, String dClusterGroupName) { try { Parameter parameter1 = Parameter.builder() - .parameterName("auto_increment_offset") - .applyMethod("immediate") - .parameterValue("5") - .build(); + .parameterName("auto_increment_offset") + .applyMethod("immediate") + .parameterValue("5") + .build(); List paraList = new ArrayList<>(); paraList.add(parameter1); ModifyDbClusterParameterGroupRequest groupRequest = ModifyDbClusterParameterGroupRequest.builder() - .dbClusterParameterGroupName(dClusterGroupName) - .parameters(paraList) - .build(); + .dbClusterParameterGroupName(dClusterGroupName) + .parameters(paraList) + .build(); ModifyDbClusterParameterGroupResponse response = rdsClient.modifyDBClusterParameterGroup(groupRequest); - System.out.println("The parameter group "+ response.dbClusterParameterGroupName() +" was successfully modified"); + System.out.println( + "The parameter group " + response.dbClusterParameterGroupName() + " was successfully modified"); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); @@ -572,22 +588,25 @@ public static void describeDbClusterParameters(RdsClient rdsClient, String dbCLu DescribeDbClusterParametersRequest dbParameterGroupsRequest; if (flag == 0) { dbParameterGroupsRequest = DescribeDbClusterParametersRequest.builder() - .dbClusterParameterGroupName(dbCLusterGroupName) - .build(); + .dbClusterParameterGroupName(dbCLusterGroupName) + .build(); } else { dbParameterGroupsRequest = DescribeDbClusterParametersRequest.builder() - .dbClusterParameterGroupName(dbCLusterGroupName) - .source("user") - .build(); + .dbClusterParameterGroupName(dbCLusterGroupName) + .source("user") + .build(); } - DescribeDbClusterParametersResponse response = rdsClient.describeDBClusterParameters(dbParameterGroupsRequest); + DescribeDbClusterParametersResponse response = rdsClient + .describeDBClusterParameters(dbParameterGroupsRequest); List dbParameters = response.parameters(); String paraName; - for (Parameter para: dbParameters) { - // Only print out information about either auto_increment_offset or auto_increment_increment. + for (Parameter para : dbParameters) { + // Only print out information about either auto_increment_offset or + // auto_increment_increment. paraName = para.parameterName(); - if ( (paraName.compareTo("auto_increment_offset") ==0) || (paraName.compareTo("auto_increment_increment ") ==0)) { + if ((paraName.compareTo("auto_increment_offset") == 0) + || (paraName.compareTo("auto_increment_increment ") == 0)) { System.out.println("*** The parameter name is " + paraName); System.out.println("*** The parameter value is " + para.parameterValue()); System.out.println("*** The parameter data type is " + para.dataType()); @@ -607,14 +626,15 @@ public static void describeDbClusterParameters(RdsClient rdsClient, String dbCLu public static void describeDbClusterParameterGroups(RdsClient rdsClient, String dbClusterGroupName) { try { DescribeDbClusterParameterGroupsRequest groupsRequest = DescribeDbClusterParameterGroupsRequest.builder() - .dbClusterParameterGroupName(dbClusterGroupName) - .maxRecords(20) - .build(); + .dbClusterParameterGroupName(dbClusterGroupName) + .maxRecords(20) + .build(); - List groups = rdsClient.describeDBClusterParameterGroups(groupsRequest).dbClusterParameterGroups(); - for (DBClusterParameterGroup group: groups) { - System.out.println("The group name is "+group.dbClusterParameterGroupName()); - System.out.println("The group ARN is "+group.dbClusterParameterGroupArn()); + List groups = rdsClient.describeDBClusterParameterGroups(groupsRequest) + .dbClusterParameterGroups(); + for (DBClusterParameterGroup group : groups) { + System.out.println("The group name is " + group.dbClusterParameterGroupName()); + System.out.println("The group ARN is " + group.dbClusterParameterGroupArn()); } } catch (RdsException e) { @@ -625,16 +645,17 @@ public static void describeDbClusterParameterGroups(RdsClient rdsClient, String // snippet-end:[rds.java2.scenario.cluster.des.param.groups.main] // snippet-start:[rds.java2.scenario.cluster.create.param.group.main] - public static void createDBClusterParameterGroup(RdsClient rdsClient, String dbClusterGroupName, String dbParameterGroupFamily) { + public static void createDBClusterParameterGroup(RdsClient rdsClient, String dbClusterGroupName, + String dbParameterGroupFamily) { try { CreateDbClusterParameterGroupRequest groupRequest = CreateDbClusterParameterGroupRequest.builder() - .dbClusterParameterGroupName(dbClusterGroupName) - .dbParameterGroupFamily(dbParameterGroupFamily) - .description("Created by using the AWS SDK for Java") - .build(); + .dbClusterParameterGroupName(dbClusterGroupName) + .dbParameterGroupFamily(dbParameterGroupFamily) + .description("Created by using the AWS SDK for Java") + .build(); CreateDbClusterParameterGroupResponse response = rdsClient.createDBClusterParameterGroup(groupRequest); - System.out.println("The group name is "+ response.dbClusterParameterGroup().dbClusterParameterGroupName()); + System.out.println("The group name is " + response.dbClusterParameterGroup().dbClusterParameterGroupName()); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); @@ -644,22 +665,23 @@ public static void createDBClusterParameterGroup(RdsClient rdsClient, String dbC // snippet-end:[rds.java2.scenario.cluster.create.param.group.main] // snippet-start:[rds.java2.scenario.cluster.describe.engines.main] - public static void describeDBEngines( RdsClient rdsClient) { + public static void describeDBEngines(RdsClient rdsClient) { try { DescribeDbEngineVersionsRequest engineVersionsRequest = DescribeDbEngineVersionsRequest.builder() - .engine("aurora-mysql") - .defaultOnly(true) - .maxRecords(20) - .build(); + .engine("aurora-mysql") + .defaultOnly(true) + .maxRecords(20) + .build(); DescribeDbEngineVersionsResponse response = rdsClient.describeDBEngineVersions(engineVersionsRequest); List engines = response.dbEngineVersions(); // Get all DBEngineVersion objects. - for (DBEngineVersion engineOb: engines) { - System.out.println("The name of the DB parameter group family for the database engine is "+engineOb.dbParameterGroupFamily()); - System.out.println("The name of the database engine "+engineOb.engine()); - System.out.println("The version number of the database engine "+engineOb.engineVersion()); + for (DBEngineVersion engineOb : engines) { + System.out.println("The name of the DB parameter group family for the database engine is " + + engineOb.dbParameterGroupFamily()); + System.out.println("The name of the database engine " + engineOb.engine()); + System.out.println("The version number of the database engine " + engineOb.engineVersion()); } } catch (RdsException e) { diff --git a/javav2/example_code/rds/src/main/java/com/example/rds/CreateDBInstance.java b/javav2/example_code/rds/src/main/java/com/example/rds/CreateDBInstance.java index bc10d08e5a7..0862c431d77 100644 --- a/javav2/example_code/rds/src/main/java/com/example/rds/CreateDBInstance.java +++ b/javav2/example_code/rds/src/main/java/com/example/rds/CreateDBInstance.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[CreateDBInstance.java demonstrates how to create an Amazon Relational Database Service (RDS) instance and wait for it to be in an available state.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Relational Database Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rds; @@ -29,33 +23,36 @@ // snippet-end:[rds.java2.create_instance.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * This example requires an AWS Secrets Manager secret that contains the database credentials. If you do not create a - * secret, this example will not work. For more details, see: + * This example requires an AWS Secrets Manager secret that contains the + * database credentials. If you do not create a + * secret, this example will not work. For more details, see: * - * https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_how-services-use-secrets_RS.html + * https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_how-services-use-secrets_RS.html * * */ public class CreateDBInstance { public static long sleepTime = 20; + public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - dbInstanceIdentifier - The database instance identifier.\s - dbName - The database name.\s - secretName - The name of the AWS Secrets Manager secret that contains the database credentials." - """; + Where: + dbInstanceIdentifier - The database instance identifier.\s + dbName - The database name.\s + secretName - The name of the AWS Secrets Manager secret that contains the database credentials." + """; if (args.length != 3) { System.out.println(usage); @@ -69,57 +66,57 @@ public static void main(String[] args) { User user = gson.fromJson(String.valueOf(getSecretValues(secretName)), User.class); Region region = Region.US_WEST_2; RdsClient rdsClient = RdsClient.builder() - .region(region) - .build(); + .region(region) + .build(); - createDatabaseInstance(rdsClient, dbInstanceIdentifier, dbName, user.getUsername(), user.getPassword()) ; - waitForInstanceReady(rdsClient, dbInstanceIdentifier) ; + createDatabaseInstance(rdsClient, dbInstanceIdentifier, dbName, user.getUsername(), user.getPassword()); + waitForInstanceReady(rdsClient, dbInstanceIdentifier); rdsClient.close(); } private static SecretsManagerClient getSecretClient() { Region region = Region.US_WEST_2; return SecretsManagerClient.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); } private static String getSecretValues(String secretName) { SecretsManagerClient secretClient = getSecretClient(); GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); } public static void createDatabaseInstance(RdsClient rdsClient, - String dbInstanceIdentifier, - String dbName, - String userName, - String userPassword) { + String dbInstanceIdentifier, + String dbName, + String userName, + String userPassword) { try { CreateDbInstanceRequest instanceRequest = CreateDbInstanceRequest.builder() - .dbInstanceIdentifier(dbInstanceIdentifier) - .allocatedStorage(100) - .dbName(dbName) - .engine("mysql") - .dbInstanceClass("db.m4.large") - .engineVersion("8.0") - .storageType("standard") - .masterUsername(userName) - .masterUserPassword(userPassword) - .build(); + .dbInstanceIdentifier(dbInstanceIdentifier) + .allocatedStorage(100) + .dbName(dbName) + .engine("mysql") + .dbInstanceClass("db.m4.large") + .engineVersion("8.0") + .storageType("standard") + .masterUsername(userName) + .masterUserPassword(userPassword) + .build(); CreateDbInstanceResponse response = rdsClient.createDBInstance(instanceRequest); System.out.print("The status is " + response.dbInstance().dbInstanceStatus()); } catch (RdsException e) { - System.out.println(e.getLocalizedMessage()); - System.exit(1); + System.out.println(e.getLocalizedMessage()); + System.exit(1); } } @@ -130,8 +127,8 @@ public static void waitForInstanceReady(RdsClient rdsClient, String dbInstanceId System.out.println("Waiting for instance to become available."); try { DescribeDbInstancesRequest instanceRequest = DescribeDbInstancesRequest.builder() - .dbInstanceIdentifier(dbInstanceIdentifier) - .build(); + .dbInstanceIdentifier(dbInstanceIdentifier) + .build(); // Loop until the cluster is ready. while (!instanceReady) { @@ -156,4 +153,3 @@ public static void waitForInstanceReady(RdsClient rdsClient, String dbInstanceId } // snippet-end:[rds.java2.create_instance.main] } - diff --git a/javav2/example_code/rds/src/main/java/com/example/rds/CreateDBSnapshot.java b/javav2/example_code/rds/src/main/java/com/example/rds/CreateDBSnapshot.java index 1288b27fcc5..dd207dfa0bc 100644 --- a/javav2/example_code/rds/src/main/java/com/example/rds/CreateDBSnapshot.java +++ b/javav2/example_code/rds/src/main/java/com/example/rds/CreateDBSnapshot.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[CreateDBSnapshot.java demonstrates how to create an Amazon Relational Database Service (RDS) snapshot.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Relational Database Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rds; @@ -19,7 +13,8 @@ // snippet-end:[rds.java2.create_snapshot.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,13 +25,13 @@ public class CreateDBSnapshot { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - dbInstanceIdentifier - The database instance identifier.\s - dbSnapshotIdentifier - The snapshot identifier.\s - """; + Where: + dbInstanceIdentifier - The database instance identifier.\s + dbSnapshotIdentifier - The snapshot identifier.\s + """; if (args.length != 2) { System.out.println(usage); @@ -47,8 +42,8 @@ public static void main(String[] args) { String dbSnapshotIdentifier = args[1]; Region region = Region.US_WEST_2; RdsClient rdsClient = RdsClient.builder() - .region(region) - .build(); + .region(region) + .build(); createSnapshot(rdsClient, dbInstanceIdentifier, dbSnapshotIdentifier); rdsClient.close(); @@ -57,9 +52,9 @@ public static void main(String[] args) { public static void createSnapshot(RdsClient rdsClient, String dbInstanceIdentifier, String dbSnapshotIdentifier) { try { CreateDbSnapshotRequest snapshotRequest = CreateDbSnapshotRequest.builder() - .dbInstanceIdentifier(dbInstanceIdentifier) - .dbSnapshotIdentifier(dbSnapshotIdentifier) - .build(); + .dbInstanceIdentifier(dbInstanceIdentifier) + .dbSnapshotIdentifier(dbSnapshotIdentifier) + .build(); CreateDbSnapshotResponse response = rdsClient.createDBSnapshot(snapshotRequest); System.out.print("The Snapshot id is " + response.dbSnapshot().dbiResourceId()); diff --git a/javav2/example_code/rds/src/main/java/com/example/rds/DeleteDBInstance.java b/javav2/example_code/rds/src/main/java/com/example/rds/DeleteDBInstance.java index cdd8c2bf6ea..343d5081797 100644 --- a/javav2/example_code/rds/src/main/java/com/example/rds/DeleteDBInstance.java +++ b/javav2/example_code/rds/src/main/java/com/example/rds/DeleteDBInstance.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DeleteDBInstance.java demonstrates how to delete an Amazon Relational Database Service (RDS) snapshot.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Relational Database Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rds; @@ -19,7 +13,8 @@ // snippet-end:[rds.java2.delete_instance.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,12 +24,12 @@ public class DeleteDBInstance { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - dbInstanceIdentifier - The database instance identifier\s - """; + Where: + dbInstanceIdentifier - The database instance identifier\s + """; if (args.length != 1) { System.out.println(usage); @@ -44,8 +39,8 @@ public static void main(String[] args) { String dbInstanceIdentifier = args[0]; Region region = Region.US_WEST_2; RdsClient rdsClient = RdsClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteDatabaseInstance(rdsClient, dbInstanceIdentifier); rdsClient.close(); @@ -54,10 +49,10 @@ public static void main(String[] args) { public static void deleteDatabaseInstance(RdsClient rdsClient, String dbInstanceIdentifier) { try { DeleteDbInstanceRequest deleteDbInstanceRequest = DeleteDbInstanceRequest.builder() - .dbInstanceIdentifier(dbInstanceIdentifier) - .deleteAutomatedBackups(true) - .skipFinalSnapshot(true) - .build(); + .dbInstanceIdentifier(dbInstanceIdentifier) + .deleteAutomatedBackups(true) + .skipFinalSnapshot(true) + .build(); DeleteDbInstanceResponse response = rdsClient.deleteDBInstance(deleteDbInstanceRequest); System.out.print("The status of the database is " + response.dbInstance().dbInstanceStatus()); diff --git a/javav2/example_code/rds/src/main/java/com/example/rds/DescribeAccountAttributes.java b/javav2/example_code/rds/src/main/java/com/example/rds/DescribeAccountAttributes.java index 4307119ecfb..61c793fb253 100644 --- a/javav2/example_code/rds/src/main/java/com/example/rds/DescribeAccountAttributes.java +++ b/javav2/example_code/rds/src/main/java/com/example/rds/DescribeAccountAttributes.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeAccountAttributes.java demonstrates how to retrieve attributes that belongs to an Amazon Relational Database Service (RDS) account.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Relational Database Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rds; @@ -20,7 +14,8 @@ // snippet-end:[rds.java2.describe_account.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,8 +25,8 @@ public class DescribeAccountAttributes { public static void main(String[] args) { Region region = Region.US_WEST_2; RdsClient rdsClient = RdsClient.builder() - .region(region) - .build(); + .region(region) + .build(); getAccountAttributes(rdsClient); rdsClient.close(); diff --git a/javav2/example_code/rds/src/main/java/com/example/rds/DescribeDBInstances.java b/javav2/example_code/rds/src/main/java/com/example/rds/DescribeDBInstances.java index d608f122969..f1237593135 100644 --- a/javav2/example_code/rds/src/main/java/com/example/rds/DescribeDBInstances.java +++ b/javav2/example_code/rds/src/main/java/com/example/rds/DescribeDBInstances.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[DescribeDBInstances.java demonstrates how to describe Amazon Relational Database Service (RDS) instances.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Relational Database Service] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rds; @@ -19,7 +14,8 @@ // snippet-end:[rds.java2.describe_instances.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,8 +26,8 @@ public class DescribeDBInstances { public static void main(String[] args) { Region region = Region.US_EAST_1; RdsClient rdsClient = RdsClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeInstances(rdsClient); rdsClient.close(); @@ -54,4 +50,3 @@ public static void describeInstances(RdsClient rdsClient) { } } // snippet-end:[rds.java2.describe_instances.main] - diff --git a/javav2/example_code/rds/src/main/java/com/example/rds/DescribeDbClusters.java b/javav2/example_code/rds/src/main/java/com/example/rds/DescribeDbClusters.java index 82f56afcfbb..08feb067c99 100644 --- a/javav2/example_code/rds/src/main/java/com/example/rds/DescribeDbClusters.java +++ b/javav2/example_code/rds/src/main/java/com/example/rds/DescribeDbClusters.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeDbClusters.java describes existing Amazon Aurora DB clusters.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Relational Database Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rds; @@ -18,18 +12,19 @@ public class DescribeDbClusters { public static void main(String[] args) { Region region = Region.US_EAST_1; RdsClient rdsClient = RdsClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeClusters(rdsClient); rdsClient.close(); } - public static void describeClusters( RdsClient rdsClient) { - DescribeDBClustersIterable clustersIterable = rdsClient.describeDBClustersPaginator(); + public static void describeClusters(RdsClient rdsClient) { + DescribeDBClustersIterable clustersIterable = rdsClient.describeDBClustersPaginator(); clustersIterable.stream() - .flatMap(r -> r.dbClusters().stream()) - .forEach(cluster -> System.out.println("Database name: " + cluster.databaseName() + " Arn = " + cluster.dbClusterArn())); + .flatMap(r -> r.dbClusters().stream()) + .forEach(cluster -> System.out + .println("Database name: " + cluster.databaseName() + " Arn = " + cluster.dbClusterArn())); } } // snippet-end:[rds.java2.hello.main] \ No newline at end of file diff --git a/javav2/example_code/rds/src/main/java/com/example/rds/GenerateRDSAuthToken.java b/javav2/example_code/rds/src/main/java/com/example/rds/GenerateRDSAuthToken.java index de557986f1d..4ed42a07950 100644 --- a/javav2/example_code/rds/src/main/java/com/example/rds/GenerateRDSAuthToken.java +++ b/javav2/example_code/rds/src/main/java/com/example/rds/GenerateRDSAuthToken.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[CreateDBInstance.java demonstrates how to generate an authorization token for AWS Identity and Access Management (IAM) authentication to an Amazon Relational Database Service (Amazon RDS) database.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Relational Database Service] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.rds; // snippet-start:[rds.java2.create_token.import] @@ -22,48 +17,48 @@ public class GenerateRDSAuthToken { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - dbInstanceIdentifier - The database instance identifier.\s - masterUsername - The master user name.\s - """; + Where: + dbInstanceIdentifier - The database instance identifier.\s + masterUsername - The master user name.\s + """; - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } - String dbInstanceIdentifier = args[0]; - String masterUsername = args[1]; - Region region = Region.US_WEST_2; - RdsClient rdsClient = RdsClient.builder() + String dbInstanceIdentifier = args[0]; + String masterUsername = args[1]; + Region region = Region.US_WEST_2; + RdsClient rdsClient = RdsClient.builder() .region(region) .build(); - String token = getAuthToken(rdsClient, dbInstanceIdentifier, masterUsername); - System.out.println("The token response is "+token); + String token = getAuthToken(rdsClient, dbInstanceIdentifier, masterUsername); + System.out.println("The token response is " + token); } - public static String getAuthToken(RdsClient rdsClient, String dbInstanceIdentifier, String masterUsername ) { + public static String getAuthToken(RdsClient rdsClient, String dbInstanceIdentifier, String masterUsername) { RdsUtilities utilities = rdsClient.utilities(); try { GenerateAuthenticationTokenRequest tokenRequest = GenerateAuthenticationTokenRequest.builder() - .credentialsProvider(ProfileCredentialsProvider.create()) - .username(masterUsername) - .port(3306) - .hostname(dbInstanceIdentifier) - .build(); + .credentialsProvider(ProfileCredentialsProvider.create()) + .username(masterUsername) + .port(3306) + .hostname(dbInstanceIdentifier) + .build(); - return utilities.generateAuthenticationToken(tokenRequest); + return utilities.generateAuthenticationToken(tokenRequest); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); System.exit(1); } return ""; - } + } } // snippet-end:[rds.java2.create_token.main] diff --git a/javav2/example_code/rds/src/main/java/com/example/rds/ModifyDBInstance.java b/javav2/example_code/rds/src/main/java/com/example/rds/ModifyDBInstance.java index 566c3ffadc8..f427c732ff0 100644 --- a/javav2/example_code/rds/src/main/java/com/example/rds/ModifyDBInstance.java +++ b/javav2/example_code/rds/src/main/java/com/example/rds/ModifyDBInstance.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[ModifyDBInstance.java demonstrates how to modify a RDS instance.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Relational Database Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rds; @@ -19,7 +13,8 @@ // snippet-end:[rds.java2.modify_instance.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,12 +24,12 @@ public class ModifyDBInstance { public static void main(String[] args) { final String usage = """ - Usage: - \s - Where: - dbInstanceIdentifier - The database instance identifier.\s - masterUserPassword - The updated password that corresponds to the master user name.\s - """; + Usage: + \s + Where: + dbInstanceIdentifier - The database instance identifier.\s + masterUserPassword - The updated password that corresponds to the master user name.\s + """; if (args.length != 2) { System.out.println(usage); @@ -45,8 +40,8 @@ public static void main(String[] args) { String masterUserPassword = args[1]; Region region = Region.US_WEST_2; RdsClient rdsClient = RdsClient.builder() - .region(region) - .build(); + .region(region) + .build(); updateIntance(rdsClient, dbInstanceIdentifier, masterUserPassword); rdsClient.close(); @@ -56,10 +51,10 @@ public static void updateIntance(RdsClient rdsClient, String dbInstanceIdentifie try { // For a demo - modify the DB instance by modifying the master password. ModifyDbInstanceRequest modifyDbInstanceRequest = ModifyDbInstanceRequest.builder() - .dbInstanceIdentifier(dbInstanceIdentifier) - .publiclyAccessible(true) - .masterUserPassword(masterUserPassword) - .build(); + .dbInstanceIdentifier(dbInstanceIdentifier) + .publiclyAccessible(true) + .masterUserPassword(masterUserPassword) + .build(); ModifyDbInstanceResponse instanceResponse = rdsClient.modifyDBInstance(modifyDbInstanceRequest); System.out.print("The ARN of the modified database is: " + instanceResponse.dbInstance().dbInstanceArn()); @@ -71,4 +66,3 @@ public static void updateIntance(RdsClient rdsClient, String dbInstanceIdentifie } } // snippet-end:[rds.java2.modify_instance.main] - diff --git a/javav2/example_code/rds/src/main/java/com/example/rds/RDSScenario.java b/javav2/example_code/rds/src/main/java/com/example/rds/RDSScenario.java index 2c9446b4581..8f3034bede6 100644 --- a/javav2/example_code/rds/src/main/java/com/example/rds/RDSScenario.java +++ b/javav2/example_code/rds/src/main/java/com/example/rds/RDSScenario.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[RDSScenario.java demonstrates how to perform multiple operations by using an Amazon Relational Database Service (RDS) service client.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Relational Database Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rds; @@ -53,13 +47,15 @@ // snippet-end:[rds.java2.scenario.import] /** - * Before running this Java (v2) code example, set up your development environment, including your credentials. + * Before running this Java (v2) code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * This example requires an AWS Secrets Manager secret that contains the database credentials. If you do not create a + * This example requires an AWS Secrets Manager secret that contains the + * database credentials. If you do not create a * secret, this example will not work. For details, see: * * https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_how-services-use-secrets_RS.html @@ -74,30 +70,33 @@ * 6. Gets and displays the updated parameters. * 7. Gets a list of allowed engine versions. * 8. Gets a list of micro instance classes available for the selected engine. - * 9. Creates an RDS database instance that contains a MySql database and uses the parameter group. - * 10. Waits for the DB instance to be ready and prints out the connection endpoint value. + * 9. Creates an RDS database instance that contains a MySql database and uses + * the parameter group. + * 10. Waits for the DB instance to be ready and prints out the connection + * endpoint value. * 11. Creates a snapshot of the DB instance. * 12. Waits for an RDS DB snapshot to be ready. - * 13. Deletes the RDS DB instance. + * 13. Deletes the RDS DB instance. * 14. Deletes the parameter group. */ public class RDSScenario { public static long sleepTime = 20; public static final String DASHES = new String(new char[80]).replace("\0", "-"); + public static void main(String[] args) throws InterruptedException { final String usage = """ - Usage: - + Usage: + - Where: - dbGroupName - The database group name.\s - dbParameterGroupFamily - The database parameter group name (for example, mysql8.0). - dbInstanceIdentifier - The database instance identifier\s - dbName - The database name.\s - dbSnapshotIdentifier - The snapshot identifier.\s - secretName - The name of the AWS Secrets Manager secret that contains the database credentials" - """; + Where: + dbGroupName - The database group name.\s + dbParameterGroupFamily - The database parameter group name (for example, mysql8.0). + dbInstanceIdentifier - The database instance identifier\s + dbName - The database name.\s + dbSnapshotIdentifier - The snapshot identifier.\s + secretName - The name of the AWS Secrets Manager secret that contains the database credentials" + """; if (args.length != 6) { System.out.println(usage); @@ -118,8 +117,8 @@ public static void main(String[] args) throws InterruptedException { Region region = Region.US_WEST_2; RdsClient rdsClient = RdsClient.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.println(DASHES); System.out.println("Welcome to the Amazon RDS example scenario."); System.out.println(DASHES); @@ -160,18 +159,20 @@ public static void main(String[] args) throws InterruptedException { System.out.println(DASHES); System.out.println(DASHES); - System.out.println("8. Get a list of micro instance classes available for the selected engine") ; + System.out.println("8. Get a list of micro instance classes available for the selected engine"); getMicroInstances(rdsClient); System.out.println(DASHES); System.out.println(DASHES); - System.out.println("9. Create an RDS database instance that contains a MySql database and uses the parameter group"); - String dbARN = createDatabaseInstance(rdsClient, dbGroupName, dbInstanceIdentifier, dbName, masterUsername, masterUserPassword); - System.out.println("The ARN of the new database is "+dbARN); + System.out.println( + "9. Create an RDS database instance that contains a MySql database and uses the parameter group"); + String dbARN = createDatabaseInstance(rdsClient, dbGroupName, dbInstanceIdentifier, dbName, masterUsername, + masterUserPassword); + System.out.println("The ARN of the new database is " + dbARN); System.out.println(DASHES); System.out.println(DASHES); - System.out.println("10. Wait for DB instance to be ready" ); + System.out.println("10. Wait for DB instance to be ready"); waitForInstanceReady(rdsClient, dbInstanceIdentifier); System.out.println(DASHES); @@ -181,12 +182,12 @@ public static void main(String[] args) throws InterruptedException { System.out.println(DASHES); System.out.println(DASHES); - System.out.println("12. Wait for DB snapshot to be ready" ); + System.out.println("12. Wait for DB snapshot to be ready"); waitForSnapshotReady(rdsClient, dbInstanceIdentifier, dbSnapshotIdentifier); System.out.println(DASHES); System.out.println(DASHES); - System.out.println("13. Delete the DB instance" ); + System.out.println("13. Delete the DB instance"); deleteDatabaseInstance(rdsClient, dbInstanceIdentifier); System.out.println(DASHES); @@ -196,7 +197,7 @@ public static void main(String[] args) throws InterruptedException { System.out.println(DASHES); System.out.println(DASHES); - System.out.println("The Scenario has successfully completed." ); + System.out.println("The Scenario has successfully completed."); System.out.println(DASHES); rdsClient.close(); @@ -205,16 +206,16 @@ public static void main(String[] args) throws InterruptedException { private static SecretsManagerClient getSecretClient() { Region region = Region.US_WEST_2; return SecretsManagerClient.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); } public static String getSecretValues(String secretName) { SecretsManagerClient secretClient = getSecretClient(); GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -222,12 +223,14 @@ public static String getSecretValues(String secretName) { // snippet-start:[rds.java2.scenario.del_paragroup.main] // Delete the parameter group after database has been deleted. - // An exception is thrown if you attempt to delete the para group while database exists. - public static void deleteParaGroup( RdsClient rdsClient, String dbGroupName, String dbARN) throws InterruptedException { + // An exception is thrown if you attempt to delete the para group while database + // exists. + public static void deleteParaGroup(RdsClient rdsClient, String dbGroupName, String dbARN) + throws InterruptedException { try { boolean isDataDel = false; boolean didFind; - String instanceARN ; + String instanceARN; // Make sure that the database has been deleted. while (!isDataDel) { @@ -236,28 +239,28 @@ public static void deleteParaGroup( RdsClient rdsClient, String dbGroupName, Str int listSize = instanceList.size(); didFind = false; int index = 1; - for (DBInstance instance: instanceList) { + for (DBInstance instance : instanceList) { instanceARN = instance.dbInstanceArn(); if (instanceARN.compareTo(dbARN) == 0) { System.out.println(dbARN + " still exists"); - didFind = true ; + didFind = true; } if ((index == listSize) && (!didFind)) { // Went through the entire list and did not find the database ARN. isDataDel = true; } Thread.sleep(sleepTime * 1000); - index ++; + index++; } } // Delete the para group. DeleteDbParameterGroupRequest parameterGroupRequest = DeleteDbParameterGroupRequest.builder() - .dbParameterGroupName(dbGroupName) - .build(); + .dbParameterGroupName(dbGroupName) + .build(); rdsClient.deleteDBParameterGroup(parameterGroupRequest); - System.out.println(dbGroupName +" was deleted."); + System.out.println(dbGroupName + " was deleted."); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); @@ -268,13 +271,13 @@ public static void deleteParaGroup( RdsClient rdsClient, String dbGroupName, Str // snippet-start:[rds.java2.scenario.del_db.main] // Delete the DB instance. - public static void deleteDatabaseInstance( RdsClient rdsClient, String dbInstanceIdentifier) { + public static void deleteDatabaseInstance(RdsClient rdsClient, String dbInstanceIdentifier) { try { DeleteDbInstanceRequest deleteDbInstanceRequest = DeleteDbInstanceRequest.builder() - .dbInstanceIdentifier(dbInstanceIdentifier) - .deleteAutomatedBackups(true) - .skipFinalSnapshot(true) - .build(); + .dbInstanceIdentifier(dbInstanceIdentifier) + .deleteAutomatedBackups(true) + .skipFinalSnapshot(true) + .build(); DeleteDbInstanceResponse response = rdsClient.deleteDBInstance(deleteDbInstanceRequest); System.out.print("The status of the database is " + response.dbInstance().dbInstanceStatus()); @@ -288,16 +291,17 @@ public static void deleteDatabaseInstance( RdsClient rdsClient, String dbInstanc // snippet-start:[rds.java2.scenario.wait_db.main] // Waits until the snapshot instance is available. - public static void waitForSnapshotReady(RdsClient rdsClient, String dbInstanceIdentifier, String dbSnapshotIdentifier) { + public static void waitForSnapshotReady(RdsClient rdsClient, String dbInstanceIdentifier, + String dbSnapshotIdentifier) { try { boolean snapshotReady = false; String snapshotReadyStr; System.out.println("Waiting for the snapshot to become available."); DescribeDbSnapshotsRequest snapshotsRequest = DescribeDbSnapshotsRequest.builder() - .dbSnapshotIdentifier(dbSnapshotIdentifier) - .dbInstanceIdentifier(dbInstanceIdentifier) - .build(); + .dbSnapshotIdentifier(dbSnapshotIdentifier) + .dbInstanceIdentifier(dbInstanceIdentifier) + .build(); while (!snapshotReady) { DescribeDbSnapshotsResponse response = rdsClient.describeDBSnapshots(snapshotsRequest); @@ -326,9 +330,9 @@ public static void waitForSnapshotReady(RdsClient rdsClient, String dbInstanceId public static void createSnapshot(RdsClient rdsClient, String dbInstanceIdentifier, String dbSnapshotIdentifier) { try { CreateDbSnapshotRequest snapshotRequest = CreateDbSnapshotRequest.builder() - .dbInstanceIdentifier(dbInstanceIdentifier) - .dbSnapshotIdentifier(dbSnapshotIdentifier) - .build(); + .dbInstanceIdentifier(dbInstanceIdentifier) + .dbSnapshotIdentifier(dbSnapshotIdentifier) + .build(); CreateDbSnapshotResponse response = rdsClient.createDBSnapshot(snapshotRequest); System.out.println("The Snapshot id is " + response.dbSnapshot().dbiResourceId()); @@ -348,10 +352,10 @@ public static void waitForInstanceReady(RdsClient rdsClient, String dbInstanceId System.out.println("Waiting for instance to become available."); try { DescribeDbInstancesRequest instanceRequest = DescribeDbInstancesRequest.builder() - .dbInstanceIdentifier(dbInstanceIdentifier) - .build(); + .dbInstanceIdentifier(dbInstanceIdentifier) + .build(); - String endpoint=""; + String endpoint = ""; while (!instanceReady) { DescribeDbInstancesResponse response = rdsClient.describeDBInstances(instanceRequest); List instanceList = response.dbInstances(); @@ -366,7 +370,7 @@ public static void waitForInstanceReady(RdsClient rdsClient, String dbInstanceId } } } - System.out.println("Database instance is available! The connection endpoint is "+ endpoint); + System.out.println("Database instance is available! The connection endpoint is " + endpoint); } catch (RdsException | InterruptedException e) { System.err.println(e.getMessage()); @@ -378,25 +382,25 @@ public static void waitForInstanceReady(RdsClient rdsClient, String dbInstanceId // snippet-start:[rds.java2.scenario.create_db.main] // Create a database instance and return the ARN of the database. public static String createDatabaseInstance(RdsClient rdsClient, - String dbGroupName, - String dbInstanceIdentifier, - String dbName, - String masterUsername, - String masterUserPassword) { + String dbGroupName, + String dbInstanceIdentifier, + String dbName, + String masterUsername, + String masterUserPassword) { try { CreateDbInstanceRequest instanceRequest = CreateDbInstanceRequest.builder() - .dbInstanceIdentifier(dbInstanceIdentifier) - .allocatedStorage(100) - .dbName(dbName) - .dbParameterGroupName(dbGroupName) - .engine("mysql") - .dbInstanceClass("db.m4.large") - .engineVersion("8.0") - .storageType("standard") - .masterUsername(masterUsername) - .masterUserPassword(masterUserPassword) - .build(); + .dbInstanceIdentifier(dbInstanceIdentifier) + .allocatedStorage(100) + .dbName(dbName) + .dbParameterGroupName(dbGroupName) + .engine("mysql") + .dbInstanceClass("db.m4.large") + .engineVersion("8.0") + .storageType("standard") + .masterUsername(masterUsername) + .masterUserPassword(masterUserPassword) + .build(); CreateDbInstanceResponse response = rdsClient.createDBInstance(instanceRequest); System.out.print("The status is " + response.dbInstance().dbInstanceStatus()); @@ -415,15 +419,17 @@ public static String createDatabaseInstance(RdsClient rdsClient, // Get a list of micro instances. public static void getMicroInstances(RdsClient rdsClient) { try { - DescribeOrderableDbInstanceOptionsRequest dbInstanceOptionsRequest = DescribeOrderableDbInstanceOptionsRequest.builder() - .engine("mysql") - .build(); + DescribeOrderableDbInstanceOptionsRequest dbInstanceOptionsRequest = DescribeOrderableDbInstanceOptionsRequest + .builder() + .engine("mysql") + .build(); - DescribeOrderableDbInstanceOptionsResponse response = rdsClient.describeOrderableDBInstanceOptions(dbInstanceOptionsRequest); + DescribeOrderableDbInstanceOptionsResponse response = rdsClient + .describeOrderableDBInstanceOptions(dbInstanceOptionsRequest); List orderableDBInstances = response.orderableDBInstanceOptions(); - for (OrderableDBInstanceOption dbInstanceOption: orderableDBInstances) { - System.out.println("The engine version is " +dbInstanceOption.engineVersion()); - System.out.println("The engine description is " +dbInstanceOption.engine()); + for (OrderableDBInstanceOption dbInstanceOption : orderableDBInstances) { + System.out.println("The engine version is " + dbInstanceOption.engineVersion()); + System.out.println("The engine description is " + dbInstanceOption.engine()); } } catch (RdsException e) { @@ -438,16 +444,16 @@ public static void getMicroInstances(RdsClient rdsClient) { public static void getAllowedEngines(RdsClient rdsClient, String dbParameterGroupFamily) { try { DescribeDbEngineVersionsRequest versionsRequest = DescribeDbEngineVersionsRequest.builder() - .dbParameterGroupFamily(dbParameterGroupFamily) - .engine("mysql") - .build(); - - DescribeDbEngineVersionsResponse response = rdsClient.describeDBEngineVersions(versionsRequest); - List dbEngines = response.dbEngineVersions(); - for (DBEngineVersion dbEngine: dbEngines) { - System.out.println("The engine version is " +dbEngine.engineVersion()); - System.out.println("The engine description is " +dbEngine.dbEngineDescription()); - } + .dbParameterGroupFamily(dbParameterGroupFamily) + .engine("mysql") + .build(); + + DescribeDbEngineVersionsResponse response = rdsClient.describeDBEngineVersions(versionsRequest); + List dbEngines = response.dbEngineVersions(); + for (DBEngineVersion dbEngine : dbEngines) { + System.out.println("The engine version is " + dbEngine.engineVersion()); + System.out.println("The engine description is " + dbEngine.dbEngineDescription()); + } } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); @@ -461,20 +467,20 @@ public static void getAllowedEngines(RdsClient rdsClient, String dbParameterGrou public static void modifyDBParas(RdsClient rdsClient, String dbGroupName) { try { Parameter parameter1 = Parameter.builder() - .parameterName("auto_increment_offset") - .applyMethod("immediate") - .parameterValue("5") - .build(); + .parameterName("auto_increment_offset") + .applyMethod("immediate") + .parameterValue("5") + .build(); List paraList = new ArrayList<>(); paraList.add(parameter1); ModifyDbParameterGroupRequest groupRequest = ModifyDbParameterGroupRequest.builder() - .dbParameterGroupName(dbGroupName) - .parameters(paraList) - .build(); + .dbParameterGroupName(dbGroupName) + .parameters(paraList) + .build(); ModifyDbParameterGroupResponse response = rdsClient.modifyDBParameterGroup(groupRequest); - System.out.println("The parameter group "+ response.dbParameterGroupName() +" was successfully modified"); + System.out.println("The parameter group " + response.dbParameterGroupName() + " was successfully modified"); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); @@ -483,57 +489,59 @@ public static void modifyDBParas(RdsClient rdsClient, String dbGroupName) { } // snippet-end:[rds.java2.scenario.mod_paras.main] - // snippet-start:[rds.java2.scenario.get_paras.main] - // Retrieve parameters in the group. - public static void describeDbParameters(RdsClient rdsClient, String dbGroupName, int flag) { - try { - DescribeDbParametersRequest dbParameterGroupsRequest; - if (flag == 0) { - dbParameterGroupsRequest = DescribeDbParametersRequest.builder() - .dbParameterGroupName(dbGroupName) - .build(); - } else { - dbParameterGroupsRequest = DescribeDbParametersRequest.builder() - .dbParameterGroupName(dbGroupName) - .source("user") - .build(); - } - - DescribeDbParametersResponse response = rdsClient.describeDBParameters(dbParameterGroupsRequest); - List dbParameters = response.parameters(); - String paraName; - for (Parameter para: dbParameters) { - // Only print out information about either auto_increment_offset or auto_increment_increment. - paraName = para.parameterName(); - if ( (paraName.compareTo("auto_increment_offset") ==0) || (paraName.compareTo("auto_increment_increment ") ==0)) { - System.out.println("*** The parameter name is " + paraName); - System.out.println("*** The parameter value is " + para.parameterValue()); - System.out.println("*** The parameter data type is " + para.dataType()); - System.out.println("*** The parameter description is " + para.description()); - System.out.println("*** The parameter allowed values is " + para.allowedValues()); - } - } - - } catch (RdsException e) { - System.out.println(e.getLocalizedMessage()); - System.exit(1); - } - } - // snippet-end:[rds.java2.scenario.get_paras.main] + // snippet-start:[rds.java2.scenario.get_paras.main] + // Retrieve parameters in the group. + public static void describeDbParameters(RdsClient rdsClient, String dbGroupName, int flag) { + try { + DescribeDbParametersRequest dbParameterGroupsRequest; + if (flag == 0) { + dbParameterGroupsRequest = DescribeDbParametersRequest.builder() + .dbParameterGroupName(dbGroupName) + .build(); + } else { + dbParameterGroupsRequest = DescribeDbParametersRequest.builder() + .dbParameterGroupName(dbGroupName) + .source("user") + .build(); + } + + DescribeDbParametersResponse response = rdsClient.describeDBParameters(dbParameterGroupsRequest); + List dbParameters = response.parameters(); + String paraName; + for (Parameter para : dbParameters) { + // Only print out information about either auto_increment_offset or + // auto_increment_increment. + paraName = para.parameterName(); + if ((paraName.compareTo("auto_increment_offset") == 0) + || (paraName.compareTo("auto_increment_increment ") == 0)) { + System.out.println("*** The parameter name is " + paraName); + System.out.println("*** The parameter value is " + para.parameterValue()); + System.out.println("*** The parameter data type is " + para.dataType()); + System.out.println("*** The parameter description is " + para.description()); + System.out.println("*** The parameter allowed values is " + para.allowedValues()); + } + } + + } catch (RdsException e) { + System.out.println(e.getLocalizedMessage()); + System.exit(1); + } + } + // snippet-end:[rds.java2.scenario.get_paras.main] // snippet-start:[rds.java2.scenario.desc_para_groups.main] public static void describeDbParameterGroups(RdsClient rdsClient, String dbGroupName) { try { DescribeDbParameterGroupsRequest groupsRequest = DescribeDbParameterGroupsRequest.builder() - .dbParameterGroupName(dbGroupName) - .maxRecords(20) - .build(); + .dbParameterGroupName(dbGroupName) + .maxRecords(20) + .build(); DescribeDbParameterGroupsResponse response = rdsClient.describeDBParameterGroups(groupsRequest); List groups = response.dbParameterGroups(); - for (DBParameterGroup group: groups) { - System.out.println("The group name is "+group.dbParameterGroupName()); - System.out.println("The group description is "+group.description()); + for (DBParameterGroup group : groups) { + System.out.println("The group name is " + group.dbParameterGroupName()); + System.out.println("The group description is " + group.description()); } } catch (RdsException e) { @@ -547,13 +555,13 @@ public static void describeDbParameterGroups(RdsClient rdsClient, String dbGroup public static void createDBParameterGroup(RdsClient rdsClient, String dbGroupName, String dbParameterGroupFamily) { try { CreateDbParameterGroupRequest groupRequest = CreateDbParameterGroupRequest.builder() - .dbParameterGroupName(dbGroupName) - .dbParameterGroupFamily(dbParameterGroupFamily) - .description("Created by using the AWS SDK for Java") - .build(); + .dbParameterGroupName(dbGroupName) + .dbParameterGroupFamily(dbParameterGroupFamily) + .description("Created by using the AWS SDK for Java") + .build(); CreateDbParameterGroupResponse response = rdsClient.createDBParameterGroup(groupRequest); - System.out.println("The group name is "+ response.dbParameterGroup().dbParameterGroupName()); + System.out.println("The group name is " + response.dbParameterGroup().dbParameterGroupName()); } catch (RdsException e) { System.out.println(e.getLocalizedMessage()); @@ -562,24 +570,24 @@ public static void createDBParameterGroup(RdsClient rdsClient, String dbGroupNam } // snippet-end:[rds.java2.scenario.create_para_group.main] - // snippet-start:[rds.java2.scenario_desc_engine.main] - public static void describeDBEngines( RdsClient rdsClient) { + public static void describeDBEngines(RdsClient rdsClient) { try { DescribeDbEngineVersionsRequest engineVersionsRequest = DescribeDbEngineVersionsRequest.builder() - .defaultOnly(true) - .engine("mysql") - .maxRecords(20) - .build(); + .defaultOnly(true) + .engine("mysql") + .maxRecords(20) + .build(); DescribeDbEngineVersionsResponse response = rdsClient.describeDBEngineVersions(engineVersionsRequest); List engines = response.dbEngineVersions(); // Get all DBEngineVersion objects. - for (DBEngineVersion engineOb: engines) { - System.out.println("The name of the DB parameter group family for the database engine is "+engineOb.dbParameterGroupFamily()); - System.out.println("The name of the database engine "+engineOb.engine()); - System.out.println("The version number of the database engine "+engineOb.engineVersion()); + for (DBEngineVersion engineOb : engines) { + System.out.println("The name of the DB parameter group family for the database engine is " + + engineOb.dbParameterGroupFamily()); + System.out.println("The name of the database engine " + engineOb.engine()); + System.out.println("The version number of the database engine " + engineOb.engineVersion()); } } catch (RdsException e) { diff --git a/javav2/example_code/rds/src/main/java/com/example/rds/RebootDBInstance.java b/javav2/example_code/rds/src/main/java/com/example/rds/RebootDBInstance.java index 53cabe786f7..3aa20b93db7 100644 --- a/javav2/example_code/rds/src/main/java/com/example/rds/RebootDBInstance.java +++ b/javav2/example_code/rds/src/main/java/com/example/rds/RebootDBInstance.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[RebootDBInstance.java demonstrates how to reboot an Amazon Relational Database Service (RDS) instance.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Relational Database Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rds; @@ -19,7 +13,8 @@ // snippet-end:[rds.java2.reboot_instance.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,12 +24,12 @@ public class RebootDBInstance { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - dbInstanceIdentifier - The database instance identifier\s - """; + Where: + dbInstanceIdentifier - The database instance identifier\s + """; if (args.length != 1) { System.out.println(usage); @@ -44,8 +39,8 @@ public static void main(String[] args) { String dbInstanceIdentifier = args[0]; Region region = Region.US_WEST_2; RdsClient rdsClient = RdsClient.builder() - .region(region) - .build(); + .region(region) + .build(); rebootInstance(rdsClient, dbInstanceIdentifier); rdsClient.close(); @@ -54,8 +49,8 @@ public static void main(String[] args) { public static void rebootInstance(RdsClient rdsClient, String dbInstanceIdentifier) { try { RebootDbInstanceRequest rebootDbInstanceRequest = RebootDbInstanceRequest.builder() - .dbInstanceIdentifier(dbInstanceIdentifier) - .build(); + .dbInstanceIdentifier(dbInstanceIdentifier) + .build(); RebootDbInstanceResponse instanceResponse = rdsClient.rebootDBInstance(rebootDbInstanceRequest); System.out.print("The database " + instanceResponse.dbInstance().dbInstanceArn() + " was rebooted"); @@ -66,5 +61,4 @@ public static void rebootInstance(RdsClient rdsClient, String dbInstanceIdentifi } } } - // snippet-end:[rds.java2.reboot_instance.main] - +// snippet-end:[rds.java2.reboot_instance.main] diff --git a/javav2/example_code/rds/src/main/java/com/example/rds/StartDatabase.java b/javav2/example_code/rds/src/main/java/com/example/rds/StartDatabase.java index d0b70985a05..a39da53125b 100644 --- a/javav2/example_code/rds/src/main/java/com/example/rds/StartDatabase.java +++ b/javav2/example_code/rds/src/main/java/com/example/rds/StartDatabase.java @@ -1,66 +1,63 @@ -//snippet-sourcedescription:[StartDatabase.java demonstrates how to start an Amazon Relational Database Service (RDS) instance.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Relational Database Service] - - -package com.example.rds; - -// snippet-start:[rds.java2.start_instance.main] -// snippet-start:[rds.java2.start_instance.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.rds.RdsClient; -import software.amazon.awssdk.services.rds.model.RdsException; -import software.amazon.awssdk.services.rds.model.StartDbInstanceRequest; -// snippet-end:[rds.java2.start_instance.import] - -/** - * Before running this Java V2 code example, set up your development environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ -public class StartDatabase { - public static void main(String[] args) { - - final String usage = """ - - Usage: - \s - - Where: - dbInstanceIdentifier - The database instance identifier\s - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String dbInstanceIdentifier = args[0]; - Region region = Region.US_WEST_2; - RdsClient rdsClient = RdsClient.builder() - .region(region) - .build(); - - startInstance(rdsClient, dbInstanceIdentifier); - rdsClient.close(); - } - - public static void startInstance(RdsClient rdsClient, String dbInstanceIdentifier) { - try { - StartDbInstanceRequest startDbInstanceRequest = StartDbInstanceRequest.builder() - .dbInstanceIdentifier(dbInstanceIdentifier) - .build(); - - rdsClient.startDBInstance(startDbInstanceRequest); - System.out.print("The database was started!"); - - } catch (RdsException e) { - System.out.println(e.getLocalizedMessage()); - System.exit(1); - } - } -} -// snippet-end:[rds.java2.start_instance.main] - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package com.example.rds; + +// snippet-start:[rds.java2.start_instance.main] +// snippet-start:[rds.java2.start_instance.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.rds.RdsClient; +import software.amazon.awssdk.services.rds.model.RdsException; +import software.amazon.awssdk.services.rds.model.StartDbInstanceRequest; +// snippet-end:[rds.java2.start_instance.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ +public class StartDatabase { + public static void main(String[] args) { + + final String usage = """ + + Usage: + \s + + Where: + dbInstanceIdentifier - The database instance identifier\s + """; + + if (args.length != 1) { + System.out.println(usage); + System.exit(1); + } + + String dbInstanceIdentifier = args[0]; + Region region = Region.US_WEST_2; + RdsClient rdsClient = RdsClient.builder() + .region(region) + .build(); + + startInstance(rdsClient, dbInstanceIdentifier); + rdsClient.close(); + } + + public static void startInstance(RdsClient rdsClient, String dbInstanceIdentifier) { + try { + StartDbInstanceRequest startDbInstanceRequest = StartDbInstanceRequest.builder() + .dbInstanceIdentifier(dbInstanceIdentifier) + .build(); + + rdsClient.startDBInstance(startDbInstanceRequest); + System.out.print("The database was started!"); + + } catch (RdsException e) { + System.out.println(e.getLocalizedMessage()); + System.exit(1); + } + } +} +// snippet-end:[rds.java2.start_instance.main] diff --git a/javav2/example_code/rds/src/main/java/com/example/rds/StopDatabase.java b/javav2/example_code/rds/src/main/java/com/example/rds/StopDatabase.java index ed6e03d1ce6..546b74ac95c 100644 --- a/javav2/example_code/rds/src/main/java/com/example/rds/StopDatabase.java +++ b/javav2/example_code/rds/src/main/java/com/example/rds/StopDatabase.java @@ -1,64 +1,62 @@ -//snippet-sourcedescription:[StopDatabase.java demonstrates how to stop an Amazon Relational Database Service (RDS) instance.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Relational Database Service] - -package com.example.rds; - -// snippet-start:[rds.java2.stop_instance.main] -// snippet-start:[rds.java2.stop_instance.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.rds.RdsClient; -import software.amazon.awssdk.services.rds.model.RdsException; -import software.amazon.awssdk.services.rds.model.StopDbInstanceRequest; -// snippet-end:[rds.java2.stop_instance.import] - -/** - * Before running this Java V2 code example, set up your development environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ -public class StopDatabase { - public static void main(String[] args) { - final String usage = """ - - Usage: - \s - - Where: - dbInstanceIdentifier - The database instance identifier\s - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String dbInstanceIdentifier = args[0]; - Region region = Region.US_WEST_2; - RdsClient rdsClient = RdsClient.builder() - .region(region) - .build(); - - stopInstance(rdsClient, dbInstanceIdentifier); - rdsClient.close(); - } - - public static void stopInstance(RdsClient rdsClient, String dbInstanceIdentifier) { - try { - StopDbInstanceRequest stopDbInstanceRequest = StopDbInstanceRequest.builder() - .dbInstanceIdentifier(dbInstanceIdentifier) - .build(); - - rdsClient.stopDBInstance(stopDbInstanceRequest); - System.out.print("The database was stopped!"); - - } catch (RdsException e) { - System.out.println(e.getLocalizedMessage()); - System.exit(1); - } - } -} -// snippet-end:[rds.java2.stop_instance.main] - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package com.example.rds; + +// snippet-start:[rds.java2.stop_instance.main] +// snippet-start:[rds.java2.stop_instance.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.rds.RdsClient; +import software.amazon.awssdk.services.rds.model.RdsException; +import software.amazon.awssdk.services.rds.model.StopDbInstanceRequest; +// snippet-end:[rds.java2.stop_instance.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ +public class StopDatabase { + public static void main(String[] args) { + final String usage = """ + + Usage: + \s + + Where: + dbInstanceIdentifier - The database instance identifier\s + """; + + if (args.length != 1) { + System.out.println(usage); + System.exit(1); + } + + String dbInstanceIdentifier = args[0]; + Region region = Region.US_WEST_2; + RdsClient rdsClient = RdsClient.builder() + .region(region) + .build(); + + stopInstance(rdsClient, dbInstanceIdentifier); + rdsClient.close(); + } + + public static void stopInstance(RdsClient rdsClient, String dbInstanceIdentifier) { + try { + StopDbInstanceRequest stopDbInstanceRequest = StopDbInstanceRequest.builder() + .dbInstanceIdentifier(dbInstanceIdentifier) + .build(); + + rdsClient.stopDBInstance(stopDbInstanceRequest); + System.out.print("The database was stopped!"); + + } catch (RdsException e) { + System.out.println(e.getLocalizedMessage()); + System.exit(1); + } + } +} +// snippet-end:[rds.java2.stop_instance.main] diff --git a/javav2/example_code/rds/src/main/java/com/example/rds/User.java b/javav2/example_code/rds/src/main/java/com/example/rds/User.java index 3c0129c7a9a..925e6170918 100644 --- a/javav2/example_code/rds/src/main/java/com/example/rds/User.java +++ b/javav2/example_code/rds/src/main/java/com/example/rds/User.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rds; public class User { diff --git a/javav2/example_code/rds/src/test/java/AmazonRDSTest.java b/javav2/example_code/rds/src/test/java/AmazonRDSTest.java index b01c76b0f8b..d03b839d8d6 100644 --- a/javav2/example_code/rds/src/test/java/AmazonRDSTest.java +++ b/javav2/example_code/rds/src/test/java/AmazonRDSTest.java @@ -1,7 +1,6 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + import com.example.rds.*; import com.google.gson.Gson; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; @@ -24,21 +23,21 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AmazonRDSTest { - private static RdsClient rdsClient ; + private static RdsClient rdsClient; - private static String dbInstanceIdentifier = "" ; - private static String dbSnapshotIdentifier = "" ; - private static String dbName = "" ; + private static String dbInstanceIdentifier = ""; + private static String dbSnapshotIdentifier = ""; + private static String dbName = ""; - private static String newMasterUserPassword = "" ; + private static String newMasterUserPassword = ""; // Set data members required for the Scenario test. - private static String dbGroupNameSc = "" ; - private static String dbParameterGroupFamilySc = "" ; - private static String dbInstanceIdentifierSc = "" ; - private static String secretDBName = "" ; - private static String dbSnapshotIdentifierSc = "" ; - private static String dbNameSc = "" ; + private static String dbGroupNameSc = ""; + private static String dbParameterGroupFamilySc = ""; + private static String dbInstanceIdentifierSc = ""; + private static String secretDBName = ""; + private static String dbSnapshotIdentifierSc = ""; + private static String dbNameSc = ""; private static String dbClusterGroupName; @@ -49,9 +48,9 @@ public class AmazonRDSTest { @BeforeAll public static void setUp() throws IOException { rdsClient = RdsClient.builder() - .region(Region.US_WEST_2) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_WEST_2) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); Random rand = new Random(); int randomNum = rand.nextInt((10000 - 1) + 1) + 1; @@ -60,48 +59,56 @@ public static void setUp() throws IOException { Gson gson = new Gson(); String json = getSecretValues(); SecretValues values = gson.fromJson(json, SecretValues.class); - dbInstanceIdentifier = values.getDbInstanceIdentifier()+ java.util.UUID.randomUUID(); - dbSnapshotIdentifier = values.getDbSnapshotIdentifier()+ java.util.UUID.randomUUID(); - dbName = values.getDbName()+ randomNum; + dbInstanceIdentifier = values.getDbInstanceIdentifier() + java.util.UUID.randomUUID(); + dbSnapshotIdentifier = values.getDbSnapshotIdentifier() + java.util.UUID.randomUUID(); + dbName = values.getDbName() + randomNum; newMasterUserPassword = values.getNewMasterUserPassword(); - dbGroupNameSc = values.getDbGroupNameSc()+ java.util.UUID.randomUUID(); + dbGroupNameSc = values.getDbGroupNameSc() + java.util.UUID.randomUUID(); dbParameterGroupFamilySc = values.getDbParameterGroupFamilySc(); - dbInstanceIdentifierSc = values.getDbInstanceIdentifierSc()+ java.util.UUID.randomUUID(); - dbSnapshotIdentifierSc = values.getDbSnapshotIdentifierSc()+ java.util.UUID.randomUUID(); - dbNameSc = values.getDbNameSc()+ randomNum ; - dbClusterGroupName = values.getDbClusterGroupName()+randomNum; + dbInstanceIdentifierSc = values.getDbInstanceIdentifierSc() + java.util.UUID.randomUUID(); + dbSnapshotIdentifierSc = values.getDbSnapshotIdentifierSc() + java.util.UUID.randomUUID(); + dbNameSc = values.getDbNameSc() + randomNum; + dbClusterGroupName = values.getDbClusterGroupName() + randomNum; dbParameterGroupFamily = values.getDbParameterGroupFamily(); dbInstanceClusterIdentifier = values.getDbInstanceClusterIdentifier(); secretDBName = values.getSecretName(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - try (InputStream input = AmazonRDSTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - prop.load(input); - dbInstanceIdentifier = prop.getProperty("dbInstanceIdentifier")+ java.util.UUID.randomUUID(); - dbSnapshotIdentifier = prop.getProperty("dbSnapshotIdentifier")+ java.util.UUID.randomUUID(); - dbName = prop.getProperty("dbName")+ randomNum; - masterUsername = prop.getProperty("masterUsername"); - masterUserPassword = prop.getProperty("masterUserPassword"); - newMasterUserPassword = prop.getProperty("newMasterUserPassword"); - dbGroupNameSc = prop.getProperty("dbGroupNameSc")+ java.util.UUID.randomUUID();; - dbParameterGroupFamilySc = prop.getProperty("dbParameterGroupFamilySc"); - dbInstanceIdentifierSc = prop.getProperty("dbInstanceIdentifierSc")+ java.util.UUID.randomUUID();; - masterUsernameSc = prop.getProperty("masterUsernameSc"); - masterUserPasswordSc = prop.getProperty("masterUserPasswordSc"); - dbSnapshotIdentifierSc = prop.getProperty("dbSnapshotIdentifierSc")+ java.util.UUID.randomUUID();; - dbNameSc = prop.getProperty("dbNameSc")+ randomNum ; - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * try (InputStream input = + * AmazonRDSTest.class.getClassLoader().getResourceAsStream("config.properties") + * ) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * prop.load(input); + * dbInstanceIdentifier = prop.getProperty("dbInstanceIdentifier")+ + * java.util.UUID.randomUUID(); + * dbSnapshotIdentifier = prop.getProperty("dbSnapshotIdentifier")+ + * java.util.UUID.randomUUID(); + * dbName = prop.getProperty("dbName")+ randomNum; + * masterUsername = prop.getProperty("masterUsername"); + * masterUserPassword = prop.getProperty("masterUserPassword"); + * newMasterUserPassword = prop.getProperty("newMasterUserPassword"); + * dbGroupNameSc = prop.getProperty("dbGroupNameSc")+ + * java.util.UUID.randomUUID();; + * dbParameterGroupFamilySc = prop.getProperty("dbParameterGroupFamilySc"); + * dbInstanceIdentifierSc = prop.getProperty("dbInstanceIdentifierSc")+ + * java.util.UUID.randomUUID();; + * masterUsernameSc = prop.getProperty("masterUsernameSc"); + * masterUserPasswordSc = prop.getProperty("masterUserPasswordSc"); + * dbSnapshotIdentifierSc = prop.getProperty("dbSnapshotIdentifierSc")+ + * java.util.UUID.randomUUID();; + * dbNameSc = prop.getProperty("dbNameSc")+ randomNum ; + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @@ -110,7 +117,8 @@ public static void setUp() throws IOException { public void CreateDBInstance() { Gson gson = new Gson(); User user = gson.fromJson(String.valueOf(RDSScenario.getSecretValues(secretDBName)), User.class); - assertDoesNotThrow(() ->CreateDBInstance.createDatabaseInstance(rdsClient, dbInstanceIdentifier, dbName, user.getUsername(), user.getPassword())); + assertDoesNotThrow(() -> CreateDBInstance.createDatabaseInstance(rdsClient, dbInstanceIdentifier, dbName, + user.getUsername(), user.getPassword())); System.out.println("CreateDBInstance test passed"); } @@ -118,7 +126,7 @@ public void CreateDBInstance() { @Tag("IntegrationTest") @Order(2) public void waitForInstanceReady() { - assertDoesNotThrow(() ->CreateDBInstance.waitForInstanceReady(rdsClient, dbInstanceIdentifier)); + assertDoesNotThrow(() -> CreateDBInstance.waitForInstanceReady(rdsClient, dbInstanceIdentifier)); System.out.println("waitForInstanceReady test passed"); } @@ -126,7 +134,7 @@ public void waitForInstanceReady() { @Tag("IntegrationTest") @Order(3) public void DescribeAccountAttributes() { - assertDoesNotThrow(() ->DescribeAccountAttributes.getAccountAttributes(rdsClient)); + assertDoesNotThrow(() -> DescribeAccountAttributes.getAccountAttributes(rdsClient)); System.out.println("DescribeAccountAttributes test passed"); } @@ -134,7 +142,7 @@ public void DescribeAccountAttributes() { @Tag("IntegrationTest") @Order(4) public void DescribeDBInstances() { - assertDoesNotThrow(() ->DescribeDBInstances.describeInstances(rdsClient)); + assertDoesNotThrow(() -> DescribeDBInstances.describeInstances(rdsClient)); System.out.println("DescribeDBInstances test passed"); } @@ -142,14 +150,16 @@ public void DescribeDBInstances() { @Tag("IntegrationTest") @Order(5) public void ModifyDBInstance() { - assertDoesNotThrow(() ->ModifyDBInstance.updateIntance(rdsClient, dbInstanceIdentifier, newMasterUserPassword)); + assertDoesNotThrow( + () -> ModifyDBInstance.updateIntance(rdsClient, dbInstanceIdentifier, newMasterUserPassword)); System.out.println("ModifyDBInstance test passed"); } @Test @Order(6) public void CreateDBSnapshot() { - assertDoesNotThrow(() ->CreateDBSnapshot.createSnapshot(rdsClient, dbInstanceIdentifier, dbSnapshotIdentifier)); + assertDoesNotThrow( + () -> CreateDBSnapshot.createSnapshot(rdsClient, dbInstanceIdentifier, dbSnapshotIdentifier)); System.out.println("CreateDBSnapshot test passed"); } @@ -157,7 +167,7 @@ public void CreateDBSnapshot() { @Tag("IntegrationTest") @Order(7) public void DeleteDBInstance() { - assertDoesNotThrow(() ->DeleteDBInstance.deleteDatabaseInstance(rdsClient, dbInstanceIdentifier)); + assertDoesNotThrow(() -> DeleteDBInstance.deleteDatabaseInstance(rdsClient, dbInstanceIdentifier)); System.out.println("DeleteDBInstance test passed"); } @@ -167,21 +177,24 @@ public void DeleteDBInstance() { public void TestRDSScenario() throws InterruptedException { Gson gson = new Gson(); User user = gson.fromJson(String.valueOf(RDSScenario.getSecretValues(secretDBName)), User.class); - assertDoesNotThrow(() ->RDSScenario.describeDBEngines(rdsClient)); - assertDoesNotThrow(() ->RDSScenario.createDBParameterGroup(rdsClient, dbGroupNameSc, dbParameterGroupFamilySc)); - assertDoesNotThrow(() ->RDSScenario.describeDbParameterGroups(rdsClient, dbGroupNameSc)); - assertDoesNotThrow(() ->RDSScenario.describeDbParameters(rdsClient, dbGroupNameSc, 0)); - assertDoesNotThrow(() ->RDSScenario.modifyDBParas(rdsClient, dbGroupNameSc)); - assertDoesNotThrow(() ->RDSScenario.describeDbParameters(rdsClient, dbGroupNameSc, -1)); - assertDoesNotThrow(() ->RDSScenario.getAllowedEngines(rdsClient, dbParameterGroupFamilySc)); - assertDoesNotThrow(() ->RDSScenario.getMicroInstances(rdsClient)); - String dbARN = RDSScenario.createDatabaseInstance(rdsClient, dbGroupNameSc, dbInstanceIdentifierSc, dbNameSc, user.getUsername(), user.getPassword()); + assertDoesNotThrow(() -> RDSScenario.describeDBEngines(rdsClient)); + assertDoesNotThrow( + () -> RDSScenario.createDBParameterGroup(rdsClient, dbGroupNameSc, dbParameterGroupFamilySc)); + assertDoesNotThrow(() -> RDSScenario.describeDbParameterGroups(rdsClient, dbGroupNameSc)); + assertDoesNotThrow(() -> RDSScenario.describeDbParameters(rdsClient, dbGroupNameSc, 0)); + assertDoesNotThrow(() -> RDSScenario.modifyDBParas(rdsClient, dbGroupNameSc)); + assertDoesNotThrow(() -> RDSScenario.describeDbParameters(rdsClient, dbGroupNameSc, -1)); + assertDoesNotThrow(() -> RDSScenario.getAllowedEngines(rdsClient, dbParameterGroupFamilySc)); + assertDoesNotThrow(() -> RDSScenario.getMicroInstances(rdsClient)); + String dbARN = RDSScenario.createDatabaseInstance(rdsClient, dbGroupNameSc, dbInstanceIdentifierSc, dbNameSc, + user.getUsername(), user.getPassword()); assertFalse(dbARN.isEmpty()); - assertDoesNotThrow(() ->RDSScenario.waitForInstanceReady(rdsClient, dbInstanceIdentifierSc)); - assertDoesNotThrow(() ->RDSScenario.createSnapshot(rdsClient, dbInstanceIdentifierSc, dbSnapshotIdentifierSc)); - assertDoesNotThrow(() ->RDSScenario.waitForSnapshotReady(rdsClient, dbInstanceIdentifierSc, dbSnapshotIdentifierSc)); - assertDoesNotThrow(() ->RDSScenario.deleteDatabaseInstance(rdsClient, dbInstanceIdentifierSc)); - assertDoesNotThrow(() ->RDSScenario.deleteParaGroup(rdsClient, dbGroupNameSc, dbARN)); + assertDoesNotThrow(() -> RDSScenario.waitForInstanceReady(rdsClient, dbInstanceIdentifierSc)); + assertDoesNotThrow(() -> RDSScenario.createSnapshot(rdsClient, dbInstanceIdentifierSc, dbSnapshotIdentifierSc)); + assertDoesNotThrow( + () -> RDSScenario.waitForSnapshotReady(rdsClient, dbInstanceIdentifierSc, dbSnapshotIdentifierSc)); + assertDoesNotThrow(() -> RDSScenario.deleteDatabaseInstance(rdsClient, dbInstanceIdentifierSc)); + assertDoesNotThrow(() -> RDSScenario.deleteParaGroup(rdsClient, dbGroupNameSc, dbARN)); System.out.println("TestRDSScenario test passed"); } @@ -192,37 +205,42 @@ public void TestAuroraScenario() throws InterruptedException { Gson gson = new Gson(); User user = gson.fromJson(String.valueOf(RDSScenario.getSecretValues(secretDBName)), User.class); System.out.println("1. Return a list of the available DB engines"); - assertDoesNotThrow(() ->AuroraScenario.describeDBEngines(rdsClient)); + assertDoesNotThrow(() -> AuroraScenario.describeDBEngines(rdsClient)); System.out.println("2. Create a custom parameter group"); - assertDoesNotThrow(() ->AuroraScenario.createDBClusterParameterGroup(rdsClient, dbClusterGroupName, dbParameterGroupFamily)); + assertDoesNotThrow(() -> AuroraScenario.createDBClusterParameterGroup(rdsClient, dbClusterGroupName, + dbParameterGroupFamily)); System.out.println("3. Get the parameter group"); - assertDoesNotThrow(() ->AuroraScenario.describeDbClusterParameterGroups(rdsClient, dbClusterGroupName)); + assertDoesNotThrow(() -> AuroraScenario.describeDbClusterParameterGroups(rdsClient, dbClusterGroupName)); System.out.println("4. Get the parameters in the group"); - assertDoesNotThrow(() ->AuroraScenario.describeDbClusterParameters(rdsClient, dbClusterGroupName, 0)); + assertDoesNotThrow(() -> AuroraScenario.describeDbClusterParameters(rdsClient, dbClusterGroupName, 0)); System.out.println("5. Modify the auto_increment_offset parameter"); - assertDoesNotThrow(() ->AuroraScenario.modifyDBClusterParas(rdsClient, dbClusterGroupName)); + assertDoesNotThrow(() -> AuroraScenario.modifyDBClusterParas(rdsClient, dbClusterGroupName)); System.out.println("6. Display the updated parameter value"); assertDoesNotThrow(() -> AuroraScenario.describeDbClusterParameters(rdsClient, dbClusterGroupName, -1)); System.out.println("7. Get a list of allowed engine versions"); - assertDoesNotThrow(() ->AuroraScenario.getAllowedEngines(rdsClient, dbParameterGroupFamily)); + assertDoesNotThrow(() -> AuroraScenario.getAllowedEngines(rdsClient, dbParameterGroupFamily)); System.out.println("8. Create an Aurora DB cluster database"); - String arnClusterVal = AuroraScenario.createDBCluster(rdsClient, dbClusterGroupName, dbName, dbInstanceClusterIdentifier, user.getUsername(), user.getPassword()) ; - System.out.println("The ARN of the cluster is "+arnClusterVal); - System.out.println("9. Wait for DB instance to be ready" ); - assertDoesNotThrow(() ->AuroraScenario.waitForInstanceReady(rdsClient, dbInstanceClusterIdentifier)); + String arnClusterVal = AuroraScenario.createDBCluster(rdsClient, dbClusterGroupName, dbName, + dbInstanceClusterIdentifier, user.getUsername(), user.getPassword()); + System.out.println("The ARN of the cluster is " + arnClusterVal); + System.out.println("9. Wait for DB instance to be ready"); + assertDoesNotThrow(() -> AuroraScenario.waitForInstanceReady(rdsClient, dbInstanceClusterIdentifier)); System.out.println("10. Get a list of instance classes available for the selected engine"); String instanceClass = AuroraScenario.getListInstanceClasses(rdsClient); System.out.println("11. Create a database instance in the cluster."); - String clusterDBARN = AuroraScenario.createDBInstanceCluster(rdsClient, dbInstanceIdentifier, dbInstanceClusterIdentifier, instanceClass); - System.out.println("The ARN of the database is "+clusterDBARN); - System.out.println("12. Wait for DB instance to be ready" ); - assertDoesNotThrow(() ->AuroraScenario.waitDBInstanceReady(rdsClient, dbInstanceIdentifier)); + String clusterDBARN = AuroraScenario.createDBInstanceCluster(rdsClient, dbInstanceIdentifier, + dbInstanceClusterIdentifier, instanceClass); + System.out.println("The ARN of the database is " + clusterDBARN); + System.out.println("12. Wait for DB instance to be ready"); + assertDoesNotThrow(() -> AuroraScenario.waitDBInstanceReady(rdsClient, dbInstanceIdentifier)); System.out.println("13. Create a snapshot"); - assertDoesNotThrow(() ->AuroraScenario.createDBClusterSnapshot(rdsClient, dbInstanceClusterIdentifier, dbSnapshotIdentifier)); - System.out.println("14. Wait for DB snapshot to be ready" ); - assertDoesNotThrow(() ->AuroraScenario.waitForSnapshotReady(rdsClient, dbSnapshotIdentifier, dbInstanceClusterIdentifier)); - System.out.println("14. Delete the DB instance" ); - assertDoesNotThrow(() ->AuroraScenario.deleteDatabaseInstance(rdsClient, dbInstanceIdentifier)); + assertDoesNotThrow(() -> AuroraScenario.createDBClusterSnapshot(rdsClient, dbInstanceClusterIdentifier, + dbSnapshotIdentifier)); + System.out.println("14. Wait for DB snapshot to be ready"); + assertDoesNotThrow(() -> AuroraScenario.waitForSnapshotReady(rdsClient, dbSnapshotIdentifier, + dbInstanceClusterIdentifier)); + System.out.println("14. Delete the DB instance"); + assertDoesNotThrow(() -> AuroraScenario.deleteDatabaseInstance(rdsClient, dbInstanceIdentifier)); System.out.println("15. Delete the DB cluster"); assertDoesNotThrow(() -> AuroraScenario.deleteCluster(rdsClient, dbInstanceClusterIdentifier)); System.out.println("16. Delete the DB cluster group"); @@ -232,14 +250,14 @@ public void TestAuroraScenario() throws InterruptedException { private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/rds"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -280,10 +298,10 @@ class SecretValues { private String secretName; - public String getSecretName() { return secretName; } + public String getDbInstanceClusterIdentifier() { return dbInstanceClusterIdentifier; } @@ -349,7 +367,3 @@ public String getDbSnapshotIdentifierSc() { } } } - - - - diff --git a/javav2/example_code/redshift/src/main/java/com/example/redshift/ConnectToCluster.java b/javav2/example_code/redshift/src/main/java/com/example/redshift/ConnectToCluster.java index da4c68f3766..d1fa1e5a255 100644 --- a/javav2/example_code/redshift/src/main/java/com/example/redshift/ConnectToCluster.java +++ b/javav2/example_code/redshift/src/main/java/com/example/redshift/ConnectToCluster.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[ConnectToCluster.java demonstrates how to connect to an Amazon Redshift cluster using the JDBC API and AWS Secrets Manager.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Redshift ] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.redshift; // snippet-start:[firehose.java2.connect.import] @@ -23,20 +18,25 @@ // snippet-end:[firehose.java2.connect.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * If you have issues connecting, check your inbound rules that belong to the security group. + * If you have issues connecting, check your inbound rules that belong to the + * security group. * - * To run this example, create an Amazon Redshift cluster and then create a database named dev. - * Next, create a table named Work that contains the specific fields. For details, see the Creating the + * To run this example, create an Amazon Redshift cluster and then create a + * database named dev. + * Next, create a table named Work that contains the specific fields. For + * details, see the Creating the * Resource section in the following article: * * https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/CreatingSpringRedshiftRest * - * This example requires an AWS Secrets Manager secret that contains the database credentials. If you do not create a + * This example requires an AWS Secrets Manager secret that contains the + * database credentials. If you do not create a * secret, this example will not work. For details, see: * * https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_how-services-use-secrets_RS.html @@ -47,47 +47,49 @@ public class ConnectToCluster { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - secretName - The name of the AWS Secrets Manager secret that contains the database credentials"""; + Where: + secretName - The name of the AWS Secrets Manager secret that contains the database credentials"""; if (args.length != 1) { System.out.println(usage); System.exit(1); - } + } // Get the Amazon RDS credentials from AWS Secrets Manager. String secretName = args[0]; Gson gson = new Gson(); User user = gson.fromJson(String.valueOf(getSecretValues(secretName)), User.class); - connectCluster(user) ; + connectCluster(user); } + // Get the Amazon Redshift credentials from AWS Secrets Manager. private static String getSecretValues(String secretName) { SecretsManagerClient secretClient = getSecretClient(); GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); } + private static SecretsManagerClient getSecretClient() { Region region = Region.US_WEST_2; return SecretsManagerClient.builder() - .region(region) - .build(); + .region(region) + .build(); } // snippet-start:[firehose.java2.connect.main] public static void connectCluster(User user) { Connection conn = null; Statement stmt = null; - try{ - //Dynamically load driver at runtime. - //Redshift JDBC 4 driver: com.amazon.redshift.jdbc4.Driver + try { + // Dynamically load driver at runtime. + // Redshift JDBC 4 driver: com.amazon.redshift.jdbc4.Driver Class.forName("com.amazon.redshift.jdbc.Driver"); // Open a connection and define properties. @@ -96,11 +98,11 @@ public static void connectCluster(User user) { // Uncomment the following line if using a keystore. // props.setProperty("ssl", "true"); - String host = "jdbc:redshift://"+user.getHost()+":5439/dev" ; + String host = "jdbc:redshift://" + user.getHost() + ":5439/dev"; String userName = user.getUsername(); String password = user.getPassword(); - props.setProperty("user", userName ); - props.setProperty("password", password ); + props.setProperty("user", userName); + props.setProperty("password", password); conn = DriverManager.getConnection(host, props); // A simple query to retrieve data from the work table. @@ -110,13 +112,13 @@ public static void connectCluster(User user) { sql = "SELECT idwork, description FROM work;"; ResultSet rs = stmt.executeQuery(sql); - //Get the data from the result set. - while(rs.next()){ + // Get the data from the result set. + while (rs.next()) { // Retrieve two columns. String idWork = rs.getString("idwork"); String description = rs.getString("description"); - //Display values. + // Display values. System.out.println("Id work: " + idWork); System.out.println("Description: " + description); } @@ -125,22 +127,22 @@ public static void connectCluster(User user) { stmt.close(); conn.close(); - }catch(SQLException | ClassNotFoundException ex){ - //For convenience, handle all errors here. + } catch (SQLException | ClassNotFoundException ex) { + // For convenience, handle all errors here. ex.printStackTrace(); System.exit(1); - }finally{ - //Finally block to close resources. - try{ - if(stmt!=null) + } finally { + // Finally block to close resources. + try { + if (stmt != null) stmt.close(); - }catch(SQLException ex){ + } catch (SQLException ex) { System.exit(1); - }// nothing we can do - try{ - if(conn!=null) + } // nothing we can do + try { + if (conn != null) conn.close(); - }catch(SQLException ex){ + } catch (SQLException ex) { ex.printStackTrace(); System.exit(1); } diff --git a/javav2/example_code/redshift/src/main/java/com/example/redshift/CreateAndModifyCluster.java b/javav2/example_code/redshift/src/main/java/com/example/redshift/CreateAndModifyCluster.java index 91faf9b89d8..388927c7287 100644 --- a/javav2/example_code/redshift/src/main/java/com/example/redshift/CreateAndModifyCluster.java +++ b/javav2/example_code/redshift/src/main/java/com/example/redshift/CreateAndModifyCluster.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[CreateAndModifyCluster.java demonstrates how to create and modify an Amazon Redshift cluster.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Redshift] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.redshift; @@ -28,13 +23,15 @@ // snippet-end:[redshift.java2.create_cluster.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * This example requires an AWS Secrets Manager secret that contains the database credentials. If you do not create a + * This example requires an AWS Secrets Manager secret that contains the + * database credentials. If you do not create a * secret, this example will not work. For details, see: * * https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_how-services-use-secrets_RS.html @@ -46,12 +43,12 @@ public class CreateAndModifyCluster { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - clusterId - The id of the cluster to create.\s - secretName - The name of the AWS Secrets Manager secret that contains the database credentials"""; + Where: + clusterId - The id of the cluster to create.\s + secretName - The name of the AWS Secrets Manager secret that contains the database credentials"""; if (args.length != 3) { System.out.println(usage); @@ -64,10 +61,10 @@ public static void main(String[] args) { User user = gson.fromJson(String.valueOf(getSecretValues(secretName)), User.class); Region region = Region.US_WEST_2; RedshiftClient redshiftClient = RedshiftClient.builder() - .region(region) - .build(); + .region(region) + .build(); - createCluster(redshiftClient,clusterId, user.getMasterUsername(), user.getMasterUserPassword() ); + createCluster(redshiftClient, clusterId, user.getMasterUsername(), user.getMasterUserPassword()); waitForClusterReady(redshiftClient, clusterId); modifyCluster(redshiftClient, clusterId); redshiftClient.close(); @@ -76,44 +73,45 @@ public static void main(String[] args) { public static String getSecretValues(String secretName) { SecretsManagerClient secretClient = getSecretClient(); GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); } + private static SecretsManagerClient getSecretClient() { Region region = Region.US_WEST_2; return SecretsManagerClient.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); } // snippet-start:[redshift.java2.create_cluster.main] - public static void createCluster(RedshiftClient redshiftClient, String clusterId, String masterUsername, String masterUserPassword ) { + public static void createCluster(RedshiftClient redshiftClient, String clusterId, String masterUsername, + String masterUserPassword) { try { CreateClusterRequest clusterRequest = CreateClusterRequest.builder() - .clusterIdentifier(clusterId) - .masterUsername(masterUsername) // set the user name here - .masterUserPassword(masterUserPassword) // set the user password here - .nodeType("dc2.large") - .publiclyAccessible(true) - .numberOfNodes(2) - .build(); + .clusterIdentifier(clusterId) + .masterUsername(masterUsername) // set the user name here + .masterUserPassword(masterUserPassword) // set the user password here + .nodeType("dc2.large") + .publiclyAccessible(true) + .numberOfNodes(2) + .build(); - CreateClusterResponse clusterResponse = redshiftClient.createCluster(clusterRequest); - System.out.println("Created cluster " + clusterResponse.cluster().clusterIdentifier()); + CreateClusterResponse clusterResponse = redshiftClient.createCluster(clusterRequest); + System.out.println("Created cluster " + clusterResponse.cluster().clusterIdentifier()); - } catch (RedshiftException e) { + } catch (RedshiftException e) { - System.err.println(e.getMessage()); - System.exit(1); - } + System.err.println(e.getMessage()); + System.exit(1); + } } // snippet-end:[redshift.java2.create_cluster.main] - // Waits until the cluster is available public static void waitForClusterReady(RedshiftClient redshiftClient, String clusterId) { @@ -123,8 +121,8 @@ public static void waitForClusterReady(RedshiftClient redshiftClient, String clu try { DescribeClustersRequest clustersRequest = DescribeClustersRequest.builder() - .clusterIdentifier(clusterId) - .build(); + .clusterIdentifier(clusterId) + .build(); // Loop until the cluster is ready. while (!clusterReady) { @@ -133,33 +131,34 @@ public static void waitForClusterReady(RedshiftClient redshiftClient, String clu for (Cluster cluster : clusterList) { clusterReadyStr = cluster.clusterStatus(); if (clusterReadyStr.contains("available")) - clusterReady = true; + clusterReady = true; else { - System.out.print("."); + System.out.print("."); Thread.sleep(sleepTime * 1000); } } } - System.out.println("Cluster is available!"); + System.out.println("Cluster is available!"); - } catch (RedshiftException | InterruptedException e) { - System.err.println(e.getMessage()); - System.exit(1); + } catch (RedshiftException | InterruptedException e) { + System.err.println(e.getMessage()); + System.exit(1); + } } - } // snippet-start:[redshift.java2.mod_cluster.main] - public static void modifyCluster(RedshiftClient redshiftClient, String clusterId) { + public static void modifyCluster(RedshiftClient redshiftClient, String clusterId) { try { ModifyClusterRequest modifyClusterRequest = ModifyClusterRequest.builder() - .clusterIdentifier(clusterId) - .preferredMaintenanceWindow("wed:07:30-wed:08:00") - .build(); + .clusterIdentifier(clusterId) + .preferredMaintenanceWindow("wed:07:30-wed:08:00") + .build(); ModifyClusterResponse clusterResponse = redshiftClient.modifyCluster(modifyClusterRequest); - System.out.println("The modified cluster was successfully modified and has "+ clusterResponse.cluster().preferredMaintenanceWindow() +" as the maintenance window"); + System.out.println("The modified cluster was successfully modified and has " + + clusterResponse.cluster().preferredMaintenanceWindow() + " as the maintenance window"); } catch (RedshiftException e) { System.err.println(e.getMessage()); diff --git a/javav2/example_code/redshift/src/main/java/com/example/redshift/DeleteCluster.java b/javav2/example_code/redshift/src/main/java/com/example/redshift/DeleteCluster.java index faefd8da906..687c7f498d1 100644 --- a/javav2/example_code/redshift/src/main/java/com/example/redshift/DeleteCluster.java +++ b/javav2/example_code/redshift/src/main/java/com/example/redshift/DeleteCluster.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DeleteCluster.java demonstrates how to delete an Amazon Redshift cluster.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Redshift] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.redshift; @@ -19,7 +13,8 @@ // snippet-end:[redshift.java2.delete_cluster.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,12 +25,12 @@ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - clusterId - The id of the cluster to delete.\s - """; + Where: + clusterId - The id of the cluster to delete.\s + """; if (args.length != 1) { System.out.println(usage); @@ -45,8 +40,8 @@ public static void main(String[] args) { String clusterId = args[0]; Region region = Region.US_WEST_2; RedshiftClient redshiftClient = RedshiftClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteRedshiftCluster(redshiftClient, clusterId); redshiftClient.close(); @@ -55,9 +50,9 @@ public static void main(String[] args) { public static void deleteRedshiftCluster(RedshiftClient redshiftClient, String clusterId) { try { DeleteClusterRequest deleteClusterRequest = DeleteClusterRequest.builder() - .clusterIdentifier(clusterId) - .skipFinalClusterSnapshot(true) - .build(); + .clusterIdentifier(clusterId) + .skipFinalClusterSnapshot(true) + .build(); DeleteClusterResponse response = redshiftClient.deleteCluster(deleteClusterRequest); System.out.println("The status is " + response.cluster().clusterStatus()); diff --git a/javav2/example_code/redshift/src/main/java/com/example/redshift/DescribeClusters.java b/javav2/example_code/redshift/src/main/java/com/example/redshift/DescribeClusters.java index 35cc59de690..fcf9e9098e9 100644 --- a/javav2/example_code/redshift/src/main/java/com/example/redshift/DescribeClusters.java +++ b/javav2/example_code/redshift/src/main/java/com/example/redshift/DescribeClusters.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[DescribeClusters.java demonstrates how to describe Amazon Redshift clusters.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Redshift] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.redshift; @@ -20,7 +14,8 @@ // snippet-end:[redshift.java2.describe_cluster.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,8 +26,8 @@ public class DescribeClusters { public static void main(String[] args) { Region region = Region.US_WEST_2; RedshiftClient redshiftClient = RedshiftClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeRedshiftClusters(redshiftClient); redshiftClient.close(); diff --git a/javav2/example_code/redshift/src/main/java/com/example/redshift/FindReservedNodeOffer.java b/javav2/example_code/redshift/src/main/java/com/example/redshift/FindReservedNodeOffer.java index bf6e2b877df..a2058a124ab 100644 --- a/javav2/example_code/redshift/src/main/java/com/example/redshift/FindReservedNodeOffer.java +++ b/javav2/example_code/redshift/src/main/java/com/example/redshift/FindReservedNodeOffer.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[FindReservedNodeOffer.java demonstrates how to find additional Amazon Redshift nodes for purchase.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Redshift] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.redshift; @@ -18,13 +12,13 @@ import software.amazon.awssdk.services.redshift.model.DescribeReservedNodeOfferingsRequest; import software.amazon.awssdk.services.redshift.model.DescribeReservedNodeOfferingsResponse; import software.amazon.awssdk.services.redshift.model.ReservedNodeOffering; -import software.amazon.awssdk.services.redshift.model.RedshiftException ; +import software.amazon.awssdk.services.redshift.model.RedshiftException; import java.util.ArrayList; // snippet-end:[redshift.java2._nodes.import] - /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -39,8 +33,8 @@ public static void main(String[] args) { Region region = Region.US_WEST_2; RedshiftClient redshiftClient = RedshiftClient.builder() - .region(region) - .build(); + .region(region) + .build(); listReservedNodes(redshiftClient); findReservedNodeOffer(redshiftClient); @@ -64,7 +58,7 @@ public static void listReservedNodes(RedshiftClient redshiftClient) { public static void findReservedNodeOffer(RedshiftClient redshiftClient) { try { DescribeReservedNodeOfferingsRequest request = DescribeReservedNodeOfferingsRequest.builder() - .build(); + .build(); DescribeReservedNodeOfferingsResponse response = redshiftClient.describeReservedNodeOfferings(request); int count = 0; diff --git a/javav2/example_code/redshift/src/main/java/com/example/redshift/ListEvents.java b/javav2/example_code/redshift/src/main/java/com/example/redshift/ListEvents.java index 29c5b022f28..571eb6641e6 100644 --- a/javav2/example_code/redshift/src/main/java/com/example/redshift/ListEvents.java +++ b/javav2/example_code/redshift/src/main/java/com/example/redshift/ListEvents.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[ListEvents.java demonstrates how to list events for a given cluster.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Redshift] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.redshift; @@ -21,7 +16,8 @@ // snippet-end:[redshift.java2._events.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,13 +27,13 @@ public class ListEvents { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - clusterId - The id of the cluster.\s - eventSourceType - The event type (ie, cluster).\s - """; + Where: + clusterId - The id of the cluster.\s + eventSourceType - The event type (ie, cluster).\s + """; if (args.length != 2) { System.out.println(usage); @@ -48,8 +44,8 @@ public static void main(String[] args) { String eventSourceType = args[1]; Region region = Region.US_WEST_2; RedshiftClient redshiftClient = RedshiftClient.builder() - .region(region) - .build(); + .region(region) + .build(); listRedShiftEvents(redshiftClient, clusterId, eventSourceType); redshiftClient.close(); @@ -62,11 +58,11 @@ public static void listRedShiftEvents(RedshiftClient redshiftClient, String clus oneWeekAgo.setTime(oneWeeksAgoMilli); DescribeEventsRequest describeEventsRequest = DescribeEventsRequest.builder() - .sourceIdentifier(clusterId) - .sourceType(eventSourceType) - .startTime(oneWeekAgo.toInstant()) - .maxRecords(20) - .build(); + .sourceIdentifier(clusterId) + .sourceType(eventSourceType) + .startTime(oneWeekAgo.toInstant()) + .maxRecords(20) + .build(); DescribeEventsResponse eventsResponse = redshiftClient.describeEvents(describeEventsRequest); List events = eventsResponse.events(); diff --git a/javav2/example_code/redshift/src/main/java/com/example/redshift/User.java b/javav2/example_code/redshift/src/main/java/com/example/redshift/User.java index 4952adbfd73..60a634e5299 100644 --- a/javav2/example_code/redshift/src/main/java/com/example/redshift/User.java +++ b/javav2/example_code/redshift/src/main/java/com/example/redshift/User.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.redshift; public class User { diff --git a/javav2/example_code/redshift/src/main/java/com/example/redshiftdata/InsertData.java b/javav2/example_code/redshift/src/main/java/com/example/redshiftdata/InsertData.java index 7a05978ed02..940ac1718a6 100644 --- a/javav2/example_code/redshift/src/main/java/com/example/redshiftdata/InsertData.java +++ b/javav2/example_code/redshift/src/main/java/com/example/redshiftdata/InsertData.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[InsertData.java demonstrates how to insert data by using a RedshiftDataClient object and parameters for the SQL statement.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Redshift] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.redshiftdata; @@ -26,15 +20,16 @@ import java.util.UUID; // snippet-end:[redshift.java2.data_addrecord.import] - /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * Also, create a Redshift cluster with a table named blog with these string fields: + * Also, create a Redshift cluster with a table named blog with these string + * fields: * * 1. idblog * 2. date @@ -42,93 +37,94 @@ * 4. body * 5. author * - * For information, see https://docs.aws.amazon.com/redshift/latest/gsg/database-tasks.html. + * For information, see + * https://docs.aws.amazon.com/redshift/latest/gsg/database-tasks.html. */ // snippet-start:[redshift.java2.data_addrecord.main] public class InsertData { - public static void main(String [] args){ - String clusterId = "redshift-cluster-1"; - String database = "dev"; - String dbUser = "awsuser"; - AddRecord(clusterId, database, dbUser); - } - - public static void AddRecord( String clusterId, String database, String dbUser) { - - try { - RedshiftDataClient redshiftDataClient = getClient(); - UUID uuid = UUID.randomUUID(); - DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); - LocalDateTime now = LocalDateTime.now(); - String sDate1 = dtf.format(now); - Date date1 = new SimpleDateFormat("yyyy/MM/dd").parse(sDate1); - java.sql.Date date = new java.sql.Date( date1.getTime()); - - String title ="OCT 2023 Weather"; - String body ="OCT is suppose to be spooky"; - String author = "user"; - - // Use parameters to add a new record. - String sqlStatement = "INSERT INTO blog VALUES( :idblog , :date, :title, :body, :author );"; - - // Create the parameters. - List parameterList = new ArrayList<>() ; - SqlParameter ob1 = SqlParameter.builder() - .name("idblog") - .value(uuid.toString()) - .build(); - - SqlParameter ob2 = SqlParameter.builder() - .name("date") - .value(String.valueOf(date)) - .build(); - - SqlParameter ob3 = SqlParameter.builder() - .name("title") - .value(title) - .build(); - - SqlParameter ob4 = SqlParameter.builder() - .name("body") - .value(body) - .build(); - - SqlParameter ob5 = SqlParameter.builder() - .name("author") - .value(author) - .build(); - - parameterList.add(ob1); - parameterList.add(ob2); - parameterList.add(ob3); - parameterList.add(ob4); - parameterList.add(ob5); - - ExecuteStatementRequest statementRequest = ExecuteStatementRequest.builder() - .clusterIdentifier(clusterId) - .database(database) - .parameters(parameterList) - .dbUser(dbUser) - .sql(sqlStatement) - .build(); - - ExecuteStatementResponse response = redshiftDataClient.executeStatement(statementRequest); - System.out.println( "The id is "+response.id()); - - } catch (RedshiftDataException | ParseException e) { - System.err.println(e.getMessage()); - System.exit(1); + public static void main(String[] args) { + String clusterId = "redshift-cluster-1"; + String database = "dev"; + String dbUser = "awsuser"; + AddRecord(clusterId, database, dbUser); } - } - private static RedshiftDataClient getClient() { - Region region = Region.US_WEST_2; - RedshiftDataClient redshiftDataClient = RedshiftDataClient.builder() - .region(region) - .build(); + public static void AddRecord(String clusterId, String database, String dbUser) { + + try { + RedshiftDataClient redshiftDataClient = getClient(); + UUID uuid = UUID.randomUUID(); + DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); + LocalDateTime now = LocalDateTime.now(); + String sDate1 = dtf.format(now); + Date date1 = new SimpleDateFormat("yyyy/MM/dd").parse(sDate1); + java.sql.Date date = new java.sql.Date(date1.getTime()); + + String title = "OCT 2023 Weather"; + String body = "OCT is suppose to be spooky"; + String author = "user"; + + // Use parameters to add a new record. + String sqlStatement = "INSERT INTO blog VALUES( :idblog , :date, :title, :body, :author );"; + + // Create the parameters. + List parameterList = new ArrayList<>(); + SqlParameter ob1 = SqlParameter.builder() + .name("idblog") + .value(uuid.toString()) + .build(); + + SqlParameter ob2 = SqlParameter.builder() + .name("date") + .value(String.valueOf(date)) + .build(); + + SqlParameter ob3 = SqlParameter.builder() + .name("title") + .value(title) + .build(); + + SqlParameter ob4 = SqlParameter.builder() + .name("body") + .value(body) + .build(); + + SqlParameter ob5 = SqlParameter.builder() + .name("author") + .value(author) + .build(); + + parameterList.add(ob1); + parameterList.add(ob2); + parameterList.add(ob3); + parameterList.add(ob4); + parameterList.add(ob5); + + ExecuteStatementRequest statementRequest = ExecuteStatementRequest.builder() + .clusterIdentifier(clusterId) + .database(database) + .parameters(parameterList) + .dbUser(dbUser) + .sql(sqlStatement) + .build(); + + ExecuteStatementResponse response = redshiftDataClient.executeStatement(statementRequest); + System.out.println("The id is " + response.id()); + + } catch (RedshiftDataException | ParseException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } - return redshiftDataClient; - } + private static RedshiftDataClient getClient() { + Region region = Region.US_WEST_2; + RedshiftDataClient redshiftDataClient = RedshiftDataClient.builder() + .region(region) + .build(); + + return redshiftDataClient; + } } // snippet-end:[redshift.java2.data_addrecord.main] \ No newline at end of file diff --git a/javav2/example_code/redshift/src/main/java/com/example/redshiftdata/ListDatabases.java b/javav2/example_code/redshift/src/main/java/com/example/redshiftdata/ListDatabases.java index c93fe546553..34801f546c5 100644 --- a/javav2/example_code/redshift/src/main/java/com/example/redshiftdata/ListDatabases.java +++ b/javav2/example_code/redshift/src/main/java/com/example/redshiftdata/ListDatabases.java @@ -1,10 +1,5 @@ - //snippet-sourcedescription:[ListDatabases.java demonstrates how to list databases and tables that are part of a cluster by using a RedshiftDataClient object.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Redshift] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.redshiftdata; @@ -18,26 +13,27 @@ import software.amazon.awssdk.services.redshiftdata.model.TableMember; import java.util.List; - /** - * Before running this Java V2 code example, set up your development environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ public class ListDatabases { public static void main(String[] args) { final String usage = """ - Usage: - ListDatabases \s + Usage: + ListDatabases \s - Where: - database - The name of the database (for example, dev)\s - dbUser - The master user name\s - clusterId - The id of the Redshift cluster (for example, redshift-cluster)\s - """; + Where: + database - The name of the database (for example, dev)\s + dbUser - The master user name\s + clusterId - The id of the Redshift cluster (for example, redshift-cluster)\s + """; if (args.length != 3) { System.out.println(usage); @@ -49,26 +45,27 @@ public static void main(String[] args) { String clusterId = args[2]; Region region = Region.US_WEST_2; RedshiftDataClient redshiftDataClient = RedshiftDataClient.builder() - .region(region) - .build(); + .region(region) + .build(); - listAllDatabases(redshiftDataClient,clusterId, dbUser, database) ; - listAllTables(redshiftDataClient,clusterId, dbUser, database); + listAllDatabases(redshiftDataClient, clusterId, dbUser, database); + listAllTables(redshiftDataClient, clusterId, dbUser, database); redshiftDataClient.close(); } - public static void listAllDatabases(RedshiftDataClient redshiftDataClient,String clusterId, String dbUser, String database) { + public static void listAllDatabases(RedshiftDataClient redshiftDataClient, String clusterId, String dbUser, + String database) { try { ListDatabasesRequest databasesRequest = ListDatabasesRequest.builder() - .clusterIdentifier(clusterId) - .dbUser(dbUser) - .database(database) - .build(); + .clusterIdentifier(clusterId) + .dbUser(dbUser) + .database(database) + .build(); ListDatabasesResponse databasesResponse = redshiftDataClient.listDatabases(databasesRequest); List databases = databasesResponse.databases(); - for (String dbName: databases) { - System.out.println("The database name is : "+dbName); + for (String dbName : databases) { + System.out.println("The database name is : " + dbName); } } catch (RedshiftDataException e) { @@ -77,19 +74,20 @@ public static void listAllDatabases(RedshiftDataClient redshiftDataClient,String } } - public static void listAllTables(RedshiftDataClient redshiftDataClient,String clusterId, String dbUser, String database){ + public static void listAllTables(RedshiftDataClient redshiftDataClient, String clusterId, String dbUser, + String database) { try { ListTablesRequest tablesRequest = ListTablesRequest.builder() - .clusterIdentifier(clusterId) - .database(database) - .dbUser(dbUser) - .build(); + .clusterIdentifier(clusterId) + .database(database) + .dbUser(dbUser) + .build(); ListTablesResponse tablesResponse = redshiftDataClient.listTables(tablesRequest); List tables = tablesResponse.tables(); - for (TableMember table: tables) { - System.out.println("The table name is : "+table.name()); + for (TableMember table : tables) { + System.out.println("The table name is : " + table.name()); } } catch (RedshiftDataException e) { diff --git a/javav2/example_code/redshift/src/main/java/com/example/redshiftdata/RetrieveData.java b/javav2/example_code/redshift/src/main/java/com/example/redshiftdata/RetrieveData.java index fc1755818d4..1cf689ad036 100644 --- a/javav2/example_code/redshift/src/main/java/com/example/redshiftdata/RetrieveData.java +++ b/javav2/example_code/redshift/src/main/java/com/example/redshiftdata/RetrieveData.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[RetrieveData.java demonstrates how to query data and check the results by using a RedshiftDataClient object.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Redshift] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.redshiftdata; @@ -22,9 +16,9 @@ import software.amazon.awssdk.services.redshiftdata.model.DescribeStatementRequest; import java.util.List; - /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -36,15 +30,15 @@ public static void main(String[] args) { final String usage = """ - Usage: - RetrieveData \s + Usage: + RetrieveData \s - Where: - database - The name of the database (for example, dev)\s - dbUser - The master user name\s - sqlStatement - The sql statement to use (for example, select * from information_schema.tables;)\s - clusterId - The id of the Redshift cluster (for example, redshift-cluster)\s - """; + Where: + database - The name of the database (for example, dev)\s + dbUser - The master user name\s + sqlStatement - The sql statement to use (for example, select * from information_schema.tables;)\s + clusterId - The id of the Redshift cluster (for example, redshift-cluster)\s + """; if (args.length != 4) { System.out.println(usage); @@ -58,32 +52,32 @@ public static void main(String[] args) { Region region = Region.US_WEST_2; RedshiftDataClient redshiftDataClient = RedshiftDataClient.builder() - .region(region) - .build(); + .region(region) + .build(); String id = performSQLStatement(redshiftDataClient, database, dbUser, sqlStatement, clusterId); - System.out.println("The identifier of the statement is "+id); - checkStatement(redshiftDataClient,id ); + System.out.println("The identifier of the statement is " + id); + checkStatement(redshiftDataClient, id); getResults(redshiftDataClient, id); redshiftDataClient.close(); } - public static void checkStatement(RedshiftDataClient redshiftDataClient,String sqlId ) { + public static void checkStatement(RedshiftDataClient redshiftDataClient, String sqlId) { try { DescribeStatementRequest statementRequest = DescribeStatementRequest.builder() - .id(sqlId) - .build() ; + .id(sqlId) + .build(); String status; while (true) { DescribeStatementResponse response = redshiftDataClient.describeStatement(statementRequest); status = response.statusAsString(); - System.out.println("..."+status); + System.out.println("..." + status); if (status.compareTo("FINISHED") == 0) { break; } - Thread.sleep(1000); + Thread.sleep(1000); } System.out.println("The statement is finished!"); @@ -95,18 +89,18 @@ public static void checkStatement(RedshiftDataClient redshiftDataClient,String s } public static String performSQLStatement(RedshiftDataClient redshiftDataClient, - String database, - String dbUser, - String sqlStatement, - String clusterId) { + String database, + String dbUser, + String sqlStatement, + String clusterId) { try { ExecuteStatementRequest statementRequest = ExecuteStatementRequest.builder() - .clusterIdentifier(clusterId) - .database(database) - .dbUser(dbUser) - .sql(sqlStatement) - .build(); + .clusterIdentifier(clusterId) + .database(database) + .dbUser(dbUser) + .sql(sqlStatement) + .build(); ExecuteStatementResponse response = redshiftDataClient.executeStatement(statementRequest); return response.id(); diff --git a/javav2/example_code/redshift/src/main/java/com/example/redshiftdata/RetrieveDataServerless.java b/javav2/example_code/redshift/src/main/java/com/example/redshiftdata/RetrieveDataServerless.java index 9a76d83e9d8..ec7b6fb7711 100644 --- a/javav2/example_code/redshift/src/main/java/com/example/redshiftdata/RetrieveDataServerless.java +++ b/javav2/example_code/redshift/src/main/java/com/example/redshiftdata/RetrieveDataServerless.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[RetrieveData.java demonstrates how to query data and check the results by using a RedshiftDataClient object.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon Redshift] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.redshiftdata; @@ -21,59 +16,61 @@ import java.util.List; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * In addition, set up a serverless version by following this documentation topic: + * In addition, set up a serverless version by following this documentation + * topic: * - * https://docs.aws.amazon.com/redshift/latest/mgmt/serverless-getting-started.html + * https://docs.aws.amazon.com/redshift/latest/mgmt/serverless-getting-started.html */ public class RetrieveDataServerless { public static void main(String[] args) { final String usage = """ - Usage: - RetrieveData \s + Usage: + RetrieveData \s - Where: - database - The name of the database (for example, sample_data_dev).\s - sqlStatement - The sql statement to use.\s - """; + Where: + database - The name of the database (for example, sample_data_dev).\s + sqlStatement - The sql statement to use.\s + """; if (args.length != 2) { System.out.println(usage); System.exit(1); } - String database = "sample_data_dev" ; - String sqlStatement = "Select * from tickit.sales" ; + String database = "sample_data_dev"; + String sqlStatement = "Select * from tickit.sales"; Region region = Region.US_WEST_2; RedshiftDataClient redshiftDataClient = RedshiftDataClient.builder() - .region(region) - .build(); + .region(region) + .build(); String id = performSQLStatement(redshiftDataClient, database, sqlStatement); - System.out.println("The identifier of the statement is "+id); - checkStatement(redshiftDataClient,id ); + System.out.println("The identifier of the statement is " + id); + checkStatement(redshiftDataClient, id); getResults(redshiftDataClient, id); redshiftDataClient.close(); } - public static void checkStatement(RedshiftDataClient redshiftDataClient,String sqlId ) { + public static void checkStatement(RedshiftDataClient redshiftDataClient, String sqlId) { try { DescribeStatementRequest statementRequest = DescribeStatementRequest.builder() - .id(sqlId) - .build() ; + .id(sqlId) + .build(); // Wait until the sql statement processing is finished. String status; while (true) { DescribeStatementResponse response = redshiftDataClient.describeStatement(statementRequest); status = response.statusAsString(); - System.out.println("..."+status); + System.out.println("..." + status); if (status.compareTo("FINISHED") == 0) { break; @@ -90,14 +87,14 @@ public static void checkStatement(RedshiftDataClient redshiftDataClient,String s } public static String performSQLStatement(RedshiftDataClient redshiftDataClient, - String database, - String sqlStatement) { + String database, + String sqlStatement) { try { ExecuteStatementRequest statementRequest = ExecuteStatementRequest.builder() - .database(database) - .sql(sqlStatement) - .build(); + .database(database) + .sql(sqlStatement) + .build(); ExecuteStatementResponse response = redshiftDataClient.executeStatement(statementRequest); return response.id(); @@ -112,13 +109,13 @@ public static String performSQLStatement(RedshiftDataClient redshiftDataClient, public static void getResults(RedshiftDataClient redshiftDataClient, String statementId) { try { GetStatementResultRequest resultRequest = GetStatementResultRequest.builder() - .id(statementId) - .build(); + .id(statementId) + .build(); GetStatementResultResponse response = redshiftDataClient.getStatementResult(resultRequest); List> dataList = response.records(); - for (List list: dataList) { - for (Object myField:list) { + for (List list : dataList) { + for (Object myField : list) { Field field = (Field) myField; String value = field.stringValue(); if (value != null) diff --git a/javav2/example_code/redshift/src/test/java/AmazonRedshiftTest.java b/javav2/example_code/redshift/src/test/java/AmazonRedshiftTest.java index 918813d8b04..81ef8c1f572 100644 --- a/javav2/example_code/redshift/src/test/java/AmazonRedshiftTest.java +++ b/javav2/example_code/redshift/src/test/java/AmazonRedshiftTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.redshift.*; import com.google.gson.Gson; @@ -32,9 +30,9 @@ public class AmazonRedshiftTest { @BeforeAll public static void setUp() throws IOException { redshiftClient = RedshiftClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); Random rand = new Random(); int randomNum = rand.nextInt((10000 - 1) + 1) + 1; @@ -43,39 +41,44 @@ public static void setUp() throws IOException { Gson gson = new Gson(); String json = getSecretValues(); SecretValues values = gson.fromJson(json, SecretValues.class); - clusterId = values.getClusterId() +randomNum; + clusterId = values.getClusterId() + randomNum; secretName = values.getSecretName(); eventSourceType = values.getEventSourceType(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - try (InputStream input = AmazonRedshiftTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - // Populate the data members required for all tests. - prop.load(input); - clusterId = prop.getProperty("clusterId")+randomNum; - masterUsername = prop.getProperty("masterUsername"); - masterUserPassword = prop.getProperty("masterUserPassword"); - eventSourceType = prop.getProperty("eventSourceType"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * try (InputStream input = + * AmazonRedshiftTest.class.getClassLoader().getResourceAsStream( + * "config.properties")) { + * Properties prop = new Properties(); + * + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * // Populate the data members required for all tests. + * prop.load(input); + * clusterId = prop.getProperty("clusterId")+randomNum; + * masterUsername = prop.getProperty("masterUsername"); + * masterUserPassword = prop.getProperty("masterUserPassword"); + * eventSourceType = prop.getProperty("eventSourceType"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } + @Test @Tag("IntegrationTest") @Order(1) public void CreateCluster() { Gson gson = new Gson(); User user = gson.fromJson(String.valueOf(CreateAndModifyCluster.getSecretValues(secretName)), User.class); - assertDoesNotThrow(() ->CreateAndModifyCluster.createCluster(redshiftClient, clusterId, user.getMasterUsername(), user.getMasterUserPassword())); + assertDoesNotThrow(() -> CreateAndModifyCluster.createCluster(redshiftClient, clusterId, + user.getMasterUsername(), user.getMasterUserPassword())); System.out.println("Test 1 passed"); } @@ -83,7 +86,7 @@ public void CreateCluster() { @Tag("IntegrationTest") @Order(2) public void WaitForClusterReady() { - assertDoesNotThrow(() ->CreateAndModifyCluster.waitForClusterReady(redshiftClient, clusterId)); + assertDoesNotThrow(() -> CreateAndModifyCluster.waitForClusterReady(redshiftClient, clusterId)); System.out.println("Test 2 passed"); } @@ -91,7 +94,7 @@ public void WaitForClusterReady() { @Tag("IntegrationTest") @Order(3) public void ModifyClusterReady() { - assertDoesNotThrow(() ->CreateAndModifyCluster.modifyCluster(redshiftClient, clusterId)); + assertDoesNotThrow(() -> CreateAndModifyCluster.modifyCluster(redshiftClient, clusterId)); System.out.println("Test 3 passed"); } @@ -99,7 +102,7 @@ public void ModifyClusterReady() { @Tag("IntegrationTest") @Order(4) public void DescribeClusters() { - assertDoesNotThrow(() ->DescribeClusters.describeRedshiftClusters(redshiftClient)); + assertDoesNotThrow(() -> DescribeClusters.describeRedshiftClusters(redshiftClient)); System.out.println("Test 4 passed"); } @@ -107,8 +110,8 @@ public void DescribeClusters() { @Tag("IntegrationTest") @Order(5) public void FindReservedNodeOffer() { - assertDoesNotThrow(() ->FindReservedNodeOffer.listReservedNodes(redshiftClient)); - assertDoesNotThrow(() ->FindReservedNodeOffer.findReservedNodeOffer(redshiftClient)); + assertDoesNotThrow(() -> FindReservedNodeOffer.listReservedNodes(redshiftClient)); + assertDoesNotThrow(() -> FindReservedNodeOffer.findReservedNodeOffer(redshiftClient)); System.out.println("Test 5 passed"); } @@ -116,7 +119,7 @@ public void FindReservedNodeOffer() { @Tag("IntegrationTest") @Order(6) public void ListEvents() { - assertDoesNotThrow(() ->ListEvents.listRedShiftEvents(redshiftClient, clusterId, eventSourceType)); + assertDoesNotThrow(() -> ListEvents.listRedShiftEvents(redshiftClient, clusterId, eventSourceType)); System.out.println("Test 6 passed"); } @@ -126,19 +129,20 @@ public void ListEvents() { public void DeleteCluster() throws InterruptedException { System.out.println("Wait 20 mins for the resource to become available"); TimeUnit.MINUTES.sleep(20); - assertDoesNotThrow(() ->DeleteCluster.deleteRedshiftCluster(redshiftClient, clusterId)); + assertDoesNotThrow(() -> DeleteCluster.deleteRedshiftCluster(redshiftClient, clusterId)); System.out.println("Test 7 passed"); } + private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/red"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -164,4 +168,3 @@ public String getEventSourceType() { } } } - diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/AddFacesToCollection.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/AddFacesToCollection.java index 8c62b6da957..cedd0758be9 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/AddFacesToCollection.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/AddFacesToCollection.java @@ -1,10 +1,5 @@ -// snippet-sourcedescription:[AddFacesToCollection.java demonstrates how to add faces to an Amazon Rekognition collection.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Rekognition] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rekognition; @@ -29,7 +24,8 @@ // snippet-end:[rekognition.java2.add_faces_collection.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -40,12 +36,12 @@ public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - collectionName - The name of the collection. - sourceImage - The path to the image (for example, C:\\AWS\\pic1.png).\s - """; + Where: + collectionName - The name of the collection. + sourceImage - The path to the image (for example, C:\\AWS\\pic1.png).\s + """; if (args.length != 2) { System.out.println(usage); @@ -56,8 +52,8 @@ public static void main(String[] args) { String sourceImage = args[1]; Region region = Region.US_EAST_1; RekognitionClient rekClient = RekognitionClient.builder() - .region(region) - .build(); + .region(region) + .build(); addToCollection(rekClient, collectionId, sourceImage); rekClient.close(); @@ -68,16 +64,16 @@ public static void addToCollection(RekognitionClient rekClient, String collectio InputStream sourceStream = new FileInputStream(sourceImage); SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream); Image souImage = Image.builder() - .bytes(sourceBytes) - .build(); + .bytes(sourceBytes) + .build(); IndexFacesRequest facesRequest = IndexFacesRequest.builder() - .collectionId(collectionId) - .image(souImage) - .maxFaces(1) - .qualityFilter(QualityFilter.AUTO) - .detectionAttributes(Attribute.DEFAULT) - .build(); + .collectionId(collectionId) + .image(souImage) + .maxFaces(1) + .qualityFilter(QualityFilter.AUTO) + .detectionAttributes(Attribute.DEFAULT) + .build(); IndexFacesResponse facesResponse = rekClient.indexFaces(facesRequest); System.out.println("Results for the image"); @@ -104,4 +100,4 @@ public static void addToCollection(RekognitionClient rekClient, String collectio } } } - // snippet-end:[rekognition.java2.add_faces_collection.main] +// snippet-end:[rekognition.java2.add_faces_collection.main] diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CelebrityInfo.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CelebrityInfo.java index a5802dd30d5..5b8d80c7e1c 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CelebrityInfo.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CelebrityInfo.java @@ -1,10 +1,5 @@ -// snippet-sourcedescription:[CelebrityInfo.java demonstrates how to get information about a detected celebrity.] -//snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Rekognition] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rekognition; @@ -18,7 +13,8 @@ // snippet-end:[rekognition.java2.celebrityInfo.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,11 +24,11 @@ public class CelebrityInfo { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - id - The id value of the celebrity. You can use the RecognizeCelebrities example to get the ID value.\s - """; + Where: + id - The id value of the celebrity. You can use the RecognizeCelebrities example to get the ID value.\s + """; if (args.length != 1) { System.out.println(usage); @@ -42,8 +38,8 @@ public static void main(String[] args) { String id = args[0]; Region region = Region.US_EAST_1; RekognitionClient rekClient = RekognitionClient.builder() - .region(region) - .build(); + .region(region) + .build(); getCelebrityInfo(rekClient, id); rekClient.close(); @@ -52,8 +48,8 @@ public static void main(String[] args) { public static void getCelebrityInfo(RekognitionClient rekClient, String id) { try { GetCelebrityInfoRequest info = GetCelebrityInfoRequest.builder() - .id(id) - .build(); + .id(id) + .build(); GetCelebrityInfoResponse response = rekClient.getCelebrityInfo(info); System.out.println("celebrity name: " + response.name()); diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CompareFaces.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CompareFaces.java index b017a204736..b2128f3ed9a 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CompareFaces.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CompareFaces.java @@ -1,10 +1,5 @@ -// snippet-sourcedescription:[CompareFaces.java demonstrates how to compare 2 faces.] -//snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Rekognition] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rekognition; @@ -27,7 +22,8 @@ // snippet-end:[rekognition.java2.compare_faces.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -37,12 +33,12 @@ public class CompareFaces { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - pathSource - The path to the source image (for example, C:\\AWS\\pic1.png).\s - pathTarget - The path to the target image (for example, C:\\AWS\\pic2.png).\s - """; + Where: + pathSource - The path to the source image (for example, C:\\AWS\\pic1.png).\s + pathTarget - The path to the target image (for example, C:\\AWS\\pic2.png).\s + """; if (args.length != 2) { System.out.println(usage); @@ -54,14 +50,15 @@ public static void main(String[] args) { String targetImage = args[1]; Region region = Region.US_EAST_1; RekognitionClient rekClient = RekognitionClient.builder() - .region(region) - .build(); + .region(region) + .build(); compareTwoFaces(rekClient, similarityThreshold, sourceImage, targetImage); rekClient.close(); } - public static void compareTwoFaces(RekognitionClient rekClient, Float similarityThreshold, String sourceImage, String targetImage) { + public static void compareTwoFaces(RekognitionClient rekClient, Float similarityThreshold, String sourceImage, + String targetImage) { try { InputStream sourceStream = new FileInputStream(sourceImage); InputStream tarStream = new FileInputStream(targetImage); @@ -70,18 +67,18 @@ public static void compareTwoFaces(RekognitionClient rekClient, Float similarity // Create an Image object for the source image. Image souImage = Image.builder() - .bytes(sourceBytes) - .build(); + .bytes(sourceBytes) + .build(); Image tarImage = Image.builder() - .bytes(targetBytes) - .build(); + .bytes(targetBytes) + .build(); CompareFacesRequest facesRequest = CompareFacesRequest.builder() - .sourceImage(souImage) - .targetImage(tarImage) - .similarityThreshold(similarityThreshold) - .build(); + .sourceImage(souImage) + .targetImage(tarImage) + .similarityThreshold(similarityThreshold) + .build(); // Compare the two images. CompareFacesResponse compareFacesResult = rekClient.compareFaces(facesRequest); @@ -90,9 +87,9 @@ public static void compareTwoFaces(RekognitionClient rekClient, Float similarity ComparedFace face = match.face(); BoundingBox position = face.boundingBox(); System.out.println("Face at " + position.left().toString() - + " " + position.top() - + " matches with " + face.confidence().toString() - + "% confidence."); + + " " + position.top() + + " matches with " + face.confidence().toString() + + "% confidence."); } List uncompared = compareFacesResult.unmatchedFaces(); @@ -106,4 +103,4 @@ public static void compareTwoFaces(RekognitionClient rekClient, Float similarity } } } - // snippet-end:[rekognition.java2.compare_faces.main] +// snippet-end:[rekognition.java2.compare_faces.main] diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateCollection.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateCollection.java index 7808d7a5adc..4e4b588a2c0 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateCollection.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateCollection.java @@ -1,10 +1,5 @@ -// snippet-sourcedescription:[CreateCollection.java demonstrates how to create an Amazon Rekognition collection.] -//snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Rekognition] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rekognition; @@ -18,7 +13,8 @@ // snippet-end:[rekognition.java2.create_collection.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,11 +24,11 @@ public class CreateCollection { public static void main(String[] args) { final String usage = """ - Usage: \s + Usage: \s - Where: - collectionName - The name of the collection.\s - """; + Where: + collectionName - The name of the collection.\s + """; if (args.length != 1) { System.out.println(usage); @@ -42,8 +38,8 @@ public static void main(String[] args) { String collectionId = args[0]; Region region = Region.US_EAST_1; RekognitionClient rekClient = RekognitionClient.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.println("Creating collection: " + collectionId); createMyCollection(rekClient, collectionId); @@ -53,8 +49,8 @@ public static void main(String[] args) { public static void createMyCollection(RekognitionClient rekClient, String collectionId) { try { CreateCollectionRequest collectionRequest = CreateCollectionRequest.builder() - .collectionId(collectionId) - .build(); + .collectionId(collectionId) + .build(); CreateCollectionResponse collectionResponse = rekClient.createCollection(collectionRequest); System.out.println("CollectionArn: " + collectionResponse.collectionArn()); diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateStreamProcessor.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateStreamProcessor.java index 7c4f2aff9e8..e254ef636a7 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateStreamProcessor.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateStreamProcessor.java @@ -1,11 +1,5 @@ -// snippet-sourcedescription:[CreateStreamProcessor.java demonstrates how to create an Amazon Rekognition stream processor that you can use to detect and recognize faces in a streaming video..] -//snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Rekognition] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rekognition; @@ -31,144 +25,150 @@ // snippet-end:[rekognition.java2.create_streamprocessor.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateStreamProcessor { - public static void main(String[] args) { - final String usage = """ - - Usage: - - Where: - role - The ARN of the AWS Identity and Access Management (IAM) role to use. \s - kinInputStream - The ARN of the Kinesis video stream.\s - kinOutputStream - The ARN of the Kinesis data stream.\s - collectionName - The name of the collection to use that contains content. \s - StreamProcessorName - The name of the Stream Processor. \s - """; - - if (args.length != 5) { - System.out.println(usage); - System.exit(1); + public static void main(String[] args) { + final String usage = """ + + Usage: + + Where: + role - The ARN of the AWS Identity and Access Management (IAM) role to use. \s + kinInputStream - The ARN of the Kinesis video stream.\s + kinOutputStream - The ARN of the Kinesis data stream.\s + collectionName - The name of the collection to use that contains content. \s + StreamProcessorName - The name of the Stream Processor. \s + """; + + if (args.length != 5) { + System.out.println(usage); + System.exit(1); + } + + String role = args[0]; + String kinInputStream = args[1]; + String kinOutputStream = args[2]; + String collectionName = args[3]; + String streamProcessorName = args[4]; + + Region region = Region.US_EAST_1; + RekognitionClient rekClient = RekognitionClient.builder() + .region(region) + .build(); + + processCollection(rekClient, streamProcessorName, kinInputStream, kinOutputStream, collectionName, + role); + startSpecificStreamProcessor(rekClient, streamProcessorName); + listStreamProcessors(rekClient); + describeStreamProcessor(rekClient, streamProcessorName); + deleteSpecificStreamProcessor(rekClient, streamProcessorName); } - String role = args[0]; - String kinInputStream = args[1]; - String kinOutputStream = args[2]; - String collectionName = args[3]; - String streamProcessorName = args[4]; - - Region region = Region.US_EAST_1; - RekognitionClient rekClient = RekognitionClient.builder() - .region(region) - .build(); - - processCollection(rekClient, streamProcessorName, kinInputStream, kinOutputStream, collectionName, role); - startSpecificStreamProcessor(rekClient, streamProcessorName); - listStreamProcessors(rekClient); - describeStreamProcessor(rekClient, streamProcessorName); - deleteSpecificStreamProcessor(rekClient, streamProcessorName); - } - - public static void listStreamProcessors(RekognitionClient rekClient) { - ListStreamProcessorsRequest request = ListStreamProcessorsRequest.builder() - .maxResults(15) - .build(); - - ListStreamProcessorsResponse listStreamProcessorsResult = rekClient.listStreamProcessors(request); - for (StreamProcessor streamProcessor : listStreamProcessorsResult.streamProcessors()) { - System.out.println("StreamProcessor name - " + streamProcessor.name()); - System.out.println("Status - " + streamProcessor.status()); + public static void listStreamProcessors(RekognitionClient rekClient) { + ListStreamProcessorsRequest request = ListStreamProcessorsRequest.builder() + .maxResults(15) + .build(); + + ListStreamProcessorsResponse listStreamProcessorsResult = rekClient.listStreamProcessors(request); + for (StreamProcessor streamProcessor : listStreamProcessorsResult.streamProcessors()) { + System.out.println("StreamProcessor name - " + streamProcessor.name()); + System.out.println("Status - " + streamProcessor.status()); + } } - } - - private static void describeStreamProcessor(RekognitionClient rekClient, String StreamProcessorName) { - DescribeStreamProcessorRequest streamProcessorRequest = DescribeStreamProcessorRequest.builder() - .name(StreamProcessorName) - .build(); - - DescribeStreamProcessorResponse describeStreamProcessorResult = rekClient.describeStreamProcessor(streamProcessorRequest); - System.out.println("Arn - " + describeStreamProcessorResult.streamProcessorArn()); - System.out.println("Input kinesisVideo stream - " - + describeStreamProcessorResult.input().kinesisVideoStream().arn()); - System.out.println("Output kinesisData stream - " - + describeStreamProcessorResult.output().kinesisDataStream().arn()); - System.out.println("RoleArn - " + describeStreamProcessorResult.roleArn()); - System.out.println( - "CollectionId - " + describeStreamProcessorResult.settings().faceSearch().collectionId()); - System.out.println("Status - " + describeStreamProcessorResult.status()); - System.out.println("Status message - " + describeStreamProcessorResult.statusMessage()); - System.out.println("Creation timestamp - " + describeStreamProcessorResult.creationTimestamp()); - System.out.println("Last update timestamp - " + describeStreamProcessorResult.lastUpdateTimestamp()); - } - - private static void startSpecificStreamProcessor(RekognitionClient rekClient, String StreamProcessorName) { - try { - StartStreamProcessorRequest streamProcessorRequest = StartStreamProcessorRequest.builder() - .name(StreamProcessorName) - .build(); - - rekClient.startStreamProcessor(streamProcessorRequest); - System.out.println("Stream Processor " + StreamProcessorName + " started."); - - } catch (RekognitionException e) { - System.out.println(e.getMessage()); - System.exit(1); + + private static void describeStreamProcessor(RekognitionClient rekClient, String StreamProcessorName) { + DescribeStreamProcessorRequest streamProcessorRequest = DescribeStreamProcessorRequest.builder() + .name(StreamProcessorName) + .build(); + + DescribeStreamProcessorResponse describeStreamProcessorResult = rekClient + .describeStreamProcessor(streamProcessorRequest); + System.out.println("Arn - " + describeStreamProcessorResult.streamProcessorArn()); + System.out.println("Input kinesisVideo stream - " + + describeStreamProcessorResult.input().kinesisVideoStream().arn()); + System.out.println("Output kinesisData stream - " + + describeStreamProcessorResult.output().kinesisDataStream().arn()); + System.out.println("RoleArn - " + describeStreamProcessorResult.roleArn()); + System.out.println( + "CollectionId - " + + describeStreamProcessorResult.settings().faceSearch().collectionId()); + System.out.println("Status - " + describeStreamProcessorResult.status()); + System.out.println("Status message - " + describeStreamProcessorResult.statusMessage()); + System.out.println("Creation timestamp - " + describeStreamProcessorResult.creationTimestamp()); + System.out.println("Last update timestamp - " + describeStreamProcessorResult.lastUpdateTimestamp()); } - } - - private static void processCollection(RekognitionClient rekClient, String StreamProcessorName, String kinInputStream, String kinOutputStream, String collectionName, String role) { - try { - KinesisVideoStream videoStream = KinesisVideoStream.builder() - .arn(kinInputStream) - .build(); - - KinesisDataStream dataStream = KinesisDataStream.builder() - .arn(kinOutputStream) - .build(); - - StreamProcessorOutput processorOutput = StreamProcessorOutput.builder() - .kinesisDataStream(dataStream) - .build(); - - StreamProcessorInput processorInput = StreamProcessorInput.builder() - .kinesisVideoStream(videoStream) - .build(); - - FaceSearchSettings searchSettings = FaceSearchSettings.builder() - .faceMatchThreshold(75f) - .collectionId(collectionName) - .build(); - - StreamProcessorSettings processorSettings = StreamProcessorSettings.builder() - .faceSearch(searchSettings) - .build(); - - CreateStreamProcessorRequest processorRequest = CreateStreamProcessorRequest.builder() - .name(StreamProcessorName) - .input(processorInput) - .output(processorOutput) - .roleArn(role) - .settings(processorSettings) - .build(); - - CreateStreamProcessorResponse response = rekClient.createStreamProcessor(processorRequest); - System.out.println("The ARN for the newly create stream processor is " + response.streamProcessorArn()); - - } catch (RekognitionException e) { - System.out.println(e.getMessage()); - System.exit(1); + + private static void startSpecificStreamProcessor(RekognitionClient rekClient, String StreamProcessorName) { + try { + StartStreamProcessorRequest streamProcessorRequest = StartStreamProcessorRequest.builder() + .name(StreamProcessorName) + .build(); + + rekClient.startStreamProcessor(streamProcessorRequest); + System.out.println("Stream Processor " + StreamProcessorName + " started."); + + } catch (RekognitionException e) { + System.out.println(e.getMessage()); + System.exit(1); + } + } + + private static void processCollection(RekognitionClient rekClient, String StreamProcessorName, + String kinInputStream, String kinOutputStream, String collectionName, String role) { + try { + KinesisVideoStream videoStream = KinesisVideoStream.builder() + .arn(kinInputStream) + .build(); + + KinesisDataStream dataStream = KinesisDataStream.builder() + .arn(kinOutputStream) + .build(); + + StreamProcessorOutput processorOutput = StreamProcessorOutput.builder() + .kinesisDataStream(dataStream) + .build(); + + StreamProcessorInput processorInput = StreamProcessorInput.builder() + .kinesisVideoStream(videoStream) + .build(); + + FaceSearchSettings searchSettings = FaceSearchSettings.builder() + .faceMatchThreshold(75f) + .collectionId(collectionName) + .build(); + + StreamProcessorSettings processorSettings = StreamProcessorSettings.builder() + .faceSearch(searchSettings) + .build(); + + CreateStreamProcessorRequest processorRequest = CreateStreamProcessorRequest.builder() + .name(StreamProcessorName) + .input(processorInput) + .output(processorOutput) + .roleArn(role) + .settings(processorSettings) + .build(); + + CreateStreamProcessorResponse response = rekClient.createStreamProcessor(processorRequest); + System.out.println("The ARN for the newly create stream processor is " + + response.streamProcessorArn()); + + } catch (RekognitionException e) { + System.out.println(e.getMessage()); + System.exit(1); + } } - } - private static void deleteSpecificStreamProcessor(RekognitionClient rekClient, String StreamProcessorName) { - rekClient.stopStreamProcessor(a -> a.name(StreamProcessorName)); - rekClient.deleteStreamProcessor(a -> a.name(StreamProcessorName)); - System.out.println("Stream Processor " + StreamProcessorName + " deleted."); - } + private static void deleteSpecificStreamProcessor(RekognitionClient rekClient, String StreamProcessorName) { + rekClient.stopStreamProcessor(a -> a.name(StreamProcessorName)); + rekClient.deleteStreamProcessor(a -> a.name(StreamProcessorName)); + System.out.println("Stream Processor " + StreamProcessorName + " deleted."); + } } // snippet-end:[rekognition.java2.create_streamprocessor.main] diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DeleteCollection.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DeleteCollection.java index 89db606e315..21ce462ffb9 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DeleteCollection.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DeleteCollection.java @@ -1,11 +1,5 @@ -// snippet-sourcedescription:[DeleteCollection.java demonstrates how to delete an Amazon Rekognition collection.] -//snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Rekognition] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rekognition; @@ -19,7 +13,8 @@ // snippet-end:[rekognition.java2.delete_collection.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,11 +24,11 @@ public class DeleteCollection { public static void main(String[] args) { final String usage = """ - Usage: \s + Usage: \s - Where: - collectionId - The id of the collection to delete.\s - """; + Where: + collectionId - The id of the collection to delete.\s + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +38,8 @@ public static void main(String[] args) { String collectionId = args[0]; Region region = Region.US_EAST_1; RekognitionClient rekClient = RekognitionClient.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.println("Deleting collection: " + collectionId); deleteMyCollection(rekClient, collectionId); @@ -54,8 +49,8 @@ public static void main(String[] args) { public static void deleteMyCollection(RekognitionClient rekClient, String collectionId) { try { DeleteCollectionRequest deleteCollectionRequest = DeleteCollectionRequest.builder() - .collectionId(collectionId) - .build(); + .collectionId(collectionId) + .build(); DeleteCollectionResponse deleteCollectionResponse = rekClient.deleteCollection(deleteCollectionRequest); System.out.println(collectionId + ": " + deleteCollectionResponse.statusCode().toString()); @@ -67,4 +62,3 @@ public static void deleteMyCollection(RekognitionClient rekClient, String collec } } // snippet-end:[rekognition.java2.delete_collection.main] - diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DeleteFacesFromCollection.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DeleteFacesFromCollection.java index 51014e71e01..fb86da10ef8 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DeleteFacesFromCollection.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DeleteFacesFromCollection.java @@ -1,11 +1,5 @@ -// snippet-sourcedescription:[DeleteFacesFromCollection.java demonstrates how to delete faces from an Amazon Rekognition collection.] -//snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Rekognition] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rekognition; @@ -18,7 +12,8 @@ // snippet-end:[rekognition.java2.delete_faces_collection.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,13 +23,13 @@ public class DeleteFacesFromCollection { public static void main(String[] args) { final String usage = """ - Usage: \s + Usage: \s - Where: - collectionId - The id of the collection from which faces are deleted.\s + Where: + collectionId - The id of the collection from which faces are deleted.\s - faceId - The id of the face to delete.\s - """; + faceId - The id of the face to delete.\s + """; if (args.length != 1) { System.out.println(usage); @@ -45,8 +40,8 @@ public static void main(String[] args) { String faceId = args[1]; Region region = Region.US_EAST_1; RekognitionClient rekClient = RekognitionClient.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.println("Deleting collection: " + collectionId); deleteFacesCollection(rekClient, collectionId, faceId); @@ -54,14 +49,14 @@ public static void main(String[] args) { } public static void deleteFacesCollection(RekognitionClient rekClient, - String collectionId, - String faceId) { + String collectionId, + String faceId) { try { DeleteFacesRequest deleteFacesRequest = DeleteFacesRequest.builder() - .collectionId(collectionId) - .faceIds(faceId) - .build(); + .collectionId(collectionId) + .faceIds(faceId) + .build(); rekClient.deleteFaces(deleteFacesRequest); System.out.println("The face was deleted from the collection."); diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DescribeCollection.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DescribeCollection.java index bfd23d0a80d..6b4b59c00f0 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DescribeCollection.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DescribeCollection.java @@ -1,11 +1,5 @@ -// snippet-sourcedescription:[DescribeCollection.java demonstrates how to retrieve the description of an Amazon Rekognition collection.] -//snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Rekognition] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rekognition; @@ -19,7 +13,8 @@ // snippet-end:[rekognition.java2.describe_collection.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,11 +24,11 @@ public class DescribeCollection { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - collectionName - The name of the Amazon Rekognition collection.\s - """; + Where: + collectionName - The name of the Amazon Rekognition collection.\s + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +38,8 @@ public static void main(String[] args) { String collectionName = args[0]; Region region = Region.US_EAST_1; RekognitionClient rekClient = RekognitionClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeColl(rekClient, collectionName); rekClient.close(); @@ -53,10 +48,11 @@ public static void main(String[] args) { public static void describeColl(RekognitionClient rekClient, String collectionName) { try { DescribeCollectionRequest describeCollectionRequest = DescribeCollectionRequest.builder() - .collectionId(collectionName) - .build(); + .collectionId(collectionName) + .build(); - DescribeCollectionResponse describeCollectionResponse = rekClient.describeCollection(describeCollectionRequest); + DescribeCollectionResponse describeCollectionResponse = rekClient + .describeCollection(describeCollectionRequest); System.out.println("Collection Arn : " + describeCollectionResponse.collectionARN()); System.out.println("Created : " + describeCollectionResponse.creationTimestamp().toString()); diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectCustomLabels.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectCustomLabels.java index da3dc2a32f9..2494a51bcea 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectCustomLabels.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectCustomLabels.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rekognition; import software.amazon.awssdk.regions.Region; diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectFaces.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectFaces.java index c448dd60f3b..1534c9ed68f 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectFaces.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectFaces.java @@ -1,11 +1,5 @@ -// snippet-sourcedescription:[DetectFaces.java demonstrates how to detect faces in an image.] -//snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Rekognition] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rekognition; @@ -28,7 +22,8 @@ // snippet-end:[rekognition.java2.detect_faces.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -38,11 +33,11 @@ public class DetectFaces { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - sourceImage - The path to the image (for example, C:\\AWS\\pic1.png).\s - """; + Where: + sourceImage - The path to the image (for example, C:\\AWS\\pic1.png).\s + """; if (args.length != 1) { System.out.println(usage); @@ -52,8 +47,8 @@ public static void main(String[] args) { String sourceImage = args[0]; Region region = Region.US_EAST_1; RekognitionClient rekClient = RekognitionClient.builder() - .region(region) - .build(); + .region(region) + .build(); detectFacesinImage(rekClient, sourceImage); rekClient.close(); @@ -66,21 +61,21 @@ public static void detectFacesinImage(RekognitionClient rekClient, String source // Create an Image object for the source image. Image souImage = Image.builder() - .bytes(sourceBytes) - .build(); + .bytes(sourceBytes) + .build(); DetectFacesRequest facesRequest = DetectFacesRequest.builder() - .attributes(Attribute.ALL) - .image(souImage) - .build(); + .attributes(Attribute.ALL) + .image(souImage) + .build(); DetectFacesResponse facesResponse = rekClient.detectFaces(facesRequest); List faceDetails = facesResponse.faceDetails(); for (FaceDetail face : faceDetails) { AgeRange ageRange = face.ageRange(); System.out.println("The detected face is estimated to be between " - + ageRange.low().toString() + " and " + ageRange.high().toString() - + " years old."); + + ageRange.low().toString() + " and " + ageRange.high().toString() + + " years old."); System.out.println("There is a smile : " + face.smile().value().toString()); } diff --git a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectLabels.java b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectLabels.java index f2a77c7458f..fbcee551dcd 100644 --- a/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectLabels.java +++ b/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectLabels.java @@ -1,11 +1,5 @@ -// snippet-sourcedescription:[DetectLabels.java demonstrates how to capture labels (like water and mountains) in a given image.] -//snippet-keyword:[AWS SDK for Java v2] -// snippet-service:[Amazon Rekognition] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.rekognition; @@ -26,21 +20,22 @@ // snippet-end:[rekognition.java2.detect_labels.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ -public class DetectLabels { +public class DetectLabels { public static void main(String[] args) { final String usage = """ - Usage: + Usage: - Where: - sourceImage - The path to the image (for example, C:\\AWS\\pic1.png).\s - """; + Where: + sourceImage - The path to the image (for example, C:\\AWS\\pic1.png).\s + """; if (args.length != 1) { System.out.println(usage); @@ -50,8 +45,8 @@ public static void main(String[] args) { String sourceImage = args[0]; Region region = Region.US_EAST_1; RekognitionClient rekClient = RekognitionClient.builder() - .region(region) - .build(); + .region(region) + .build(); detectImageLabels(rekClient, sourceImage); rekClient.close(); @@ -64,13 +59,13 @@ public static void detectImageLabels(RekognitionClient rekClient, String sourceI // Create an Image object for the source image. Image souImage = Image.builder() - .bytes(sourceBytes) - .build(); + .bytes(sourceBytes) + .build(); DetectLabelsRequest detectLabelsRequest = DetectLabelsRequest.builder() - .image(souImage) - .maxLabels(10) - .build(); + .image(souImage) + .maxLabels(10) + .build(); DetectLabelsResponse labelsResponse = rekClient.detectLabels(detectLabelsRequest); List

    * For more information, see the following documentation topic: *

    @@ -60,8 +60,9 @@ public static void main(String[] args) { // snippet-start:[presigned.java2.generatepresignedurl.main] /** * Create a presigned URL for uploading a String object. + * * @param bucketName - The name of the bucket. - * @param keyName - The name of the object. + * @param keyName - The name of the object. * @return - The presigned URL for an HTTP PUT. */ public URL createSignedUrlForStringPut(String bucketName, String keyName) { @@ -74,27 +75,31 @@ public URL createSignedUrlForStringPut(String bucketName, String keyName) { .build(); PutObjectPresignRequest presignRequest = PutObjectPresignRequest.builder() - .signatureDuration(Duration.ofMinutes(10)) // The URL will expire in 10 minutes. + .signatureDuration(Duration.ofMinutes(10)) // The URL will expire in 10 minutes. .putObjectRequest(objectRequest) .build(); PresignedPutObjectRequest presignedRequest = presigner.presignPutObject(presignRequest); String myURL = presignedRequest.url().toString(); logger.info("Presigned URL to upload to: [{}]", myURL); - logger.info("Which HTTP method needs to be used when uploading: [{}]", presignedRequest.httpRequest().method()); + logger.info("Which HTTP method needs to be used when uploading: [{}]", + presignedRequest.httpRequest().method()); return presignedRequest.url(); } } /** - * Use the JDK HttpURLConnection (since v1.1) class to upload a String, but you can + * Use the JDK HttpURLConnection (since v1.1) class to upload a String, but you + * can * use any HTTP client. + * * @param presignedUrl - The presigned URL. */ public void useHttpUrlConnectionToPutString(URL presignedUrl) { try { - // Create the connection and use it to upload the new object by using the presigned URL. + // Create the connection and use it to upload the new object by using the + // presigned URL. HttpURLConnection connection = (HttpURLConnection) presignedUrl.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "text/plain"); @@ -114,16 +119,18 @@ public void useHttpUrlConnectionToPutString(URL presignedUrl) { /** * Use the JDK HttpClient class (since v11) to upload a String, * but you can use any HTTP client. + * * @param presignedUrl - The presigned URL. */ public void useHttpClientToPutString(URL presignedUrl) { HttpClient httpClient = HttpClient.newHttpClient(); try { final HttpResponse response = httpClient.send(HttpRequest.newBuilder() - .uri(presignedUrl.toURI()) - .header("Content-Type", "text/plain") - .PUT(HttpRequest.BodyPublishers.ofString("This text was uploaded as an object by using a presigned URL.")) - .build(), + .uri(presignedUrl.toURI()) + .header("Content-Type", "text/plain") + .PUT(HttpRequest.BodyPublishers + .ofString("This text was uploaded as an object by using a presigned URL.")) + .build(), HttpResponse.BodyHandlers.discarding()); logger.info("HTTP response code is " + response.statusCode()); } catch (S3Exception | IOException | URISyntaxException | InterruptedException e) { diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GetAcl.java b/javav2/example_code/s3/src/main/java/com/example/s3/GetAcl.java index 1cc077d86a1..3c72a0d41f0 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/GetAcl.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/GetAcl.java @@ -1,10 +1,6 @@ -//snippet-sourcedescription:[GetAcl.java demonstrates how to get the access control list (ACL) for an Amazon Simple Storage Service (Amazon S3) bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.s3; // snippet-start:[s3.java2.get_acl.main] @@ -19,7 +15,8 @@ // snippet-end:[s3.java2.get_acl.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,13 +27,13 @@ public class GetAcl { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - bucketName - The Amazon S3 bucket to get the access control list (ACL) for. - objectKey - The object to get the ACL for.\s - """; + Where: + bucketName - The Amazon S3 bucket to get the access control list (ACL) for. + objectKey - The object to get the ACL for.\s + """; if (args.length != 2) { System.out.println(usage); @@ -49,8 +46,8 @@ public static void main(String[] args) { System.out.println("in bucket: " + bucketName); Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); getBucketACL(s3, objectKey, bucketName); s3.close(); @@ -60,9 +57,9 @@ public static void main(String[] args) { public static String getBucketACL(S3Client s3, String objectKey, String bucketName) { try { GetObjectAclRequest aclReq = GetObjectAclRequest.builder() - .bucket(bucketName) - .key(objectKey) - .build(); + .bucket(bucketName) + .key(objectKey) + .build(); GetObjectAclResponse aclRes = s3.getObjectAcl(aclReq); List grants = aclRes.grants(); @@ -82,4 +79,3 @@ public static String getBucketACL(S3Client s3, String objectKey, String bucketNa } } // snippet-end:[s3.java2.get_acl.main] - diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GetBucketPolicy.java b/javav2/example_code/s3/src/main/java/com/example/s3/GetBucketPolicy.java index 310e476e196..74a4118449c 100755 --- a/javav2/example_code/s3/src/main/java/com/example/s3/GetBucketPolicy.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/GetBucketPolicy.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[GetBucketPolicy.java demonstrates how to get the bucket policy for an existing Amazon Simple Storage Service (Amazon S3) bucket] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; @@ -19,7 +13,8 @@ // snippet-end:[s3.java2.get_bucket_policy.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,12 +25,12 @@ public class GetBucketPolicy { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - bucketName - The Amazon S3 bucket to get the policy from. - """; + Where: + bucketName - The Amazon S3 bucket to get the policy from. + """; if (args.length != 1) { System.out.println(usage); @@ -46,8 +41,8 @@ public static void main(String[] args) { System.out.format("Getting policy for bucket: \"%s\"\n\n", bucketName); Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); String polText = getPolicy(s3, bucketName); System.out.println("Policy Text: " + polText); @@ -58,8 +53,8 @@ public static String getPolicy(S3Client s3, String bucketName) { String policyText; System.out.format("Getting policy for bucket: \"%s\"\n\n", bucketName); GetBucketPolicyRequest policyReq = GetBucketPolicyRequest.builder() - .bucket(bucketName) - .build(); + .bucket(bucketName) + .build(); try { GetBucketPolicyResponse policyRes = s3.getBucketPolicy(policyReq); diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GetDataResponseTransformer.java b/javav2/example_code/s3/src/main/java/com/example/s3/GetDataResponseTransformer.java index bf0495488d0..73da74e5b32 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/GetDataResponseTransformer.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/GetDataResponseTransformer.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[GetDataResponseTransformer.java demonstrates how to read data from an Amazon Simple Storage Service (Amazon S3) object using a ResponseTransformer.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; @@ -26,7 +19,8 @@ // snippet-end:[s3.java2.getobjectdata.transformer.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -37,14 +31,14 @@ public class GetDataResponseTransformer { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - bucketName - The Amazon S3 bucket name.\s - keyName - The key name.\s - path - The path where the file is written to.\s - """; + Where: + bucketName - The Amazon S3 bucket name.\s + keyName - The key name.\s + path - The path where the file is written to.\s + """; if (args.length != 3) { System.out.println(usage); @@ -56,8 +50,8 @@ public static void main(String[] args) { String path = args[2]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); getObjectBytes(s3, bucketName, keyName, path); s3.close(); @@ -66,10 +60,10 @@ public static void main(String[] args) { public static void getObjectBytes(S3Client s3, String bucketName, String keyName, String path) { try { GetObjectRequest objectRequest = GetObjectRequest - .builder() - .key(keyName) - .bucket(bucketName) - .build(); + .builder() + .key(keyName) + .bucket(bucketName) + .build(); ResponseBytes objectBytes = s3.getObject(objectRequest, ResponseTransformer.toBytes()); byte[] data = objectBytes.asByteArray(); @@ -90,4 +84,3 @@ public static void getObjectBytes(S3Client s3, String bucketName, String keyName } } // snippet-end:[s3.java2.getobjectdata.transformer.main] - diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectContentType.java b/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectContentType.java index 45e03309b2b..d01c8f9620d 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectContentType.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectContentType.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[GetObjectContentType.java demonstrates how to determine the content type of an object in an Amazon Simple Storage Service (Amazon S3) bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; @@ -20,7 +13,8 @@ // snippet-end:[s3.java2.getobjectcontenttype.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,13 +24,13 @@ public class GetObjectContentType { public static void main(String[] args) { final String usage = """ - Usage: - > + Usage: + > - Where: - bucketName - The Amazon S3 bucket name.\s - keyName - The key name.\s - """; + Where: + bucketName - The Amazon S3 bucket name.\s + keyName - The key name.\s + """; if (args.length != 2) { System.out.println(usage); @@ -47,8 +41,8 @@ public static void main(String[] args) { String keyName = args[1]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); getContentType(s3, bucketName, keyName); s3.close(); @@ -57,9 +51,9 @@ public static void main(String[] args) { public static void getContentType(S3Client s3, String bucketName, String keyName) { try { HeadObjectRequest objectRequest = HeadObjectRequest.builder() - .key(keyName) - .bucket(bucketName) - .build(); + .key(keyName) + .bucket(bucketName) + .build(); HeadObjectResponse objectHead = s3.headObject(objectRequest); String type = objectHead.contentType(); diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectData.java b/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectData.java index b1430c4b2cc..510dd8539e7 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectData.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectData.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[GetObjectData.java demonstrates how to read data from an Amazon Simple Storage Service (Amazon S3) object.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; @@ -25,7 +18,8 @@ // snippet-end:[s3.java2.getobjectdata.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -36,14 +30,14 @@ public class GetObjectData { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - bucketName - The Amazon S3 bucket name.\s - keyName - The key name.\s - path - The path where the file is written to.\s - """; + Where: + bucketName - The Amazon S3 bucket name.\s + keyName - The key name.\s + path - The path where the file is written to.\s + """; if (args.length != 3) { System.out.println(usage); @@ -55,20 +49,19 @@ public static void main(String[] args) { String path = args[2]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); getObjectBytes(s3, bucketName, keyName, path); } - public static void - getObjectBytes(S3Client s3, String bucketName, String keyName, String path) { + public static void getObjectBytes(S3Client s3, String bucketName, String keyName, String path) { try { GetObjectRequest objectRequest = GetObjectRequest - .builder() - .key(keyName) - .bucket(bucketName) - .build(); + .builder() + .key(keyName) + .bucket(bucketName) + .build(); ResponseBytes objectBytes = s3.getObjectAsBytes(objectRequest); byte[] data = objectBytes.asByteArray(); diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectPresignedUrl.java b/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectPresignedUrl.java index 430b4e06d69..4ea26af1182 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectPresignedUrl.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectPresignedUrl.java @@ -1,12 +1,6 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[GetObjectUsingPresignedUrl.java demonstrates how to get an object located in an Amazon Simple Storage Service (Amazon S3) bucket by using the S3Presigner client object] -// snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.s3; // snippet-start:[presigned.java2.getobjectpresigned.main] @@ -26,7 +20,8 @@ // snippet-end:[presigned.java2.getobjectpresigned.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -36,13 +31,13 @@ public class GetObjectPresignedUrl { public static void main(String[] args) { final String USAGE = """ - Usage: - \s + Usage: + \s - Where: - bucketName - The Amazon S3 bucket name.\s - keyName - A key name that represents a text file.\s - """; + Where: + bucketName - The Amazon S3 bucket name.\s + keyName - A key name that represents a text file.\s + """; if (args.length != 2) { System.out.println(USAGE); @@ -53,8 +48,8 @@ public static void main(String[] args) { String keyName = args[1]; Region region = Region.US_EAST_1; S3Presigner presigner = S3Presigner.builder() - .region(region) - .build(); + .region(region) + .build(); getPresignedUrl(presigner, bucketName, keyName); presigner.close(); @@ -63,14 +58,14 @@ public static void main(String[] args) { public static void getPresignedUrl(S3Presigner presigner, String bucketName, String keyName) { try { GetObjectRequest getObjectRequest = GetObjectRequest.builder() - .bucket(bucketName) - .key(keyName) - .build(); + .bucket(bucketName) + .key(keyName) + .build(); GetObjectPresignRequest getObjectPresignRequest = GetObjectPresignRequest.builder() - .signatureDuration(Duration.ofMinutes(60)) - .getObjectRequest(getObjectRequest) - .build(); + .signatureDuration(Duration.ofMinutes(60)) + .getObjectRequest(getObjectRequest) + .build(); PresignedGetObjectRequest presignedGetObjectRequest = presigner.presignGetObject(getObjectPresignRequest); String theUrl = presignedGetObjectRequest.url().toString(); @@ -82,12 +77,13 @@ public static void getPresignedUrl(S3Presigner presigner, String bucketName, Str }); }); - // Send any request payload that the service needs (not needed when isBrowserExecutable is true). + // Send any request payload that the service needs (not needed when + // isBrowserExecutable is true). if (presignedGetObjectRequest.signedPayload().isPresent()) { connection.setDoOutput(true); try (InputStream signedPayload = presignedGetObjectRequest.signedPayload().get().asInputStream(); - OutputStream httpOutputStream = connection.getOutputStream()) { + OutputStream httpOutputStream = connection.getOutputStream()) { IoUtils.copy(signedPayload, httpOutputStream); } } diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectRestoreStatus.java b/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectRestoreStatus.java index 9b7c93277b1..b3102d23e49 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectRestoreStatus.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectRestoreStatus.java @@ -1,61 +1,58 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[GetObjectRestoreStatus.java demonstrates how to get the restore status of an Amazon Simple Storage Service (Amazon S3) object.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -package com.example.s3; - -// snippet-start:[s3.java2.get.restore.status.main] -// snippet-start:[s3.java2.get.restore.status.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.HeadObjectRequest; -import software.amazon.awssdk.services.s3.model.HeadObjectResponse; -import software.amazon.awssdk.services.s3.model.S3Exception; -// snippet-end:[s3.java2.get.restore.status.import] - -public class GetObjectRestoreStatus { - public static void main(String[] args) { - final String usage = """ - - Usage: - \s - - Where: - bucketName - The Amazon S3 bucket name.\s - keyName - A key name that represents the object.\s - """; - - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String keyName = args[1]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - checkStatus(s3, bucketName, keyName); - s3.close(); - } - - public static void checkStatus(S3Client s3, String bucketName, String keyName) { - try { - HeadObjectRequest headObjectRequest = HeadObjectRequest.builder() - .bucket(bucketName) - .key(keyName) - .build(); - - HeadObjectResponse response = s3.headObject(headObjectRequest); - System.out.println("The Amazon S3 object restoration status is " + response.restore()); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.get.restore.status.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +package com.example.s3; + +// snippet-start:[s3.java2.get.restore.status.main] +// snippet-start:[s3.java2.get.restore.status.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.HeadObjectRequest; +import software.amazon.awssdk.services.s3.model.HeadObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; +// snippet-end:[s3.java2.get.restore.status.import] + +public class GetObjectRestoreStatus { + public static void main(String[] args) { + final String usage = """ + + Usage: + \s + + Where: + bucketName - The Amazon S3 bucket name.\s + keyName - A key name that represents the object.\s + """; + + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String keyName = args[1]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + checkStatus(s3, bucketName, keyName); + s3.close(); + } + + public static void checkStatus(S3Client s3, String bucketName, String keyName) { + try { + HeadObjectRequest headObjectRequest = HeadObjectRequest.builder() + .bucket(bucketName) + .key(keyName) + .build(); + + HeadObjectResponse response = s3.headObject(headObjectRequest); + System.out.println("The Amazon S3 object restoration status is " + response.restore()); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.get.restore.status.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectTags.java b/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectTags.java index 42d1e6bb8ab..86a3c73b7fa 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectTags.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectTags.java @@ -1,12 +1,6 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[GetObjectTags.java demonstrates how to read tags that belong to an object located in an Amazon Simple Storage Service (Amazon S3) bucket.] -///snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.s3; // snippet-start:[s3.java2.getobjecttags.main] @@ -21,7 +15,8 @@ // snippet-end:[s3.java2.getobjecttags.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,13 +27,13 @@ public class GetObjectTags { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - bucketName - The Amazon S3 bucket name.\s - keyName - A key name that represents the object.\s - """; + Where: + bucketName - The Amazon S3 bucket name.\s + keyName - A key name that represents the object.\s + """; if (args.length != 2) { System.out.println(usage); @@ -49,23 +44,23 @@ public static void main(String[] args) { String keyName = args[1]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); - listTags(s3,bucketName,keyName); + listTags(s3, bucketName, keyName); s3.close(); } public static void listTags(S3Client s3, String bucketName, String keyName) { try { GetObjectTaggingRequest getTaggingRequest = GetObjectTaggingRequest - .builder() - .key(keyName) - .bucket(bucketName) - .build(); + .builder() + .key(keyName) + .bucket(bucketName) + .build(); GetObjectTaggingResponse tags = s3.getObjectTagging(getTaggingRequest); - List tagSet= tags.tagSet(); + List tagSet = tags.tagSet(); for (Tag tag : tagSet) { System.out.println(tag.key()); System.out.println(tag.value()); diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectUrl.java b/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectUrl.java index aaeb4e8f008..76faa750e6e 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectUrl.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectUrl.java @@ -1,74 +1,69 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[GetObjectUrl.java demonstrates how to get an URL for an object located in an Amazon Simple Storage Service (Amazon S3) bucket.] -///snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ -package com.example.s3; - -// snippet-start:[s3.java2.getobjecturl.main] -// snippet-start:[s3.java2.getobjecturl.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.GetUrlRequest; -import software.amazon.awssdk.services.s3.model.S3Exception; -import java.net.URL; -// snippet-end:[s3.java2.getobjecturl.import] - -/** - * Before running this Java V2 code example, set up your development environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class GetObjectUrl { - public static void main(String[] args) { - final String usage = """ - - Usage: - \s - - Where: - bucketName - The Amazon S3 bucket name. - keyName - A key name that represents the object.\s - """; - - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String keyName = args[1]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - getURL(s3, bucketName, keyName); - s3.close(); - } - - public static void getURL(S3Client s3, String bucketName, String keyName) { - try { - GetUrlRequest request = GetUrlRequest.builder() - .bucket(bucketName) - .key(keyName) - .build(); - - URL url = s3.utilities().getUrl(request); - System.out.println("The URL for " + keyName + " is " + url); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.getobjecturl.main] - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +//* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +*SPDX-License-Identifier:Apache-2.0*/ +package com.example.s3; + +// snippet-start:[s3.java2.getobjecturl.main] +// snippet-start:[s3.java2.getobjecturl.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetUrlRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import java.net.URL; +// snippet-end:[s3.java2.getobjecturl.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class GetObjectUrl { + public static void main(String[] args) { + final String usage = """ + + Usage: + \s + + Where: + bucketName - The Amazon S3 bucket name. + keyName - A key name that represents the object.\s + """; + + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String keyName = args[1]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + getURL(s3, bucketName, keyName); + s3.close(); + } + + public static void getURL(S3Client s3, String bucketName, String keyName) { + try { + GetUrlRequest request = GetUrlRequest.builder() + .bucket(bucketName) + .key(keyName) + .build(); + + URL url = s3.utilities().getUrl(request); + System.out.println("The URL for " + keyName + " is " + url); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.getobjecturl.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/HelloS3.java b/javav2/example_code/s3/src/main/java/com/example/s3/HelloS3.java index 83f10453443..b62cf0f35cf 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/HelloS3.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/HelloS3.java @@ -1,10 +1,6 @@ -//snippet-sourcedescription:[HelloS3.java demonstrates how to list your Amazon Simple Storage Service (Amazon S3) buckets.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.s3; // snippet-start:[s3.java2.hello.main] @@ -16,7 +12,8 @@ import java.util.List; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -26,8 +23,8 @@ public class HelloS3 { public static void main(String[] args) { Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); listBuckets(s3); } diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/KMSEncryptionExample.java b/javav2/example_code/s3/src/main/java/com/example/s3/KMSEncryptionExample.java index 32d60e8908c..5b57eadebfe 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/KMSEncryptionExample.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/KMSEncryptionExample.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[KMSEncryptionExample.java demonstrates how to use the AWS Key Management Service (AWS KMS) service to encrypt data prior to placing the data into an Amazon Simple Storage Service (Amazon S3) bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; @@ -34,14 +28,17 @@ // snippet-end:[s3.java2.kms.import] /** - * Before running this code example, you need to create a key by using the AWS Key Management Service. - * For information, see "Creating keys" in the AWS Key Management Service Developer Guide. + * Before running this code example, you need to create a key by using the AWS + * Key Management Service. + * For information, see "Creating keys" in the AWS Key Management Service + * Developer Guide. * - * In addition, before running this Java V2 code example, set up your development environment, including your credentials. + * In addition, before running this Java V2 code example, set up your + * development environment, including your credentials. * * For more information, see the following documentation topic: * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * */ @@ -50,16 +47,16 @@ public class KMSEncryptionExample { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - objectName - The name of the object.\s - bucketName - The Amazon S3 bucket name that contains the object (for example, bucket1).\s - objectPath - The path to a TXT file to encrypt and place into a Amazon S3 bucket (for example, C:/AWS/test.txt). - outPath - The path where a text file is written to after it's decrypted (for example, C:/AWS/testPlain.txt). - keyId - The id of the AWS KMS key to use to encrpt/decrypt the data. You can obtain the key ID value from the AWS Management Console. - """; + Where: + objectName - The name of the object.\s + bucketName - The Amazon S3 bucket name that contains the object (for example, bucket1).\s + objectPath - The path to a TXT file to encrypt and place into a Amazon S3 bucket (for example, C:/AWS/test.txt). + outPath - The path where a text file is written to after it's decrypted (for example, C:/AWS/testPlain.txt). + keyId - The id of the AWS KMS key to use to encrpt/decrypt the data. You can obtain the key ID value from the AWS Management Console. + """; if (args.length != 5) { System.out.println(usage); @@ -73,8 +70,8 @@ public static void main(String[] args) { String keyId = args[4]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); putEncryptData(s3, objectName, bucketName, objectPath, keyId); getEncryptedData(s3, bucketName, objectName, outPath, keyId); @@ -82,12 +79,13 @@ public static void main(String[] args) { } // Encrypt data and place the encrypted data into an Amazon S3 bucket. - public static void putEncryptData(S3Client s3, String objectName, String bucketName, String objectPath, String keyId) { + public static void putEncryptData(S3Client s3, String objectName, String bucketName, String objectPath, + String keyId) { try { PutObjectRequest objectRequest = PutObjectRequest.builder() - .bucket(bucketName) - .key(objectName) - .build(); + .bucket(bucketName) + .key(objectName) + .build(); byte[] myData = getObjectFile(objectPath); @@ -105,9 +103,9 @@ public static void putEncryptData(S3Client s3, String objectName, String bucketN public static void getEncryptedData(S3Client s3, String bucketName, String objectName, String path, String keyId) { try { GetObjectRequest objectRequest = GetObjectRequest.builder() - .key(objectName) - .bucket(bucketName) - .build(); + .key(objectName) + .bucket(bucketName) + .build(); // Get the byte[] from the Amazon S3 bucket. ResponseBytes objectBytes = s3.getObjectAsBytes(objectRequest); @@ -138,9 +136,9 @@ private static byte[] encryptData(String keyId, byte[] data) { SdkBytes myBytes = SdkBytes.fromByteArray(data); EncryptRequest encryptRequest = EncryptRequest.builder() - .keyId(keyId) - .plaintext(myBytes) - .build(); + .keyId(keyId) + .plaintext(myBytes) + .build(); EncryptResponse response = kmsClient.encrypt(encryptRequest); String algorithm = response.encryptionAlgorithm().toString(); @@ -166,9 +164,9 @@ private static byte[] decryptData(byte[] data, String keyId) { SdkBytes encryptedData = SdkBytes.fromByteArray(data); DecryptRequest decryptRequest = DecryptRequest.builder() - .ciphertextBlob(encryptedData) - .keyId(keyId) - .build(); + .ciphertextBlob(encryptedData) + .keyId(keyId) + .build(); DecryptResponse decryptResponse = kmsClient.decrypt(decryptRequest); SdkBytes plainText = decryptResponse.plaintext(); @@ -215,8 +213,8 @@ private static KmsClient getKMSClient() { Region region = Region.US_EAST_1; return KmsClient.builder() - .region(region) - .build(); + .region(region) + .build(); } } // snippet-end:[s3.java2.kms.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/LifecycleConfiguration.java b/javav2/example_code/s3/src/main/java/com/example/s3/LifecycleConfiguration.java index 2a2ddfca56c..023923e4d84 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/LifecycleConfiguration.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/LifecycleConfiguration.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[LifecycleConfiguration.java demonstrates how to add, update, and delete a Lifecycle configuration.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.s3; // snippet-start:[s3.java2.manage_lifecycle.main] @@ -15,7 +10,7 @@ import software.amazon.awssdk.services.s3.model.LifecycleRuleFilter; import software.amazon.awssdk.services.s3.model.Transition; import software.amazon.awssdk.services.s3.model.GetBucketLifecycleConfigurationRequest; -import software.amazon.awssdk.services.s3.model.GetBucketLifecycleConfigurationResponse ; +import software.amazon.awssdk.services.s3.model.GetBucketLifecycleConfigurationResponse; import software.amazon.awssdk.services.s3.model.DeleteBucketLifecycleRequest; import software.amazon.awssdk.services.s3.model.TransitionStorageClass; import software.amazon.awssdk.services.s3.model.LifecycleRule; @@ -28,7 +23,8 @@ // snippet-end:[s3.java2.manage_lifecycle.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -36,164 +32,170 @@ */ public class LifecycleConfiguration { - public static void main(String[] args) { - final String usage = """ - - Usage: - \s - - Where: - bucketName - The Amazon Simple Storage Service (Amazon S3) bucket to upload an object into. - accountId - The id of the account that owns the Amazon S3 bucket. - """; - - if (args.length != 2) { - System.out.println(usage); - System.exit(1); + public static void main(String[] args) { + final String usage = """ + + Usage: + \s + + Where: + bucketName - The Amazon Simple Storage Service (Amazon S3) bucket to upload an object into. + accountId - The id of the account that owns the Amazon S3 bucket. + """; + + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String accountId = args[1]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + setLifecycleConfig(s3, bucketName, accountId); + getLifecycleConfig(s3, bucketName, accountId); + deleteLifecycleConfig(s3, bucketName, accountId); + System.out.println("You have successfully created, updated, and deleted a Lifecycle configuration"); + s3.close(); } - String bucketName = args[0]; - String accountId = args[1]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - setLifecycleConfig(s3, bucketName, accountId); - getLifecycleConfig(s3, bucketName, accountId); - deleteLifecycleConfig(s3, bucketName, accountId); - System.out.println("You have successfully created, updated, and deleted a Lifecycle configuration"); - s3.close(); - } - - public static void setLifecycleConfig(S3Client s3, String bucketName, String accountId) { - try { - // Create a rule to archive objects with the "glacierobjects/" prefix to Amazon S3 Glacier. - LifecycleRuleFilter ruleFilter = LifecycleRuleFilter.builder() - .prefix("glacierobjects/") - .build(); - - Transition transition = Transition.builder() - .storageClass(TransitionStorageClass.GLACIER) - .days(0) - .build(); - - LifecycleRule rule1 = LifecycleRule.builder() - .id("Archive immediately rule") - .filter(ruleFilter) - .transitions(transition) - .status(ExpirationStatus.ENABLED) - .build(); - - // Create a second rule. - Transition transition2 = Transition.builder() - .storageClass(TransitionStorageClass.GLACIER) - .days(0) - .build(); - - List transitionList = new ArrayList<>(); - transitionList.add(transition2); - - LifecycleRuleFilter ruleFilter2 = LifecycleRuleFilter.builder() - .prefix("glacierobjects/") - .build(); - - LifecycleRule rule2 = LifecycleRule.builder() - .id("Archive and then delete rule") - .filter(ruleFilter2) - .transitions(transitionList) - .status(ExpirationStatus.ENABLED) - .build(); - - // Add the LifecycleRule objects to an ArrayList. - ArrayList ruleList = new ArrayList<>(); - ruleList.add(rule1); - ruleList.add(rule2); - - BucketLifecycleConfiguration lifecycleConfiguration = BucketLifecycleConfiguration.builder() - .rules(ruleList) - .build(); - - PutBucketLifecycleConfigurationRequest putBucketLifecycleConfigurationRequest = PutBucketLifecycleConfigurationRequest.builder() - .bucket(bucketName) - .lifecycleConfiguration(lifecycleConfiguration) - .expectedBucketOwner(accountId) - .build(); - - s3.putBucketLifecycleConfiguration(putBucketLifecycleConfigurationRequest); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + public static void setLifecycleConfig(S3Client s3, String bucketName, String accountId) { + try { + // Create a rule to archive objects with the "glacierobjects/" prefix to Amazon + // S3 Glacier. + LifecycleRuleFilter ruleFilter = LifecycleRuleFilter.builder() + .prefix("glacierobjects/") + .build(); + + Transition transition = Transition.builder() + .storageClass(TransitionStorageClass.GLACIER) + .days(0) + .build(); + + LifecycleRule rule1 = LifecycleRule.builder() + .id("Archive immediately rule") + .filter(ruleFilter) + .transitions(transition) + .status(ExpirationStatus.ENABLED) + .build(); + + // Create a second rule. + Transition transition2 = Transition.builder() + .storageClass(TransitionStorageClass.GLACIER) + .days(0) + .build(); + + List transitionList = new ArrayList<>(); + transitionList.add(transition2); + + LifecycleRuleFilter ruleFilter2 = LifecycleRuleFilter.builder() + .prefix("glacierobjects/") + .build(); + + LifecycleRule rule2 = LifecycleRule.builder() + .id("Archive and then delete rule") + .filter(ruleFilter2) + .transitions(transitionList) + .status(ExpirationStatus.ENABLED) + .build(); + + // Add the LifecycleRule objects to an ArrayList. + ArrayList ruleList = new ArrayList<>(); + ruleList.add(rule1); + ruleList.add(rule2); + + BucketLifecycleConfiguration lifecycleConfiguration = BucketLifecycleConfiguration.builder() + .rules(ruleList) + .build(); + + PutBucketLifecycleConfigurationRequest putBucketLifecycleConfigurationRequest = PutBucketLifecycleConfigurationRequest + .builder() + .bucket(bucketName) + .lifecycleConfiguration(lifecycleConfiguration) + .expectedBucketOwner(accountId) + .build(); + + s3.putBucketLifecycleConfiguration(putBucketLifecycleConfigurationRequest); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } } - } - - // Retrieve the configuration and add a new rule. - public static void getLifecycleConfig(S3Client s3, String bucketName, String accountId) { - try { - GetBucketLifecycleConfigurationRequest getBucketLifecycleConfigurationRequest = GetBucketLifecycleConfigurationRequest.builder() - .bucket(bucketName) - .expectedBucketOwner(accountId) - .build(); - - GetBucketLifecycleConfigurationResponse response = s3.getBucketLifecycleConfiguration(getBucketLifecycleConfigurationRequest); - List newList = new ArrayList<>(); - List rules = response.rules(); - for (LifecycleRule rule : rules) { - newList.add(rule); - } - - // Add a new rule with both a prefix predicate and a tag predicate. - LifecycleRuleFilter ruleFilter = LifecycleRuleFilter.builder() - .prefix("YearlyDocuments/") - .build(); - - Transition transition = Transition.builder() - .storageClass(TransitionStorageClass.GLACIER) - .days(3650) - .build(); - - LifecycleRule rule1 = LifecycleRule.builder() - .id("NewRule") - .filter(ruleFilter) - .transitions(transition) - .status(ExpirationStatus.ENABLED) - .build(); - - // Add the new rule to the list. - newList.add(rule1); - BucketLifecycleConfiguration lifecycleConfiguration = BucketLifecycleConfiguration.builder() - .rules(newList) - .build(); - - PutBucketLifecycleConfigurationRequest putBucketLifecycleConfigurationRequest = PutBucketLifecycleConfigurationRequest.builder() - .bucket(bucketName) - .lifecycleConfiguration(lifecycleConfiguration) - .expectedBucketOwner(accountId) - .build(); - - s3.putBucketLifecycleConfiguration(putBucketLifecycleConfigurationRequest); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - // Delete the configuration from the Amazon S3 bucket. - public static void deleteLifecycleConfig(S3Client s3, String bucketName, String accountId) { - try { - DeleteBucketLifecycleRequest deleteBucketLifecycleRequest = DeleteBucketLifecycleRequest.builder() - .bucket(bucketName) - .expectedBucketOwner(accountId) - .build(); - s3.deleteBucketLifecycle(deleteBucketLifecycleRequest); + // Retrieve the configuration and add a new rule. + public static void getLifecycleConfig(S3Client s3, String bucketName, String accountId) { + try { + GetBucketLifecycleConfigurationRequest getBucketLifecycleConfigurationRequest = GetBucketLifecycleConfigurationRequest + .builder() + .bucket(bucketName) + .expectedBucketOwner(accountId) + .build(); + + GetBucketLifecycleConfigurationResponse response = s3 + .getBucketLifecycleConfiguration(getBucketLifecycleConfigurationRequest); + List newList = new ArrayList<>(); + List rules = response.rules(); + for (LifecycleRule rule : rules) { + newList.add(rule); + } + + // Add a new rule with both a prefix predicate and a tag predicate. + LifecycleRuleFilter ruleFilter = LifecycleRuleFilter.builder() + .prefix("YearlyDocuments/") + .build(); + + Transition transition = Transition.builder() + .storageClass(TransitionStorageClass.GLACIER) + .days(3650) + .build(); + + LifecycleRule rule1 = LifecycleRule.builder() + .id("NewRule") + .filter(ruleFilter) + .transitions(transition) + .status(ExpirationStatus.ENABLED) + .build(); + + // Add the new rule to the list. + newList.add(rule1); + BucketLifecycleConfiguration lifecycleConfiguration = BucketLifecycleConfiguration.builder() + .rules(newList) + .build(); + + PutBucketLifecycleConfigurationRequest putBucketLifecycleConfigurationRequest = PutBucketLifecycleConfigurationRequest + .builder() + .bucket(bucketName) + .lifecycleConfiguration(lifecycleConfiguration) + .expectedBucketOwner(accountId) + .build(); + + s3.putBucketLifecycleConfiguration(putBucketLifecycleConfigurationRequest); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + // Delete the configuration from the Amazon S3 bucket. + public static void deleteLifecycleConfig(S3Client s3, String bucketName, String accountId) { + try { + DeleteBucketLifecycleRequest deleteBucketLifecycleRequest = DeleteBucketLifecycleRequest + .builder() + .bucket(bucketName) + .expectedBucketOwner(accountId) + .build(); + + s3.deleteBucketLifecycle(deleteBucketLifecycleRequest); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } } - } } // snippet-end:[s3.java2.manage_lifecycle.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/ListMultipartUploads.java b/javav2/example_code/s3/src/main/java/com/example/s3/ListMultipartUploads.java index 7b1a9e45f36..b6b84cc3342 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/ListMultipartUploads.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/ListMultipartUploads.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[ListMultipartUploads.java demonstrates how to retrieve a list of in-progress multipart uploads.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; @@ -21,7 +15,8 @@ // snippet-end:[s3.java2.list_multi_uploads.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,12 +27,12 @@ public class ListMultipartUploads { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - bucketName - The name of the Amazon S3 bucket where an in-progress multipart upload is occurring. - """; + Where: + bucketName - The name of the Amazon S3 bucket where an in-progress multipart upload is occurring. + """; if (args.length != 1) { System.out.println(usage); @@ -47,8 +42,8 @@ public static void main(String[] args) { String bucketName = args[0]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); listUploads(s3, bucketName); s3.close(); } @@ -56,8 +51,8 @@ public static void main(String[] args) { public static void listUploads(S3Client s3, String bucketName) { try { ListMultipartUploadsRequest listMultipartUploadsRequest = ListMultipartUploadsRequest.builder() - .bucket(bucketName) - .build(); + .bucket(bucketName) + .build(); ListMultipartUploadsResponse response = s3.listMultipartUploads(listMultipartUploadsRequest); List uploads = response.uploads(); diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/ListObjects.java b/javav2/example_code/s3/src/main/java/com/example/s3/ListObjects.java index 9f8794ca81b..b43802fada4 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/ListObjects.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/ListObjects.java @@ -1,10 +1,6 @@ -//snippet-sourcedescription:[ListObjects.java demonstrates how to list objects located in a given Amazon Simple Storage Service (Amazon S3) bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.s3; // snippet-start:[s3.java2.list_objects.main] @@ -19,7 +15,8 @@ // snippet-end:[s3.java2.list_objects.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,12 +27,12 @@ public class ListObjects { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - bucketName - The Amazon S3 bucket from which objects are read.\s - """; + Where: + bucketName - The Amazon S3 bucket from which objects are read.\s + """; if (args.length != 1) { System.out.println(usage); @@ -45,8 +42,8 @@ public static void main(String[] args) { String bucketName = args[0]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); listBucketObjects(s3, bucketName); s3.close(); @@ -55,9 +52,9 @@ public static void main(String[] args) { public static void listBucketObjects(S3Client s3, String bucketName) { try { ListObjectsRequest listObjects = ListObjectsRequest - .builder() - .bucket(bucketName) - .build(); + .builder() + .bucket(bucketName) + .build(); ListObjectsResponse res = s3.listObjects(listObjects); List objects = res.contents(); @@ -73,7 +70,7 @@ public static void listBucketObjects(S3Client s3, String bucketName) { } } - //convert bytes to kbs. + // convert bytes to kbs. private static long calKb(Long val) { return val / 1024; } diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/ListObjectsPaginated.java b/javav2/example_code/s3/src/main/java/com/example/s3/ListObjectsPaginated.java index fe3583ea04a..a967fbf0076 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/ListObjectsPaginated.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/ListObjectsPaginated.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[ListObjectsPaginated.java demonstrates how to list objects using pagination.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; @@ -19,12 +14,12 @@ public class ListObjectsPaginated { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - bucketName - The Amazon S3 bucket from which objects are read.\s - """; + Where: + bucketName - The Amazon S3 bucket from which objects are read.\s + """; if (args.length != 1) { System.out.println(usage); @@ -34,8 +29,8 @@ public static void main(String[] args) { String bucketName = args[0]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); listBucketObjects(s3, bucketName); s3.close(); @@ -44,14 +39,14 @@ public static void main(String[] args) { public static void listBucketObjects(S3Client s3, String bucketName) { try { ListObjectsV2Request listReq = ListObjectsV2Request.builder() - .bucket(bucketName) - .maxKeys(1) - .build(); + .bucket(bucketName) + .maxKeys(1) + .build(); ListObjectsV2Iterable listRes = s3.listObjectsV2Paginator(listReq); listRes.stream() - .flatMap(r -> r.contents().stream()) - .forEach(content -> System.out.println(" Key: " + content.key() + " size = " + content.size())); + .flatMap(r -> r.contents().stream()) + .forEach(content -> System.out.println(" Key: " + content.key() + " size = " + content.size())); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -60,5 +55,3 @@ public static void listBucketObjects(S3Client s3, String bucketName) { } } // snippet-end:[s3.java2.list_objects.pag.main] - - diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/ManagingObjectTags.java b/javav2/example_code/s3/src/main/java/com/example/s3/ManagingObjectTags.java index ae7e5543139..2977b43d359 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/ManagingObjectTags.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/ManagingObjectTags.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[ManagingObjectTags.java demonstrates how to set tags for an object in an Amazon Simple Storage Service (Amazon S3) bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.s3; // snippet-start:[s3.java2.s3_object_manage_tags.import] @@ -27,7 +22,8 @@ // snippet-end:[s3.java2.s3_object_manage_tags.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -37,14 +33,14 @@ public class ManagingObjectTags { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - bucketName - The Amazon S3 bucket. - objectKey - The object that a tag is applied (for example, book.pdf). - objectPath - The path where the file is located (for example, C:/AWS/book2.pdf).\s - """; + Where: + bucketName - The Amazon S3 bucket. + objectKey - The object that a tag is applied (for example, book.pdf). + objectPath - The path where the file is located (for example, C:/AWS/book2.pdf).\s + """; if (args.length != 3) { System.out.println(usage); @@ -54,12 +50,12 @@ public static void main(String[] args) { String bucketName = args[0]; String objectKey = args[1]; String objectPath = args[2]; - System.out.println("Putting object " + objectKey +" into bucket "+bucketName); + System.out.println("Putting object " + objectKey + " into bucket " + bucketName); System.out.println(" in bucket: " + bucketName); Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); putS3ObjectTags(s3, bucketName, objectKey, objectPath); updateObjectTags(s3, bucketName, objectKey); @@ -70,28 +66,28 @@ public static void main(String[] args) { public static void putS3ObjectTags(S3Client s3, String bucketName, String objectKey, String objectPath) { try { Tag tag1 = Tag.builder() - .key("Tag 1") - .value("This is tag 1") - .build(); + .key("Tag 1") + .value("This is tag 1") + .build(); Tag tag2 = Tag.builder() - .key("Tag 2") - .value("This is tag 2") - .build(); + .key("Tag 2") + .value("This is tag 2") + .build(); List tags = new ArrayList<>(); tags.add(tag1); tags.add(tag2); Tagging allTags = Tagging.builder() - .tagSet(tags) - .build(); + .tagSet(tags) + .build(); PutObjectRequest putOb = PutObjectRequest.builder() - .bucket(bucketName) - .key(objectKey) - .tagging(allTags) - .build(); + .bucket(bucketName) + .key(objectKey) + .tagging(allTags) + .build(); s3.putObject(putOb, RequestBody.fromBytes(getObjectFile(objectPath))); @@ -104,48 +100,48 @@ public static void putS3ObjectTags(S3Client s3, String bucketName, String object public static void updateObjectTags(S3Client s3, String bucketName, String objectKey) { try { GetObjectTaggingRequest taggingRequest = GetObjectTaggingRequest.builder() - .bucket(bucketName) - .key(objectKey) - .build(); + .bucket(bucketName) + .key(objectKey) + .build(); GetObjectTaggingResponse getTaggingRes = s3.getObjectTagging(taggingRequest); List obTags = getTaggingRes.tagSet(); - for (Tag sinTag: obTags) { - System.out.println("The tag key is: "+sinTag.key()); - System.out.println("The tag value is: "+sinTag.value()); + for (Tag sinTag : obTags) { + System.out.println("The tag key is: " + sinTag.key()); + System.out.println("The tag value is: " + sinTag.value()); } // Replace the object's tags with two new tags. Tag tag3 = Tag.builder() - .key("Tag 3") - .value("This is tag 3") - .build(); + .key("Tag 3") + .value("This is tag 3") + .build(); Tag tag4 = Tag.builder() - .key("Tag 4") - .value("This is tag 4") - .build(); + .key("Tag 4") + .value("This is tag 4") + .build(); List tags = new ArrayList<>(); tags.add(tag3); tags.add(tag4); Tagging updatedTags = Tagging.builder() - .tagSet(tags) - .build(); + .tagSet(tags) + .build(); PutObjectTaggingRequest taggingRequest1 = PutObjectTaggingRequest.builder() - .bucket(bucketName) - .key(objectKey) - .tagging(updatedTags) - .build(); + .bucket(bucketName) + .key(objectKey) + .tagging(updatedTags) + .build(); s3.putObjectTagging(taggingRequest1); GetObjectTaggingResponse getTaggingRes2 = s3.getObjectTagging(taggingRequest); List modTags = getTaggingRes2.tagSet(); - for (Tag sinTag: modTags) { - System.out.println("The tag key is: "+sinTag.key()); - System.out.println("The tag value is: "+sinTag.value()); + for (Tag sinTag : modTags) { + System.out.println("The tag key is: " + sinTag.key()); + System.out.println("The tag value is: " + sinTag.value()); } } catch (S3Exception e) { diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/ParseUri.java b/javav2/example_code/s3/src/main/java/com/example/s3/ParseUri.java index 307a9dc2733..ae2f5a39333 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/ParseUri.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/ParseUri.java @@ -1,12 +1,6 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[ParseUri.java demonstrates how to parse a URI for an Amazon Simple Storage Service (Amazon S3) object.] -///snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.s3; // snippet-start:[s3.java2.scenario_uriparsing.import] @@ -23,7 +17,8 @@ // snippet-end:[s3.java2.scenario_uriparsing.import] /** - * Before running this Java V2 code example, set up your development environment, including access to temporary credentials. + * Before running this Java V2 code example, set up your development + * environment, including access to temporary credentials. *

    * For more information, see the following documentation topic: *

    @@ -32,6 +27,7 @@ public class ParseUri { private static final Logger logger = LoggerFactory.getLogger(ParseUri.class); + public static void main(String[] args) { S3Client s3Client = S3Client.create(); String url = "https://s3.us-west-1.amazonaws.com/myBucket/resources/doc.txt?versionId=abc123&partNumber=77&partNumber=88"; @@ -41,12 +37,14 @@ public static void main(String[] args) { // snippet-start:[s3.java2.scenario_uriparsing.main] /** * - * @param s3Client - An S3Client through which you acquire an S3Uri instance. - * @param s3ObjectUrl - A complex URL (String) that is used to demonstrate S3Uri capabilities. + * @param s3Client - An S3Client through which you acquire an S3Uri instance. + * @param s3ObjectUrl - A complex URL (String) that is used to demonstrate S3Uri + * capabilities. */ public static void parseS3UriExample(S3Client s3Client, String s3ObjectUrl) { logger.info(s3ObjectUrl); - //Console output: 'https://s3.us-west-1.amazonaws.com/myBucket/resources/doc.txt?versionId=abc123&partNumber=77&partNumber=88'. + // Console output: + // 'https://s3.us-west-1.amazonaws.com/myBucket/resources/doc.txt?versionId=abc123&partNumber=77&partNumber=88'. // Create an S3Utilities object using the configuration of the s3Client. S3Utilities s3Utilities = s3Client.utilities(); @@ -55,7 +53,8 @@ public static void parseS3UriExample(S3Client s3Client, String s3ObjectUrl) { URI uri = URI.create(s3ObjectUrl); S3Uri s3Uri = s3Utilities.parseUri(uri); - // If the URI contains no value for the Region, bucket or key, the SDK returns an empty Optional. + // If the URI contains no value for the Region, bucket or key, the SDK returns + // an empty Optional. // The SDK returns decoded URI values. Region region = s3Uri.region().orElse(null); @@ -77,9 +76,11 @@ public static void parseS3UriExample(S3Client s3Client, String s3ObjectUrl) { // If the URI contains no query parameters, the SDK returns an empty map. Map> queryParams = s3Uri.rawQueryParameters(); log("rawQueryParameters", queryParams); - // Console output: 'rawQueryParameters: {versionId=[abc123], partNumber=[77, 88]}'. + // Console output: 'rawQueryParameters: {versionId=[abc123], partNumber=[77, + // 88]}'. - // Retrieve the first or all values for a query parameter as shown in the following code. + // Retrieve the first or all values for a query parameter as shown in the + // following code. String versionId = s3Uri.firstMatchingRawQueryParameter("versionId").orElse(null); log("firstMatchingRawQueryParameter-versionId", versionId); // Console output: 'firstMatchingRawQueryParameter-versionId: abc123'. @@ -92,16 +93,20 @@ public static void parseS3UriExample(S3Client s3Client, String s3ObjectUrl) { log("firstMatchingRawQueryParameter", partNumbers); // Console output: 'firstMatchingRawQueryParameter: [77, 88]'. -/* - Object keys and query parameters with reserved or unsafe characters, must be URL-encoded. - For example replace whitespace " " with "%20". - Valid: "https://s3.us-west-1.amazonaws.com/myBucket/object%20key?query=%5Bbrackets%5D" - Invalid: "https://s3.us-west-1.amazonaws.com/myBucket/object key?query=[brackets]" - - Virtual-hosted-style URIs with bucket names that contain a dot, ".", the dot must not be URL-encoded. - Valid: "https://my.Bucket.s3.us-west-1.amazonaws.com/key" - Invalid: "https://my%2EBucket.s3.us-west-1.amazonaws.com/key" -*/ + /* + * Object keys and query parameters with reserved or unsafe characters, must be + * URL-encoded. + * For example replace whitespace " " with "%20". + * Valid: + * "https://s3.us-west-1.amazonaws.com/myBucket/object%20key?query=%5Bbrackets%5D" + * Invalid: + * "https://s3.us-west-1.amazonaws.com/myBucket/object key?query=[brackets]" + * + * Virtual-hosted-style URIs with bucket names that contain a dot, ".", the dot + * must not be URL-encoded. + * Valid: "https://my.Bucket.s3.us-west-1.amazonaws.com/key" + * Invalid: "https://my%2EBucket.s3.us-west-1.amazonaws.com/key" + */ } private static void log(String s3UriElement, Object element) { @@ -113,4 +118,3 @@ private static void log(String s3UriElement, Object element) { } // snippet-end:[s3.java2.scenario_uriparsing.main] } - diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/PerformMultiPartUpload.java b/javav2/example_code/s3/src/main/java/com/example/s3/PerformMultiPartUpload.java index 54a5f179a71..4d392d216c5 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/PerformMultiPartUpload.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/PerformMultiPartUpload.java @@ -1,7 +1,6 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.s3; // snippet-start:[s3.java2.performMultiPartUpload.import] @@ -87,10 +86,9 @@ public void multipartUploadWithTransferManager(String filePath) { public void multipartUploadWithS3Client(String filePath) { // Initiate the multipart upload. - CreateMultipartUploadResponse createMultipartUploadResponse = - s3Client.createMultipartUpload(b -> b - .bucket(bucketName) - .key(key)); + CreateMultipartUploadResponse createMultipartUploadResponse = s3Client.createMultipartUpload(b -> b + .bucket(bucketName) + .key(key)); String uploadId = createMultipartUploadResponse.uploadId(); // Upload the parts of the file. diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/PresignedSwing.java b/javav2/example_code/s3/src/main/java/com/example/s3/PresignedSwing.java index 38bca6eb2d5..65b2a2642e0 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/PresignedSwing.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/PresignedSwing.java @@ -1,15 +1,5 @@ -//snippet-sourcedescription:[PresignedSwing.java demonstrates how to a presigned object using a Java Swing app.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon S3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[12/15/2021] -//snippet-sourceauthor:[scmacdon-aws] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; @@ -23,32 +13,33 @@ import java.net.URL; class Swing implements ActionListener { - JFrame frame=new JFrame(); - JButton button=new JButton("Get Presigned Amazon S3 Object"); + JFrame frame = new JFrame(); + JButton button = new JButton("Get Presigned Amazon S3 Object"); - Swing(){ + Swing() { prepareGUI(); buttonProperties(); } - public void prepareGUI(){ + public void prepareGUI() { frame.setTitle("My Window"); frame.getContentPane().setLayout(null); frame.setVisible(true); - frame.setBounds(200,200,400,400); + frame.setBounds(200, 200, 400, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } - public void buttonProperties(){ - button.setBounds(130,200,200,100); + + public void buttonProperties() { + button.setBounds(130, 200, 200, 100); frame.add(button); button.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { - //Get a presigned PDF from an Amazon S3 bucket. + // Get a presigned PDF from an Amazon S3 bucket. try { - URL url = new URL("") ; + URL url = new URL(""); InputStream in; in = url.openStream(); FileOutputStream fos = new FileOutputStream("C:\\AWS\\allpeople.png"); diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/PutBucketLogging.java b/javav2/example_code/s3/src/main/java/com/example/s3/PutBucketLogging.java index e0178f38354..d52fcf1e4bf 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/PutBucketLogging.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/PutBucketLogging.java @@ -1,10 +1,6 @@ -//snippet-sourcedescription:[PutBucketLogging.java demonstrates how to set the logging parameters for an Amazon Simple Storage Service (Amazon S3) bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.s3; // snippet-start:[s3.java2.s3_put_log.main] @@ -25,82 +21,83 @@ // snippet-end:[s3.java2.s3_put_log.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class PutBucketLogging { - public static void main(String[] args) { - final String usage = """ - - Usage: - \s - - Where: - bucketName - The Amazon S3 bucket to upload an object into. - targetBucket - The target bucket . - """; - - if (args.length != 3) { - System.out.println(usage); - System.exit(1); + public static void main(String[] args) { + final String usage = """ + + Usage: + \s + + Where: + bucketName - The Amazon S3 bucket to upload an object into. + targetBucket - The target bucket . + """; + + if (args.length != 3) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String targetBucket = args[1]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + setlogRequest(s3, bucketName, targetBucket); + s3.close(); } - String bucketName = args[0]; - String targetBucket = args[1]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - setlogRequest(s3, bucketName, targetBucket); - s3.close(); - } - - public static void setlogRequest(S3Client s3, String bucketName, String targetBucket) { - try { - GetBucketAclRequest aclRequest = GetBucketAclRequest.builder() - .bucket(targetBucket) - .build(); - - s3.getBucketAcl(aclRequest); - Grantee grantee = Grantee.builder() - .type(Type.GROUP) - .uri("http://acs.amazonaws.com/groups/s3/LogDelivery") - .build(); - - TargetGrant targetGrant = TargetGrant.builder() - .grantee(grantee) - .permission(BucketLogsPermission.FULL_CONTROL) - .build(); - - List granteeList = new ArrayList<>(); - granteeList.add(targetGrant); - - LoggingEnabled loggingEnabled = LoggingEnabled.builder() - .targetBucket(targetBucket) - .targetGrants(granteeList) - .build(); - - BucketLoggingStatus loggingStatus = BucketLoggingStatus.builder() - .loggingEnabled(loggingEnabled) - .build(); - - PutBucketLoggingRequest loggingRequest = PutBucketLoggingRequest.builder() - .bucket(bucketName) - .expectedBucketOwner("814548047983") - .bucketLoggingStatus(loggingStatus) - .build(); - - s3.putBucketLogging(loggingRequest); - System.out.println("Enabling logging for the target bucket " + targetBucket); - - } catch (S3Exception e) { - System.err.println(e.getMessage()); - System.exit(1); + public static void setlogRequest(S3Client s3, String bucketName, String targetBucket) { + try { + GetBucketAclRequest aclRequest = GetBucketAclRequest.builder() + .bucket(targetBucket) + .build(); + + s3.getBucketAcl(aclRequest); + Grantee grantee = Grantee.builder() + .type(Type.GROUP) + .uri("http://acs.amazonaws.com/groups/s3/LogDelivery") + .build(); + + TargetGrant targetGrant = TargetGrant.builder() + .grantee(grantee) + .permission(BucketLogsPermission.FULL_CONTROL) + .build(); + + List granteeList = new ArrayList<>(); + granteeList.add(targetGrant); + + LoggingEnabled loggingEnabled = LoggingEnabled.builder() + .targetBucket(targetBucket) + .targetGrants(granteeList) + .build(); + + BucketLoggingStatus loggingStatus = BucketLoggingStatus.builder() + .loggingEnabled(loggingEnabled) + .build(); + + PutBucketLoggingRequest loggingRequest = PutBucketLoggingRequest.builder() + .bucket(bucketName) + .expectedBucketOwner("814548047983") + .bucketLoggingStatus(loggingStatus) + .build(); + + s3.putBucketLogging(loggingRequest); + System.out.println("Enabling logging for the target bucket " + targetBucket); + + } catch (S3Exception e) { + System.err.println(e.getMessage()); + System.exit(1); + } } - } } // snippet-end:[s3.java2.s3_put_log.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/PutObject.java b/javav2/example_code/s3/src/main/java/com/example/s3/PutObject.java index 3ac6bb6ea6d..a55e81965c1 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/PutObject.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/PutObject.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[PutObject.java demonstrates how to upload an object to an Amazon Simple Storage Service (Amazon S3) bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.s3; // snippet-start:[s3.java2.s3_object_upload.main] @@ -21,7 +16,8 @@ // snippet-end:[s3.java2.s3_object_upload.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,14 +28,14 @@ public class PutObject { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - bucketName - The Amazon S3 bucket to upload an object into. - objectKey - The object to upload (for example, book.pdf). - objectPath - The path where the file is located (for example, C:/AWS/book2.pdf).\s - """; + Where: + bucketName - The Amazon S3 bucket to upload an object into. + objectKey - The object to upload (for example, book.pdf). + objectPath - The path where the file is located (for example, C:/AWS/book2.pdf).\s + """; if (args.length != 3) { System.out.println(usage); @@ -51,23 +47,24 @@ public static void main(String[] args) { String objectPath = args[2]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); putS3Object(s3, bucketName, objectKey, objectPath); s3.close(); } - // This example uses RequestBody.fromFile to avoid loading the whole file into memory. + // This example uses RequestBody.fromFile to avoid loading the whole file into + // memory. public static void putS3Object(S3Client s3, String bucketName, String objectKey, String objectPath) { try { Map metadata = new HashMap<>(); metadata.put("x-amz-meta-myVal", "test"); PutObjectRequest putOb = PutObjectRequest.builder() - .bucket(bucketName) - .key(objectKey) - .metadata(metadata) - .build(); + .bucket(bucketName) + .key(objectKey) + .metadata(metadata) + .build(); s3.putObject(putOb, RequestBody.fromFile(new File(objectPath))); System.out.println("Successfully placed " + objectKey + " into bucket " + bucketName); diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/PutObjectMetadata.java b/javav2/example_code/s3/src/main/java/com/example/s3/PutObjectMetadata.java index fcc7f36ff29..9b7de61188d 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/PutObjectMetadata.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/PutObjectMetadata.java @@ -1,10 +1,6 @@ -//snippet-sourcedescription:[PutObjectMetadata.java demonstrates how to upload an object with metadata to an Amazon Simple Storage Service (Amazon S3) bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.s3; // snippet-start:[s3.java2.s3_object_upload.metadata.main] @@ -20,7 +16,8 @@ // snippet-end:[s3.java2.s3_object_upload.metadata.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,14 +27,14 @@ public class PutObjectMetadata { public static void main(String[] args) { final String USAGE = """ - Usage: - \s + Usage: + \s - Where: - bucketName - The Amazon S3 bucket to upload an object into. - objectKey - The object to upload (for example, book.pdf). - objectPath - The path where the file is located (for example, C:/AWS/book2.pdf).\s - """; + Where: + bucketName - The Amazon S3 bucket to upload an object into. + objectKey - The object to upload (for example, book.pdf). + objectPath - The path where the file is located (for example, C:/AWS/book2.pdf).\s + """; if (args.length != 3) { System.out.println(USAGE); @@ -51,14 +48,15 @@ public static void main(String[] args) { System.out.println(" in bucket: " + bucketName); Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); putS3Object(s3, bucketName, objectKey, objectPath); s3.close(); } - // This example uses RequestBody.fromFile to avoid loading the whole file into memory. + // This example uses RequestBody.fromFile to avoid loading the whole file into + // memory. public static void putS3Object(S3Client s3, String bucketName, String objectKey, String objectPath) { try { Map metadata = new HashMap<>(); @@ -66,10 +64,10 @@ public static void putS3Object(S3Client s3, String bucketName, String objectKey, metadata.put("version", "1.0.0.0"); PutObjectRequest putOb = PutObjectRequest.builder() - .bucket(bucketName) - .key(objectKey) - .metadata(metadata) - .build(); + .bucket(bucketName) + .key(objectKey) + .metadata(metadata) + .build(); s3.putObject(putOb, RequestBody.fromFile(new File(objectPath))); System.out.println("Successfully placed " + objectKey + " into bucket " + bucketName); diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/PutObjectRetention.java b/javav2/example_code/s3/src/main/java/com/example/s3/PutObjectRetention.java index 34e91fe0b42..9ddfc8e0cac 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/PutObjectRetention.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/PutObjectRetention.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[PutObjectRetention demonstrates how to place an object retention configuration on an Amazon Simple Storage Service (Amazon S3) object.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; @@ -14,7 +8,7 @@ import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.PutObjectRetentionRequest; -import software.amazon.awssdk.services.s3.model.ObjectLockRetention ; +import software.amazon.awssdk.services.s3.model.ObjectLockRetention; import software.amazon.awssdk.services.s3.model.S3Exception; import java.time.Instant; import java.time.LocalDate; @@ -23,7 +17,8 @@ // snippet-end:[s3.java2.retention_object.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -34,13 +29,13 @@ public class PutObjectRetention { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - key - The name of the object (for example, book.pdf).\s - bucketName - The Amazon S3 bucket name that contains the object (for example, bucket1).\s - """; + Where: + key - The name of the object (for example, book.pdf).\s + bucketName - The Amazon S3 bucket name that contains the object (for example, bucket1).\s + """; if (args.length != 2) { System.out.println(usage); @@ -51,8 +46,8 @@ public static void main(String[] args) { String bucketName = args[1]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); setRentionPeriod(s3, key, bucketName); s3.close(); @@ -65,18 +60,19 @@ public static void setRentionPeriod(S3Client s3, String key, String bucket) { Instant instant = localDateTime.toInstant(ZoneOffset.UTC); ObjectLockRetention lockRetention = ObjectLockRetention.builder() - .mode("COMPLIANCE") - .retainUntilDate(instant) - .build(); + .mode("COMPLIANCE") + .retainUntilDate(instant) + .build(); PutObjectRetentionRequest retentionRequest = PutObjectRetentionRequest.builder() - .bucket(bucket) - .key(key) - .bypassGovernanceRetention(true) - .retention(lockRetention) - .build(); - - // To set Retention on an object, the Amazon S3 bucket must support object locking, otherwise an exception is thrown. + .bucket(bucket) + .key(key) + .bypassGovernanceRetention(true) + .retention(lockRetention) + .build(); + + // To set Retention on an object, the Amazon S3 bucket must support object + // locking, otherwise an exception is thrown. s3.putObjectRetention(retentionRequest); System.out.print("An object retention configuration was successfully placed on the object"); @@ -87,5 +83,3 @@ public static void setRentionPeriod(S3Client s3, String key, String bucket) { } } // snippet-end:[s3.java2.retention_object.main] - - diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/RestoreObject.java b/javav2/example_code/s3/src/main/java/com/example/s3/RestoreObject.java index 16b46775217..2116d2d0cea 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/RestoreObject.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/RestoreObject.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[RestoreObject.java demonstrates how to restores an archived copy of an object back into an Amazon S3 Amazon Simple Storage Service (Amazon S3) bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; @@ -35,14 +28,14 @@ public class RestoreObject { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - bucketName - The Amazon S3 bucket name.\s - keyName - The key name of an object with a Storage class value of Glacier.\s - expectedBucketOwner - The account that owns the bucket (you can obtain this value from the AWS Management Console).\s - """; + Where: + bucketName - The Amazon S3 bucket name.\s + keyName - The key name of an object with a Storage class value of Glacier.\s + expectedBucketOwner - The account that owns the bucket (you can obtain this value from the AWS Management Console).\s + """; if (args.length != 3) { System.out.println(usage); @@ -54,8 +47,8 @@ public static void main(String[] args) { String expectedBucketOwner = args[2]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); restoreS3Object(s3, bucketName, keyName, expectedBucketOwner); s3.close(); @@ -64,16 +57,16 @@ public static void main(String[] args) { public static void restoreS3Object(S3Client s3, String bucketName, String keyName, String expectedBucketOwner) { try { RestoreRequest restoreRequest = RestoreRequest.builder() - .days(10) - .glacierJobParameters(GlacierJobParameters.builder().tier(Tier.STANDARD).build()) - .build(); + .days(10) + .glacierJobParameters(GlacierJobParameters.builder().tier(Tier.STANDARD).build()) + .build(); RestoreObjectRequest objectRequest = RestoreObjectRequest.builder() - .expectedBucketOwner(expectedBucketOwner) - .bucket(bucketName) - .key(keyName) - .restoreRequest(restoreRequest) - .build(); + .expectedBucketOwner(expectedBucketOwner) + .bucket(bucketName) + .key(keyName) + .restoreRequest(restoreRequest) + .build(); s3.restoreObject(objectRequest); diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/S3BucketDeletion.java b/javav2/example_code/s3/src/main/java/com/example/s3/S3BucketDeletion.java index 1209287c506..2b81958bdd1 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/S3BucketDeletion.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/S3BucketDeletion.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[S3BucketDeletion.java demonstrates how to delete an empty Amazon Simple Storage Service (Amazon S3) bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.s3; // snippet-start:[s3.java2.bucket_deletion.main] @@ -24,7 +19,8 @@ // snippet-end:[s3.java2.bucket_deletion.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -34,12 +30,12 @@ public class S3BucketDeletion { public static void main(String[] args) throws Exception { final String usage = """ - Usage: - + Usage: + - Where: - bucket - The bucket to delete (for example, bucket1).\s - """; + Where: + bucket - The bucket to delete (for example, bucket1).\s + """; if (args.length != 1) { System.out.println(usage); @@ -52,11 +48,11 @@ public static void main(String[] args) throws Exception { .region(region) .build(); - deleteObjectsInBucket(s3,bucket); + deleteObjectsInBucket(s3, bucket); s3.close(); } - public static void deleteObjectsInBucket (S3Client s3, String bucket) { + public static void deleteObjectsInBucket(S3Client s3, String bucket) { try { // To delete a bucket, all the objects in the bucket must be deleted first. ListObjectsV2Request listObjectsV2Request = ListObjectsV2Request.builder() @@ -85,4 +81,3 @@ public static void deleteObjectsInBucket (S3Client s3, String bucket) { } // snippet-end:[s3.java2.s3_bucket_deletion.delete_objects] // snippet-end:[s3.java2.bucket_deletion.main] - diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/S3BucketOps.java b/javav2/example_code/s3/src/main/java/com/example/s3/S3BucketOps.java index 1c3b74e3afe..637dfe93ff7 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/S3BucketOps.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/S3BucketOps.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[S3BucketOps.java demonstrates how to create, list and delete an Amazon Simple Storage Service (Amazon S3) bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; @@ -25,7 +20,8 @@ // snippet-start:[s3.java2.s3_bucket_ops.main] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -36,33 +32,33 @@ public static void main(String[] args) { // snippet-start:[s3.java2.s3_bucket_ops.region] Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); // snippet-end:[s3.java2.s3_bucket_ops.region] String bucket = "bucket" + System.currentTimeMillis(); System.out.println(bucket); createBucket(s3, bucket); - performOperations(s3, bucket) ; - } + performOperations(s3, bucket); + } // Create a bucket by using a S3Waiter object - public static void createBucket( S3Client s3Client, String bucketName) { + public static void createBucket(S3Client s3Client, String bucketName) { try { S3Waiter s3Waiter = s3Client.waiter(); CreateBucketRequest bucketRequest = CreateBucketRequest.builder() - .bucket(bucketName) - .build(); + .bucket(bucketName) + .build(); s3Client.createBucket(bucketRequest); HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder() - .bucket(bucketName) - .build(); + .bucket(bucketName) + .build(); // Wait until the bucket is created and print out the response. WaiterResponse waiterResponse = s3Waiter.waitUntilBucketExists(bucketRequestWait); waiterResponse.matched().response().ifPresent(System.out::println); - System.out.println(bucketName +" is ready"); + System.out.println(bucketName + " is ready"); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -80,15 +76,14 @@ public static void performOperations(S3Client s3, String bucket) { // snippet-end:[s3.java2.s3_bucket_ops.list_bucket] // Delete empty bucket. - // snippet-start:[s3.java2.s3_bucket_ops.delete_bucket] + // snippet-start:[s3.java2.s3_bucket_ops.delete_bucket] DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder() - .bucket(bucket) - .build(); + .bucket(bucket) + .build(); s3.deleteBucket(deleteBucketRequest); s3.close(); - // snippet-end:[s3.java2.s3_bucket_ops.delete_bucket] + // snippet-end:[s3.java2.s3_bucket_ops.delete_bucket] } } // snippet-end:[s3.java2.s3_bucket_ops.main] - diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/S3Cors.java b/javav2/example_code/s3/src/main/java/com/example/s3/S3Cors.java index c3ebf4cfe97..a88e1229f6e 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/S3Cors.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/S3Cors.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[S3Cors.java demonstrates how to manage cross-origin resource sharing (CORS) for an Amazon Simple Storage Service (Amazon S3) bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; @@ -25,7 +19,8 @@ // snippet-end:[s3.java2.cors.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -35,13 +30,13 @@ public class S3Cors { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - bucketName - The Amazon S3 bucket to upload an object into. - accountId - The id of the account that owns the Amazon S3 bucket. - """; + Where: + bucketName - The Amazon S3 bucket to upload an object into. + accountId - The id of the account that owns the Amazon S3 bucket. + """; if (args.length != 2) { System.out.println(usage); @@ -52,8 +47,8 @@ public static void main(String[] args) { String accountId = args[1]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); setCorsInformation(s3, bucketName, accountId); getBucketCorsInformation(s3, bucketName, accountId); @@ -64,9 +59,9 @@ public static void main(String[] args) { public static void deleteBucketCorsInformation(S3Client s3, String bucketName, String accountId) { try { DeleteBucketCorsRequest bucketCorsRequest = DeleteBucketCorsRequest.builder() - .bucket(bucketName) - .expectedBucketOwner(accountId) - .build(); + .bucket(bucketName) + .expectedBucketOwner(accountId) + .build(); s3.deleteBucketCors(bucketCorsRequest); @@ -79,9 +74,9 @@ public static void deleteBucketCorsInformation(S3Client s3, String bucketName, S public static void getBucketCorsInformation(S3Client s3, String bucketName, String accountId) { try { GetBucketCorsRequest bucketCorsRequest = GetBucketCorsRequest.builder() - .bucket(bucketName) - .expectedBucketOwner(accountId) - .build(); + .bucket(bucketName) + .expectedBucketOwner(accountId) + .build(); GetBucketCorsResponse corsResponse = s3.getBucketCors(bucketCorsRequest); List corsRules = corsResponse.corsRules(); @@ -108,21 +103,21 @@ public static void setCorsInformation(S3Client s3, String bucketName, String acc try { // Define CORS rules. CORSRule corsRule = CORSRule.builder() - .allowedMethods(allowMethods) - .allowedOrigins(allowOrigins) - .build(); + .allowedMethods(allowMethods) + .allowedOrigins(allowOrigins) + .build(); List corsRules = new ArrayList<>(); corsRules.add(corsRule); CORSConfiguration configuration = CORSConfiguration.builder() - .corsRules(corsRules) - .build(); + .corsRules(corsRules) + .build(); PutBucketCorsRequest putBucketCorsRequest = PutBucketCorsRequest.builder() - .bucket(bucketName) - .corsConfiguration(configuration) - .expectedBucketOwner(accountId) - .build(); + .bucket(bucketName) + .corsConfiguration(configuration) + .expectedBucketOwner(accountId) + .build(); s3.putBucketCors(putBucketCorsRequest); diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/S3Log.java b/javav2/example_code/s3/src/main/java/com/example/s3/S3Log.java index af997dda387..e45c7a79a67 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/S3Log.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/S3Log.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[S3log.java demonstrates how to log information.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; @@ -21,7 +16,8 @@ // snippet-start:[s3.java2.logging.main] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,7 +25,8 @@ */ public class S3Log { private static final Logger logger = LogManager.getLogger(S3Log.class); - public static void main (String[] args) { + + public static void main(String[] args) { System.out.println("testing logging setup for " + S3Log.class); Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/S3ObjectOperations.java b/javav2/example_code/s3/src/main/java/com/example/s3/S3ObjectOperations.java index 94617d74f77..f0aef8893ed 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/S3ObjectOperations.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/S3ObjectOperations.java @@ -1,15 +1,5 @@ -//snippet-sourcedescription:[S3ObjectOperations.java demonstrates how to create an Amazon Simple Storage Service (Amazon S3) bucket by using a S3Waiter object. In addition, this code example demonstrates how to perform other tasks such as uploading an object into an Amazon S3 bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Code Sample] -//snippet-service:[Amazon S3] -//snippet-sourcetype:[full-example] -//snippet-sourcedate:[09/27/2021] -//snippet-sourceauthor:[scmacdon-aws] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; // snippet-start:[s3.java2.s3_object_operations.complete] @@ -47,224 +37,232 @@ // snippet-start:[s3.java2.s3_object_operations.main] /** - * To run this AWS code example, ensure that you have setup your development environment, including your AWS credentials. + * To run this AWS code example, ensure that you have setup your development + * environment, including your AWS credentials. * * For information, see this documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class S3ObjectOperations { - private static S3Client s3; - public static void main(String[] args) throws IOException { - final String USAGE = """ - - Usage: - - - Where: - bucketName - the Amazon S3 bucket to create. - key - the key to use. - """; + private static S3Client s3; + + public static void main(String[] args) throws IOException { + final String USAGE = """ + + Usage: + + + Where: + bucketName - the Amazon S3 bucket to create. + key - the key to use. + """; + + if (args.length != 2) { + System.out.println(USAGE); + System.exit(1); + } + + String bucketName = args[0]; + String key = args[1]; + + // snippet-start:[s3.java2.s3_object_operations.upload] + Region region = Region.US_WEST_2; + s3 = S3Client.builder() + .region(region) + .build(); + + createBucket(s3, bucketName, region); + + PutObjectRequest objectRequest = PutObjectRequest.builder() + .bucket(bucketName) + .key(key) + .build(); + + s3.putObject(objectRequest, RequestBody.fromByteBuffer(getRandomByteBuffer(10_000))); + // snippet-end:[s3.java2.s3_object_operations.upload] + + // Multipart upload example + String multipartKey = "multiPartKey"; + multipartUpload(bucketName, multipartKey); + + // snippet-start:[s3.java2.s3_object_operations.pagination] + ListObjectsV2Request listObjectsReqManual = ListObjectsV2Request.builder() + .bucket(bucketName) + .maxKeys(1) + .build(); + + boolean done = false; + while (!done) { + ListObjectsV2Response listObjResponse = s3.listObjectsV2(listObjectsReqManual); + for (S3Object content : listObjResponse.contents()) { + System.out.println(content.key()); + } + + if (listObjResponse.nextContinuationToken() == null) { + done = true; + } + + listObjectsReqManual = listObjectsReqManual.toBuilder() + .continuationToken(listObjResponse.nextContinuationToken()) + .build(); + } + // snippet-end:[s3.java2.s3_object_operations.pagination] + // snippet-start:[s3.java2.s3_object_operations.iterative] + ListObjectsV2Request listReq = ListObjectsV2Request.builder() + .bucket(bucketName) + .maxKeys(1) + .build(); + + ListObjectsV2Iterable listRes = s3.listObjectsV2Paginator(listReq); + // Process response pages + listRes.stream() + .flatMap(r -> r.contents().stream()) + .forEach(content -> System.out + .println(" Key: " + content.key() + " size = " + content.size())); + + // snippet-end:[s3.java2.s3_object_operations.iterative] + // snippet-start:[s3.java2.s3_object_operations.stream] + // Helper method to work with paginated collection of items directly. + listRes.contents().stream() + .forEach(content -> System.out + .println(" Key: " + content.key() + " size = " + content.size())); + + // snippet-end:[s3.java2.s3_object_operations.stream] + // snippet-start:[s3.java2.s3_object_operations.forloop] + for (S3Object content : listRes.contents()) { + System.out.println(" Key: " + content.key() + " size = " + content.size()); + } + // snippet-end:[s3.java2.s3_object_operations.forloop] + + // snippet-start:[s3.java2.s3_object_operations.download] + GetObjectRequest getObjectRequest = GetObjectRequest.builder() + .bucket(bucketName) + .key(key) + .build(); + + s3.getObject(getObjectRequest); + // snippet-end:[s3.java2.s3_object_operations.download] + + // snippet-start:[s3.java2.s3_object_operations.delete] + DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder() + .bucket(bucketName) + .key(key) + .build(); + + s3.deleteObject(deleteObjectRequest); + // snippet-end:[s3.java2.s3_object_operations.delete] + + // Delete an object + deleteObjectRequest = DeleteObjectRequest.builder() + .bucket(bucketName) + .key(multipartKey) + .build(); + + s3.deleteObject(deleteObjectRequest); + deleteBucket(s3, bucketName); + System.out.println("Done"); + } - if (args.length != 2) { - System.out.println(USAGE); - System.exit(1); + // Create a bucket by using a S3Waiter object + public static void createBucket(S3Client s3Client, String bucketName, Region region) { + + S3Waiter s3Waiter = s3Client.waiter(); + + try { + CreateBucketRequest bucketRequest = CreateBucketRequest.builder() + .bucket(bucketName) + .createBucketConfiguration( + CreateBucketConfiguration.builder() + .locationConstraint(region.id()) + .build()) + .build(); + + s3Client.createBucket(bucketRequest); + HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder() + .bucket(bucketName) + .build(); + + // Wait until the bucket is created and print out the response + WaiterResponse waiterResponse = s3Waiter + .waitUntilBucketExists(bucketRequestWait); + waiterResponse.matched().response().ifPresent(System.out::println); + System.out.println(bucketName + " is ready"); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } } - String bucketName = args[0]; - String key = args[1]; - - // snippet-start:[s3.java2.s3_object_operations.upload] - Region region = Region.US_WEST_2; - s3 = S3Client.builder() - .region(region) - .build(); - - createBucket(s3, bucketName, region); - - PutObjectRequest objectRequest = PutObjectRequest.builder() - .bucket(bucketName) - .key(key) - .build(); - - s3.putObject(objectRequest, RequestBody.fromByteBuffer(getRandomByteBuffer(10_000))); - // snippet-end:[s3.java2.s3_object_operations.upload] - - // Multipart upload example - String multipartKey = "multiPartKey"; - multipartUpload(bucketName, multipartKey); - - // snippet-start:[s3.java2.s3_object_operations.pagination] - ListObjectsV2Request listObjectsReqManual = ListObjectsV2Request.builder() - .bucket(bucketName) - .maxKeys(1) - .build(); - - boolean done = false; - while (!done) { - ListObjectsV2Response listObjResponse = s3.listObjectsV2(listObjectsReqManual); - for (S3Object content : listObjResponse.contents()) { - System.out.println(content.key()); - } - - if (listObjResponse.nextContinuationToken() == null) { - done = true; - } - - listObjectsReqManual = listObjectsReqManual.toBuilder() - .continuationToken(listObjResponse.nextContinuationToken()) - .build(); + public static void deleteBucket(S3Client client, String bucket) { + DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder() + .bucket(bucket) + .build(); + client.deleteBucket(deleteBucketRequest); } - // snippet-end:[s3.java2.s3_object_operations.pagination] - // snippet-start:[s3.java2.s3_object_operations.iterative] - ListObjectsV2Request listReq = ListObjectsV2Request.builder() - .bucket(bucketName) - .maxKeys(1) - .build(); - - ListObjectsV2Iterable listRes = s3.listObjectsV2Paginator(listReq); - // Process response pages - listRes.stream() - .flatMap(r -> r.contents().stream()) - .forEach(content -> System.out.println(" Key: " + content.key() + " size = " + content.size())); - - // snippet-end:[s3.java2.s3_object_operations.iterative] - // snippet-start:[s3.java2.s3_object_operations.stream] - // Helper method to work with paginated collection of items directly. - listRes.contents().stream() - .forEach(content -> System.out.println(" Key: " + content.key() + " size = " + content.size())); - - // snippet-end:[s3.java2.s3_object_operations.stream] - // snippet-start:[s3.java2.s3_object_operations.forloop] - for (S3Object content : listRes.contents()) { - System.out.println(" Key: " + content.key() + " size = " + content.size()); + + /** + * Upload an object in parts + */ + private static void multipartUpload(String bucketName, String key) throws IOException { + + int mB = 1024 * 1024; + // snippet-start:[s3.java2.s3_object_operations.upload_multi_part] + // First create a multipart upload and get the upload id + CreateMultipartUploadRequest createMultipartUploadRequest = CreateMultipartUploadRequest.builder() + .bucket(bucketName) + .key(key) + .build(); + + CreateMultipartUploadResponse response = s3.createMultipartUpload(createMultipartUploadRequest); + String uploadId = response.uploadId(); + System.out.println(uploadId); + + // Upload all the different parts of the object + UploadPartRequest uploadPartRequest1 = UploadPartRequest.builder() + .bucket(bucketName) + .key(key) + .uploadId(uploadId) + .partNumber(1).build(); + + String etag1 = s3 + .uploadPart(uploadPartRequest1, RequestBody.fromByteBuffer(getRandomByteBuffer(5 * mB))) + .eTag(); + + CompletedPart part1 = CompletedPart.builder().partNumber(1).eTag(etag1).build(); + + UploadPartRequest uploadPartRequest2 = UploadPartRequest.builder().bucket(bucketName).key(key) + .uploadId(uploadId) + .partNumber(2).build(); + String etag2 = s3 + .uploadPart(uploadPartRequest2, RequestBody.fromByteBuffer(getRandomByteBuffer(3 * mB))) + .eTag(); + CompletedPart part2 = CompletedPart.builder().partNumber(2).eTag(etag2).build(); + + // Finally call completeMultipartUpload operation to tell S3 to merge all + // uploaded + // parts and finish the multipart operation. + CompletedMultipartUpload completedMultipartUpload = CompletedMultipartUpload.builder() + .parts(part1, part2) + .build(); + + CompleteMultipartUploadRequest completeMultipartUploadRequest = CompleteMultipartUploadRequest.builder() + .bucket(bucketName) + .key(key) + .uploadId(uploadId) + .multipartUpload(completedMultipartUpload) + .build(); + + s3.completeMultipartUpload(completeMultipartUploadRequest); + // snippet-end:[s3.java2.s3_object_operations.upload_multi_part] } - // snippet-end:[s3.java2.s3_object_operations.forloop] - - // snippet-start:[s3.java2.s3_object_operations.download] - GetObjectRequest getObjectRequest = GetObjectRequest.builder() - .bucket(bucketName) - .key(key) - .build(); - - s3.getObject(getObjectRequest); - // snippet-end:[s3.java2.s3_object_operations.download] - - // snippet-start:[s3.java2.s3_object_operations.delete] - DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder() - .bucket(bucketName) - .key(key) - .build(); - - s3.deleteObject(deleteObjectRequest); - // snippet-end:[s3.java2.s3_object_operations.delete] - - // Delete an object - deleteObjectRequest = DeleteObjectRequest.builder() - .bucket(bucketName) - .key(multipartKey) - .build(); - - s3.deleteObject(deleteObjectRequest); - deleteBucket(s3,bucketName); - System.out.println("Done"); - } - - // Create a bucket by using a S3Waiter object - public static void createBucket( S3Client s3Client, String bucketName, Region region) { - - S3Waiter s3Waiter = s3Client.waiter(); - - try { - CreateBucketRequest bucketRequest = CreateBucketRequest.builder() - .bucket(bucketName) - .createBucketConfiguration( - CreateBucketConfiguration.builder() - .locationConstraint(region.id()) - .build()) - .build(); - - s3Client.createBucket(bucketRequest); - HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder() - .bucket(bucketName) - .build(); - - // Wait until the bucket is created and print out the response - WaiterResponse waiterResponse = s3Waiter.waitUntilBucketExists(bucketRequestWait); - waiterResponse.matched().response().ifPresent(System.out::println); - System.out.println(bucketName +" is ready"); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + + private static ByteBuffer getRandomByteBuffer(int size) throws IOException { + byte[] b = new byte[size]; + new Random().nextBytes(b); + return ByteBuffer.wrap(b); } - } - - public static void deleteBucket(S3Client client, String bucket) { - DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder() - .bucket(bucket) - .build(); - client.deleteBucket(deleteBucketRequest); - } - - /** - * Upload an object in parts - */ - private static void multipartUpload(String bucketName, String key) throws IOException { - - int mB = 1024 * 1024; - // snippet-start:[s3.java2.s3_object_operations.upload_multi_part] - // First create a multipart upload and get the upload id - CreateMultipartUploadRequest createMultipartUploadRequest = CreateMultipartUploadRequest.builder() - .bucket(bucketName) - .key(key) - .build(); - - CreateMultipartUploadResponse response = s3.createMultipartUpload(createMultipartUploadRequest); - String uploadId = response.uploadId(); - System.out.println(uploadId); - - // Upload all the different parts of the object - UploadPartRequest uploadPartRequest1 = UploadPartRequest.builder() - .bucket(bucketName) - .key(key) - .uploadId(uploadId) - .partNumber(1).build(); - - String etag1 = s3.uploadPart(uploadPartRequest1, RequestBody.fromByteBuffer(getRandomByteBuffer(5 * mB))).eTag(); - - CompletedPart part1 = CompletedPart.builder().partNumber(1).eTag(etag1).build(); - - UploadPartRequest uploadPartRequest2 = UploadPartRequest.builder().bucket(bucketName).key(key) - .uploadId(uploadId) - .partNumber(2).build(); - String etag2 = s3.uploadPart(uploadPartRequest2, RequestBody.fromByteBuffer(getRandomByteBuffer(3 * mB))).eTag(); - CompletedPart part2 = CompletedPart.builder().partNumber(2).eTag(etag2).build(); - - - // Finally call completeMultipartUpload operation to tell S3 to merge all uploaded - // parts and finish the multipart operation. - CompletedMultipartUpload completedMultipartUpload = CompletedMultipartUpload.builder() - .parts(part1, part2) - .build(); - - CompleteMultipartUploadRequest completeMultipartUploadRequest = - CompleteMultipartUploadRequest.builder() - .bucket(bucketName) - .key(key) - .uploadId(uploadId) - .multipartUpload(completedMultipartUpload) - .build(); - - s3.completeMultipartUpload(completeMultipartUploadRequest); - // snippet-end:[s3.java2.s3_object_operations.upload_multi_part] - } - - private static ByteBuffer getRandomByteBuffer(int size) throws IOException { - byte[] b = new byte[size]; - new Random().nextBytes(b); - return ByteBuffer.wrap(b); - } } // snippet-end:[s3.java2.s3_object_operations.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/S3Scenario.java b/javav2/example_code/s3/src/main/java/com/example/s3/S3Scenario.java index da22072275f..f6b3654d885 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/S3Scenario.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/S3Scenario.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[S3Scenario.java demonstrates how to perform various Amazon Simple Storage Service (Amazon S3) operations.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; @@ -50,39 +44,41 @@ // snippet-start:[s3.java2.s3_scenario.main] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * - * For more information, see the following documentation topic: + * For more information, see the following documentation topic: * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * This Java code example performs the following tasks: + * This Java code example performs the following tasks: * - * 1. Creates an Amazon S3 bucket. - * 2. Uploads an object to the bucket. - * 3. Downloads the object to another local file. - * 4. Uploads an object using multipart upload. - * 5. List all objects located in the Amazon S3 bucket. - * 6. Copies the object to another Amazon S3 bucket. - * 7. Deletes the object from the Amazon S3 bucket. - * 8. Deletes the Amazon S3 bucket. + * 1. Creates an Amazon S3 bucket. + * 2. Uploads an object to the bucket. + * 3. Downloads the object to another local file. + * 4. Uploads an object using multipart upload. + * 5. List all objects located in the Amazon S3 bucket. + * 6. Copies the object to another Amazon S3 bucket. + * 7. Deletes the object from the Amazon S3 bucket. + * 8. Deletes the Amazon S3 bucket. */ public class S3Scenario { public static final String DASHES = new String(new char[80]).replace("\0", "-"); + public static void main(String[] args) throws IOException { final String usage = """ - Usage: - + Usage: + - Where: - bucketName - The Amazon S3 bucket to create. - key - The key to use. - objectPath - The path where the file is located (for example, C:/AWS/book2.pdf). - savePath - The path where the file is saved after it's downloaded (for example, C:/AWS/book2.pdf). - toBucket - An Amazon S3 bucket to where an object is copied to (for example, C:/AWS/book2.pdf).\s - """; + Where: + bucketName - The Amazon S3 bucket to create. + key - The key to use. + objectPath - The path where the file is located (for example, C:/AWS/book2.pdf). + savePath - The path where the file is saved after it's downloaded (for example, C:/AWS/book2.pdf). + toBucket - An Amazon S3 bucket to where an object is copied to (for example, C:/AWS/book2.pdf).\s + """; if (args.length != 5) { System.out.println(usage); @@ -93,11 +89,11 @@ public static void main(String[] args) throws IOException { String key = args[1]; String objectPath = args[2]; String savePath = args[3]; - String toBucket = args[4] ; + String toBucket = args[4]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); System.out.println(DASHES); System.out.println("Welcome to the Amazon S3 example scenario."); @@ -115,7 +111,7 @@ public static void main(String[] args) throws IOException { System.out.println(DASHES); System.out.println("3. Download the object to another local file."); - getObjectBytes (s3, bucketName, key, savePath); + getObjectBytes(s3, bucketName, key, savePath); System.out.println(DASHES); System.out.println(DASHES); @@ -127,12 +123,12 @@ public static void main(String[] args) throws IOException { System.out.println(DASHES); System.out.println("5. List all objects located in the Amazon S3 bucket."); listAllObjects(s3, bucketName); - anotherListExample(s3, bucketName) ; + anotherListExample(s3, bucketName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("6. Copy the object to another Amazon S3 bucket."); - copyBucketObject (s3, bucketName, key, toBucket); + copyBucketObject(s3, bucketName, key, toBucket); System.out.println(DASHES); System.out.println(DASHES); @@ -152,22 +148,22 @@ public static void main(String[] args) throws IOException { } // Create a bucket by using a S3Waiter object. - public static void createBucket( S3Client s3Client, String bucketName) { + public static void createBucket(S3Client s3Client, String bucketName) { try { S3Waiter s3Waiter = s3Client.waiter(); CreateBucketRequest bucketRequest = CreateBucketRequest.builder() - .bucket(bucketName) - .build(); + .bucket(bucketName) + .build(); s3Client.createBucket(bucketRequest); HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder() - .bucket(bucketName) - .build(); + .bucket(bucketName) + .build(); // Wait until the bucket is created and print out the response. WaiterResponse waiterResponse = s3Waiter.waitUntilBucketExists(bucketRequestWait); waiterResponse.matched().response().ifPresent(System.out::println); - System.out.println(bucketName +" is ready"); + System.out.println(bucketName + " is ready"); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); @@ -177,11 +173,11 @@ public static void createBucket( S3Client s3Client, String bucketName) { public static void deleteBucket(S3Client client, String bucket) { DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder() - .bucket(bucket) - .build(); + .bucket(bucket) + .build(); client.deleteBucket(deleteBucketRequest); - System.out.println(bucket +" was deleted."); + System.out.println(bucket + " was deleted."); } /** @@ -191,9 +187,9 @@ public static void multipartUpload(S3Client s3, String bucketName, String key) { int mB = 1024 * 1024; // First create a multipart upload and get the upload id. CreateMultipartUploadRequest createMultipartUploadRequest = CreateMultipartUploadRequest.builder() - .bucket(bucketName) - .key(key) - .build(); + .bucket(bucketName) + .key(key) + .build(); CreateMultipartUploadResponse response = s3.createMultipartUpload(createMultipartUploadRequest); String uploadId = response.uploadId(); @@ -201,32 +197,34 @@ public static void multipartUpload(S3Client s3, String bucketName, String key) { // Upload all the different parts of the object. UploadPartRequest uploadPartRequest1 = UploadPartRequest.builder() - .bucket(bucketName) - .key(key) - .uploadId(uploadId) - .partNumber(1).build(); + .bucket(bucketName) + .key(key) + .uploadId(uploadId) + .partNumber(1).build(); - String etag1 = s3.uploadPart(uploadPartRequest1, RequestBody.fromByteBuffer(getRandomByteBuffer(5 * mB))).eTag(); + String etag1 = s3.uploadPart(uploadPartRequest1, RequestBody.fromByteBuffer(getRandomByteBuffer(5 * mB))) + .eTag(); CompletedPart part1 = CompletedPart.builder().partNumber(1).eTag(etag1).build(); UploadPartRequest uploadPartRequest2 = UploadPartRequest.builder().bucket(bucketName).key(key) - .uploadId(uploadId) - .partNumber(2).build(); - String etag2 = s3.uploadPart(uploadPartRequest2, RequestBody.fromByteBuffer(getRandomByteBuffer(3 * mB))).eTag(); + .uploadId(uploadId) + .partNumber(2).build(); + String etag2 = s3.uploadPart(uploadPartRequest2, RequestBody.fromByteBuffer(getRandomByteBuffer(3 * mB))) + .eTag(); CompletedPart part2 = CompletedPart.builder().partNumber(2).eTag(etag2).build(); // Call completeMultipartUpload operation to tell S3 to merge all uploaded // parts and finish the multipart operation. CompletedMultipartUpload completedMultipartUpload = CompletedMultipartUpload.builder() - .parts(part1, part2) - .build(); + .parts(part1, part2) + .build(); CompleteMultipartUploadRequest completeMultipartUploadRequest = CompleteMultipartUploadRequest.builder() - .bucket(bucketName) - .key(key) - .uploadId(uploadId) - .multipartUpload(completedMultipartUpload) - .build(); + .bucket(bucketName) + .key(key) + .uploadId(uploadId) + .multipartUpload(completedMultipartUpload) + .build(); s3.completeMultipartUpload(completeMultipartUploadRequest); } @@ -237,13 +235,13 @@ private static ByteBuffer getRandomByteBuffer(int size) { return ByteBuffer.wrap(b); } - public static void getObjectBytes (S3Client s3, String bucketName, String keyName, String path ) { + public static void getObjectBytes(S3Client s3, String bucketName, String keyName, String path) { try { GetObjectRequest objectRequest = GetObjectRequest - .builder() - .key(keyName) - .bucket(bucketName) - .build(); + .builder() + .key(keyName) + .bucket(bucketName) + .build(); ResponseBytes objectBytes = s3.getObjectAsBytes(objectRequest); byte[] data = objectBytes.asByteArray(); @@ -263,21 +261,20 @@ public static void getObjectBytes (S3Client s3, String bucketName, String keyNam } } - public static void uploadLocalFile(S3Client s3, String bucketName, String key, String objectPath) { PutObjectRequest objectRequest = PutObjectRequest.builder() - .bucket(bucketName) - .key(key) - .build(); + .bucket(bucketName) + .key(key) + .build(); s3.putObject(objectRequest, RequestBody.fromFile(new File(objectPath))); } public static void listAllObjects(S3Client s3, String bucketName) { ListObjectsV2Request listObjectsReqManual = ListObjectsV2Request.builder() - .bucket(bucketName) - .maxKeys(1) - .build(); + .bucket(bucketName) + .maxKeys(1) + .build(); boolean done = false; while (!done) { @@ -291,27 +288,27 @@ public static void listAllObjects(S3Client s3, String bucketName) { } listObjectsReqManual = listObjectsReqManual.toBuilder() - .continuationToken(listObjResponse.nextContinuationToken()) - .build(); + .continuationToken(listObjResponse.nextContinuationToken()) + .build(); } } public static void anotherListExample(S3Client s3, String bucketName) { - ListObjectsV2Request listReq = ListObjectsV2Request.builder() - .bucket(bucketName) - .maxKeys(1) - .build(); + ListObjectsV2Request listReq = ListObjectsV2Request.builder() + .bucket(bucketName) + .maxKeys(1) + .build(); - ListObjectsV2Iterable listRes = s3.listObjectsV2Paginator(listReq); + ListObjectsV2Iterable listRes = s3.listObjectsV2Paginator(listReq); - // Process response pages. - listRes.stream() - .flatMap(r -> r.contents().stream()) - .forEach(content -> System.out.println(" Key: " + content.key() + " size = " + content.size())); + // Process response pages. + listRes.stream() + .flatMap(r -> r.contents().stream()) + .forEach(content -> System.out.println(" Key: " + content.key() + " size = " + content.size())); // Helper method to work with paginated collection of items directly. listRes.contents().stream() - .forEach(content -> System.out.println(" Key: " + content.key() + " size = " + content.size())); + .forEach(content -> System.out.println(" Key: " + content.key() + " size = " + content.size())); for (S3Object content : listRes.contents()) { System.out.println(" Key: " + content.key() + " size = " + content.size()); @@ -320,15 +317,15 @@ public static void anotherListExample(S3Client s3, String bucketName) { public static void deleteObjectFromBucket(S3Client s3, String bucketName, String key) { DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder() - .bucket(bucketName) - .key(key) - .build(); + .bucket(bucketName) + .key(key) + .build(); s3.deleteObject(deleteObjectRequest); - System.out.println(key +" was deleted"); + System.out.println(key + " was deleted"); } - public static String copyBucketObject (S3Client s3, String fromBucket, String objectKey, String toBucket) { + public static String copyBucketObject(S3Client s3, String fromBucket, String objectKey, String toBucket) { String encodedUrl = null; try { encodedUrl = URLEncoder.encode(fromBucket + "/" + objectKey, StandardCharsets.UTF_8.toString()); @@ -336,14 +333,14 @@ public static String copyBucketObject (S3Client s3, String fromBucket, String ob System.out.println("URL could not be encoded: " + e.getMessage()); } CopyObjectRequest copyReq = CopyObjectRequest.builder() - .copySource(encodedUrl) - .destinationBucket(toBucket) - .destinationKey(objectKey) - .build(); + .copySource(encodedUrl) + .destinationBucket(toBucket) + .destinationKey(objectKey) + .build(); try { CopyObjectResponse copyRes = s3.copyObject(copyReq); - System.out.println("The "+ objectKey +" was copied to "+toBucket); + System.out.println("The " + objectKey + " was copied to " + toBucket); return copyRes.copyObjectResult().toString(); } catch (S3Exception e) { @@ -354,4 +351,3 @@ public static String copyBucketObject (S3Client s3, String fromBucket, String ob } } // snippet-end:[s3.java2.s3_scenario.main] - diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/S3ZipExample.java b/javav2/example_code/s3/src/main/java/com/example/s3/S3ZipExample.java index 1d7ac3772c6..aa0ed071392 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/S3ZipExample.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/S3ZipExample.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[S3ZipExample.java demonstrates how to create a ZIP file of images, store the ZIP file in an Amazon Simple Storage Service (Amazon S3) and presign the ZIP file.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; @@ -26,7 +21,8 @@ import java.util.zip.ZipOutputStream; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -36,17 +32,17 @@ public class S3ZipExample { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - bucketName - The Amazon S3 bucket where JPG images are located.\s - keys - A comma separated list of images (without spaces) located in the S3 bucket and to be placed into a ZIP file. For example, For example pic1.jpg,pic2.jpg"""; + Where: + bucketName - The Amazon S3 bucket where JPG images are located.\s + keys - A comma separated list of images (without spaces) located in the S3 bucket and to be placed into a ZIP file. For example, For example pic1.jpg,pic2.jpg"""; - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } // Replace with your S3 bucket name. String bucketName = args[0]; @@ -54,13 +50,13 @@ public static void main(String[] args) { String[] imageKeys = keys.split("[,]", 0); Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); createZIPFile(s3, bucketName, imageKeys); } - public static void createZIPFile(S3Client s3, String bucketName,String[] imageKeys) { + public static void createZIPFile(S3Client s3, String bucketName, String[] imageKeys) { String uuid = java.util.UUID.randomUUID().toString(); String zipName = uuid + ".zip"; // Create a ByteArrayOutputStream to write the ZIP file to. @@ -74,9 +70,9 @@ public static void createZIPFile(S3Client s3, String bucketName,String[] imageKe for (String imageKey : imageKeys) { // Get the object data from S3. GetObjectRequest getObjectRequest = GetObjectRequest.builder() - .bucket(bucketName) - .key(imageKey) - .build(); + .bucket(bucketName) + .key(imageKey) + .build(); ResponseBytes responseBytes = s3.getObjectAsBytes(getObjectRequest); // Create a ZipEntry for the object and add it to the ZipOutputStream. @@ -95,12 +91,12 @@ public static void createZIPFile(S3Client s3, String bucketName,String[] imageKe // Upload the ZIP file to S3. PutObjectRequest putObjectRequest = PutObjectRequest.builder() - .bucket(bucketName) - .key(zipName) - .build(); + .bucket(bucketName) + .key(zipName) + .build(); s3.putObject(putObjectRequest, RequestBody.fromBytes(outputStream.toByteArray())); - String preSignUrl = signObjectToDownload(bucketName,zipName); - System.out.println("The Presigned URL is "+preSignUrl); + String preSignUrl = signObjectToDownload(bucketName, zipName); + System.out.println("The Presigned URL is " + preSignUrl); } catch (S3Exception | IOException e) { System.err.println(e.getMessage()); @@ -116,19 +112,19 @@ public static void createZIPFile(S3Client s3, String bucketName,String[] imageKe public static String signObjectToDownload(String bucketName, String keyName) { S3Presigner presignerOb = S3Presigner.builder() - .region(Region.US_EAST_1) - .build(); + .region(Region.US_EAST_1) + .build(); try { GetObjectRequest getObjectRequest = GetObjectRequest.builder() - .bucket(bucketName) - .key(keyName) - .build(); + .bucket(bucketName) + .key(keyName) + .build(); GetObjectPresignRequest getObjectPresignRequest = GetObjectPresignRequest.builder() - .signatureDuration(Duration.ofMinutes(1440)) - .getObjectRequest(getObjectRequest) - .build(); + .signatureDuration(Duration.ofMinutes(1440)) + .getObjectRequest(getObjectRequest) + .build(); PresignedGetObjectRequest presignedGetObjectRequest = presignerOb.presignGetObject(getObjectPresignRequest); return presignedGetObjectRequest.url().toString(); diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/SetAcl.java b/javav2/example_code/s3/src/main/java/com/example/s3/SetAcl.java index 93c91fd0935..4852b92ef3a 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/SetAcl.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/SetAcl.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[SetAcl.java demonstrates how to set a new access control list (ACL) to an Amazon Simple Storage Service (Amazon S3) bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.s3; // snippet-start:[s3.java2.set_acl.main] @@ -24,7 +19,8 @@ // snippet-end:[s3.java2.set_acl.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -34,13 +30,13 @@ public class SetAcl { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - bucketName - The Amazon S3 bucket to grant permissions on.\s - id - The ID of the owner of this bucket (you can get this value from the AWS Management Console). - """; + Where: + bucketName - The Amazon S3 bucket to grant permissions on.\s + id - The ID of the owner of this bucket (you can get this value from the AWS Management Console). + """; if (args.length != 2) { System.out.println(usage); @@ -53,8 +49,8 @@ public static void main(String[] args) { System.out.println(" in bucket: " + bucketName); Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); setBucketAcl(s3, bucketName, id); System.out.println("Done!"); @@ -64,23 +60,23 @@ public static void main(String[] args) { public static void setBucketAcl(S3Client s3, String bucketName, String id) { try { Grant ownerGrant = Grant.builder() - .grantee(builder -> builder.id(id) - .type(Type.CANONICAL_USER)) - .permission(Permission.FULL_CONTROL) - .build(); + .grantee(builder -> builder.id(id) + .type(Type.CANONICAL_USER)) + .permission(Permission.FULL_CONTROL) + .build(); List grantList2 = new ArrayList<>(); grantList2.add(ownerGrant); AccessControlPolicy acl = AccessControlPolicy.builder() - .owner(builder -> builder.id(id)) - .grants(grantList2) - .build(); + .owner(builder -> builder.id(id)) + .grants(grantList2) + .build(); PutBucketAclRequest putAclReq = PutBucketAclRequest.builder() - .bucket(bucketName) - .accessControlPolicy(acl) - .build(); + .bucket(bucketName) + .accessControlPolicy(acl) + .build(); s3.putBucketAcl(putAclReq); @@ -91,4 +87,3 @@ public static void setBucketAcl(S3Client s3, String bucketName, String id) { } } // snippet-end:[s3.java2.set_acl.main] - diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/SetBucketEventBridgeNotification.java b/javav2/example_code/s3/src/main/java/com/example/s3/SetBucketEventBridgeNotification.java index 68e80156314..8973461696a 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/SetBucketEventBridgeNotification.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/SetBucketEventBridgeNotification.java @@ -1,10 +1,5 @@ -//snippet-sourcedescription:[SetBucketEventBridgeNotification.java demonstrates how to enable notifications of specified events for an Amazon Simple Storage Service (Amazon S3) bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; @@ -23,14 +18,14 @@ public class SetBucketEventBridgeNotification { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - bucketName - The Amazon S3 bucket.\s - topicArn - The Simple Notification Service topic ARN.\s - id - An id value used for the topic configuration. This value is displayed in the AWS Management Console.\s - """; + Where: + bucketName - The Amazon S3 bucket.\s + topicArn - The Simple Notification Service topic ARN.\s + id - An id value used for the topic configuration. This value is displayed in the AWS Management Console.\s + """; if (args.length != 3) { System.out.println(usage); @@ -42,8 +37,8 @@ public static void main(String[] args) { String id = args[2]; Region region = Region.US_EAST_1; S3Client s3Client = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); setBucketNotification(s3Client, bucketName, topicArn, id); s3Client.close(); @@ -55,23 +50,24 @@ public static void setBucketNotification(S3Client s3Client, String bucketName, S events.add(Event.S3_OBJECT_CREATED_PUT); TopicConfiguration config = TopicConfiguration.builder() - .topicArn(topicArn) - .events(events) - .id(id) - .build(); + .topicArn(topicArn) + .events(events) + .id(id) + .build(); List topics = new ArrayList<>(); topics.add(config); NotificationConfiguration configuration = NotificationConfiguration.builder() - .topicConfigurations(topics) - .build(); + .topicConfigurations(topics) + .build(); - PutBucketNotificationConfigurationRequest configurationRequest = PutBucketNotificationConfigurationRequest.builder() - .bucket(bucketName) - .notificationConfiguration(configuration) - .skipDestinationValidation(true) - .build(); + PutBucketNotificationConfigurationRequest configurationRequest = PutBucketNotificationConfigurationRequest + .builder() + .bucket(bucketName) + .notificationConfiguration(configuration) + .skipDestinationValidation(true) + .build(); // Set the bucket notification configuration. s3Client.putBucketNotificationConfiguration(configurationRequest); diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/SetBucketPolicy.java b/javav2/example_code/s3/src/main/java/com/example/s3/SetBucketPolicy.java index 3a8d973b5bb..57b226be63f 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/SetBucketPolicy.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/SetBucketPolicy.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[SetBucketPolicy.java demonstrates how to add a bucket policy to an existing Amazon Simple Storage Service (Amazon S3) bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; @@ -25,7 +19,8 @@ // snippet-end:[s3.java2.set_bucket_policy.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -35,13 +30,13 @@ public class SetBucketPolicy { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - bucketName - The Amazon S3 bucket to set the policy on. - polFile - A JSON file containing the policy (see the Amazon S3 Readme for an example).\s - """; + Where: + bucketName - The Amazon S3 bucket to set the policy on. + polFile - A JSON file containing the policy (see the Amazon S3 Readme for an example).\s + """; if (args.length != 2) { System.out.println(usage); @@ -53,8 +48,8 @@ public static void main(String[] args) { String policyText = getBucketPolicyFromFile(polFile); Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); setPolicy(s3, bucketName, policyText); s3.close(); @@ -69,9 +64,9 @@ public static void setPolicy(S3Client s3, String bucketName, String policyText) try { PutBucketPolicyRequest policyReq = PutBucketPolicyRequest.builder() - .bucket(bucketName) - .policy(policyText) - .build(); + .bucket(bucketName) + .policy(policyText) + .build(); s3.putBucketPolicy(policyReq); @@ -110,4 +105,3 @@ public static String getBucketPolicyFromFile(String policyFile) { } } // snippet-end:[s3.java2.set_bucket_policy.main] - diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/SetWebsiteConfiguration.java b/javav2/example_code/s3/src/main/java/com/example/s3/SetWebsiteConfiguration.java index 3a668a8555d..16365530660 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/SetWebsiteConfiguration.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/SetWebsiteConfiguration.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[SetWebsiteConfiguration.java demonstrates how to set the website configuration for an Amazon Simple Storage Service (Amazon S3) bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.s3; // snippet-start:[s3.java2.set_website_configuration.main] @@ -19,7 +14,8 @@ // snippet-end:[s3.java2.set_website_configuration.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,13 +26,13 @@ public class SetWebsiteConfiguration { public static void main(String[] args) { final String usage = """ - Usage: [indexdoc]\s + Usage: [indexdoc]\s - Where: - bucketName - The Amazon S3 bucket to set the website configuration on.\s - indexdoc - The index document, ex. 'index.html' - If not specified, 'index.html' will be set. - """; + Where: + bucketName - The Amazon S3 bucket to set the website configuration on.\s + indexdoc - The index document, ex. 'index.html' + If not specified, 'index.html' will be set. + """; if (args.length != 1) { System.out.println(usage); @@ -47,24 +43,23 @@ public static void main(String[] args) { String indexDoc = "index.html"; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .region(region) - .build(); + .region(region) + .build(); setWebsiteConfig(s3, bucketName, indexDoc); s3.close(); } - public static void setWebsiteConfig(S3Client s3, String bucketName, String indexDoc) { try { WebsiteConfiguration websiteConfig = WebsiteConfiguration.builder() - .indexDocument(IndexDocument.builder().suffix(indexDoc).build()) - .build(); + .indexDocument(IndexDocument.builder().suffix(indexDoc).build()) + .build(); PutBucketWebsiteRequest pubWebsiteReq = PutBucketWebsiteRequest.builder() - .bucket(bucketName) - .websiteConfiguration(websiteConfig) - .build(); + .bucket(bucketName) + .websiteConfiguration(websiteConfig) + .build(); s3.putBucketWebsite(pubWebsiteReq); System.out.println("The call was successful"); @@ -76,4 +71,3 @@ public static void setWebsiteConfig(S3Client s3, String bucketName, String index } } // snippet-end:[s3.java2.set_website_configuration.main] - diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/VPCCreateJob.java b/javav2/example_code/s3/src/main/java/com/example/s3/VPCCreateJob.java index c44679eac47..e7e20461fa7 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/VPCCreateJob.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/VPCCreateJob.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[VPCS3Example.java demonstrates how to create a S3ControlClient object using a virtual private cloud (VPC) URL.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; @@ -29,9 +23,9 @@ import java.util.ArrayList; // snippet-end:[s3.java2.create_job.vpc.import] - /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -39,106 +33,110 @@ */ public class VPCCreateJob { - public static void main(String[] args) throws URISyntaxException { - final String usage = """ - - Usage: - - - Where: - accountId - The account id value that owns the Amazon S3 bucket. - - iamRoleArn - The ARN of the AWS Identity and Access Management (IAM) role that has permissions to create a batch job. - manifestLocation - The location where the manaifest file required for the job (for example, arn:aws:s3:::/manifest.csv). - reportBucketName - The Amazon S3 bucket where the report is written to (for example, arn:aws:s3:::). - tagKey - The key used for a tag (for example, keyOne). - tagValue - The value for the key (for example, ValueOne). - eTag - The ETag for the specified manifest object (for example, 000000c9d1046e73f7dde5043ac3ae85). - vpcBucketURL - The URL of the bucket located in your virtual private cloud (VPC) (for example, https://bucket.vpce-xxxxxc4d-5e6f.s3.us-east-1.vpce.amazonaws.com) - """; - - if (args.length != 8) { - System.out.println(usage); - System.exit(1); + public static void main(String[] args) throws URISyntaxException { + final String usage = """ + + Usage: + + + Where: + accountId - The account id value that owns the Amazon S3 bucket. + + iamRoleArn - The ARN of the AWS Identity and Access Management (IAM) role that has permissions to create a batch job. + manifestLocation - The location where the manaifest file required for the job (for example, arn:aws:s3:::/manifest.csv). + reportBucketName - The Amazon S3 bucket where the report is written to (for example, arn:aws:s3:::). + tagKey - The key used for a tag (for example, keyOne). + tagValue - The value for the key (for example, ValueOne). + eTag - The ETag for the specified manifest object (for example, 000000c9d1046e73f7dde5043ac3ae85). + vpcBucketURL - The URL of the bucket located in your virtual private cloud (VPC) (for example, https://bucket.vpce-xxxxxc4d-5e6f.s3.us-east-1.vpce.amazonaws.com) + """; + + if (args.length != 8) { + System.out.println(usage); + System.exit(1); + } + + String accountId = args[0]; + String iamRoleArn = args[1]; + String manifestLocation = args[2]; + String reportBucketName = args[3]; + String tagKey = args[4]; + String tagValue = args[5]; + String eTag = args[6]; + String vpcBucketURL = args[7]; + String uuid = java.util.UUID.randomUUID().toString(); + URI myURI = new URI(vpcBucketURL); + S3ControlClient s3ControlClient = S3ControlClient.builder() + .region(Region.US_EAST_1) + .endpointOverride(myURI) + .build(); + + createS3Job(s3ControlClient, accountId, iamRoleArn, manifestLocation, reportBucketName, tagKey, + tagValue, eTag, + uuid); + s3ControlClient.close(); } - String accountId = args[0]; - String iamRoleArn = args[1]; - String manifestLocation = args[2]; - String reportBucketName = args[3]; - String tagKey = args[4]; - String tagValue = args[5]; - String eTag = args[6]; - String vpcBucketURL = args[7]; - String uuid = java.util.UUID.randomUUID().toString(); - URI myURI = new URI(vpcBucketURL); - S3ControlClient s3ControlClient = S3ControlClient.builder() - .region(Region.US_EAST_1) - .endpointOverride(myURI) - .build(); - - createS3Job(s3ControlClient, accountId, iamRoleArn, manifestLocation, reportBucketName, tagKey, tagValue, eTag, uuid); - s3ControlClient.close(); - } - - public static void createS3Job(S3ControlClient s3ControlClient, String accountId, String iamRoleArn, String manifestLocation, String reportBucketName, String tagKey, String tagValue, String eTag, String uuid) { - try { - ArrayList tagSet = new ArrayList<>(); - S3Tag s3Tag = S3Tag.builder() - .key(tagKey) - .value(tagValue) - .build(); - - tagSet.add(s3Tag); - S3SetObjectTaggingOperation objectTaggingOperation = S3SetObjectTaggingOperation.builder() - .tagSet(tagSet) - .build(); - - JobOperation jobOperation = JobOperation.builder() - .s3PutObjectTagging(objectTaggingOperation) - .build(); - - JobManifestLocation jobManifestLocation = JobManifestLocation.builder() - .objectArn(manifestLocation) - .eTag(eTag) - .build(); - - JobManifestSpec manifestSpec = JobManifestSpec.builder() - .fieldsWithStrings(new String[]{"Bucket", "Key"}) - .format(JobManifestFormat.S3_BATCH_OPERATIONS_CSV_20180820) - .build(); - - JobManifest jobManifest = JobManifest.builder() - .spec(manifestSpec) - .location(jobManifestLocation) - .build(); - - JobReport jobReport = JobReport.builder() - .bucket(reportBucketName) - .prefix("reports") - .format(JobReportFormat.REPORT_CSV_20180820) - .enabled(true) - .reportScope("AllTasks") - .build(); - - CreateJobRequest jobRequest = CreateJobRequest.builder() - .accountId(accountId) - .description("Job created using the AWS Java SDK") - .manifest(jobManifest) - .operation(jobOperation) - .report(jobReport) - .priority(42) - .roleArn(iamRoleArn) - .clientRequestToken(uuid) - .confirmationRequired(false) - .build(); - - s3ControlClient.createJob(jobRequest); - - } catch (S3ControlException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + public static void createS3Job(S3ControlClient s3ControlClient, String accountId, String iamRoleArn, + String manifestLocation, String reportBucketName, String tagKey, String tagValue, String eTag, + String uuid) { + try { + ArrayList tagSet = new ArrayList<>(); + S3Tag s3Tag = S3Tag.builder() + .key(tagKey) + .value(tagValue) + .build(); + + tagSet.add(s3Tag); + S3SetObjectTaggingOperation objectTaggingOperation = S3SetObjectTaggingOperation.builder() + .tagSet(tagSet) + .build(); + + JobOperation jobOperation = JobOperation.builder() + .s3PutObjectTagging(objectTaggingOperation) + .build(); + + JobManifestLocation jobManifestLocation = JobManifestLocation.builder() + .objectArn(manifestLocation) + .eTag(eTag) + .build(); + + JobManifestSpec manifestSpec = JobManifestSpec.builder() + .fieldsWithStrings(new String[] { "Bucket", "Key" }) + .format(JobManifestFormat.S3_BATCH_OPERATIONS_CSV_20180820) + .build(); + + JobManifest jobManifest = JobManifest.builder() + .spec(manifestSpec) + .location(jobManifestLocation) + .build(); + + JobReport jobReport = JobReport.builder() + .bucket(reportBucketName) + .prefix("reports") + .format(JobReportFormat.REPORT_CSV_20180820) + .enabled(true) + .reportScope("AllTasks") + .build(); + + CreateJobRequest jobRequest = CreateJobRequest.builder() + .accountId(accountId) + .description("Job created using the AWS Java SDK") + .manifest(jobManifest) + .operation(jobOperation) + .report(jobReport) + .priority(42) + .roleArn(iamRoleArn) + .clientRequestToken(uuid) + .confirmationRequired(false) + .build(); + + s3ControlClient.createJob(jobRequest); + + } catch (S3ControlException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } } - } } // snippet-end:[s3.java2.create_job.vpc.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/VPCS3Example.java b/javav2/example_code/s3/src/main/java/com/example/s3/VPCS3Example.java index 1f1f507af4c..8237fd88817 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/VPCS3Example.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/VPCS3Example.java @@ -1,11 +1,5 @@ -//snippet-sourcedescription:[VPCS3Example.java demonstrates how to setup a S3Client object using a virtual private cloud (VPC) URL.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; @@ -23,7 +17,8 @@ // snippet-end:[s3.java2.vpc.example.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -34,17 +29,17 @@ public class VPCS3Example { public static void main(String[] args) throws URISyntaxException { final String usage = """ - Usage: - \s + Usage: + \s - Where: - bucketName - The Amazon S3 bucket from which objects are read.\s - vpcBucketURL - The URL of the bucket located in your virtual private cloud (VPC) (for example, https://bucket.vpxx-xxxxxc4d-5e6f.s3.us-east-1.vpce.amazonaws.com - """; + Where: + bucketName - The Amazon S3 bucket from which objects are read.\s + vpcBucketURL - The URL of the bucket located in your virtual private cloud (VPC) (for example, https://bucket.vpxx-xxxxxc4d-5e6f.s3.us-east-1.vpce.amazonaws.com + """; if (args.length != 2) { - System.out.println(usage); - System.exit(1); + System.out.println(usage); + System.exit(1); } String bucketName = args[0]; @@ -52,23 +47,23 @@ public static void main(String[] args) throws URISyntaxException { URI myURI = new URI(vpcBucketURL); Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() - .endpointOverride(myURI) - .region(region) - .build(); + .endpointOverride(myURI) + .region(region) + .build(); listBucketObjects(s3, bucketName); s3.close(); } - public static void listBucketObjects(S3Client s3, String bucketName ) { + public static void listBucketObjects(S3Client s3, String bucketName) { try { ListObjectsRequest listObjects = ListObjectsRequest.builder() - .bucket(bucketName) - .build(); + .bucket(bucketName) + .build(); ListObjectsResponse res = s3.listObjects(listObjects); List objects = res.contents(); - for (S3Object s3Object: objects) { + for (S3Object s3Object : objects) { System.out.print("\n The name of the key is " + s3Object.key()); System.out.print("\n The object is " + convertBToKb(s3Object.size()) + " KBs"); System.out.print("\n The owner is " + s3Object.owner()); @@ -80,10 +75,9 @@ public static void listBucketObjects(S3Client s3, String bucketName ) { } } - //convert bytes to kbs. + // convert bytes to kbs. private static long convertBToKb(Long val) { - return val/1024; + return val / 1024; } - } +} // snippet-end:[s3.java2.vpc.example.main] - diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/async/CreateBucketAsync.java b/javav2/example_code/s3/src/main/java/com/example/s3/async/CreateBucketAsync.java index e165ce559e8..b36305d8b4c 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/async/CreateBucketAsync.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/async/CreateBucketAsync.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[CreateBucketAsync.java demonstrates how to create an Amazon Simple Storage Service (Amazon S3) object using the Async client.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3.async; @@ -20,7 +13,8 @@ import java.util.concurrent.CompletableFuture; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,12 +25,12 @@ public class CreateBucketAsync { public static void main(String[] args) throws URISyntaxException { final String usage = """ - Usage: - \s + Usage: + \s - Where: - bucketName - The name of the bucket to create. The bucket name must be unique, or an error occurs. - """; + Where: + bucketName - The name of the bucket to create. The bucket name must be unique, or an error occurs. + """; if (args.length != 1) { System.out.println(usage); @@ -49,13 +43,13 @@ public static void main(String[] args) throws URISyntaxException { Region region = Region.US_EAST_1; S3AsyncClient s3AsyncClient = S3AsyncClient.builder() - .region(region) - .build(); + .region(region) + .build(); - createBucket (s3AsyncClient, bucketName); + createBucket(s3AsyncClient, bucketName); } - public static void createBucket( S3AsyncClient s3AsyncClient, String bucketName) { + public static void createBucket(S3AsyncClient s3AsyncClient, String bucketName) { try { CreateBucketRequest bucketRequest = CreateBucketRequest.builder() .bucket(bucketName) @@ -65,7 +59,7 @@ public static void createBucket( S3AsyncClient s3AsyncClient, String bucketName) futureGet.whenComplete((resp, err) -> { try { if (resp != null) { - System.out.println(bucketName +" is ready~"); + System.out.println(bucketName + " is ready~"); } else { err.printStackTrace(); } @@ -82,4 +76,3 @@ public static void createBucket( S3AsyncClient s3AsyncClient, String bucketName) } } } - diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/async/GetObjectDataAsync.java b/javav2/example_code/s3/src/main/java/com/example/s3/async/GetObjectDataAsync.java index ac0366caa42..c40378e5b22 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/async/GetObjectDataAsync.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/async/GetObjectDataAsync.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[GetObjectDataAsync.java demonstrates how to read data from an Amazon Simple Storage Service (Amazon S3) object using the Async client.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3.async; @@ -20,7 +13,8 @@ import java.util.concurrent.CompletableFuture; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,32 +25,32 @@ public class GetObjectDataAsync { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - bucketName - The Amazon S3 bucket name.\s - keyName - The key name.\s - path - The path where the file is written to.\s - """; + Where: + bucketName - The Amazon S3 bucket name.\s + keyName - The key name.\s + path - The path where the file is written to.\s + """; if (args.length != 3) { - System.out.println(usage); - System.exit(1); + System.out.println(usage); + System.exit(1); } String bucketName = args[0]; String keyName = args[1]; String path = args[2]; Region region = Region.US_EAST_1; S3AsyncClient s3AsyncClient = S3AsyncClient.builder() - .region(region) - .build(); + .region(region) + .build(); - getObject (s3AsyncClient, bucketName, keyName, path); + getObject(s3AsyncClient, bucketName, keyName, path); s3AsyncClient.close(); } - public static void getObject (S3AsyncClient s3AsyncClient, String bucketName, String keyName, String path ) { + public static void getObject(S3AsyncClient s3AsyncClient, String bucketName, String keyName, String path) { try { GetObjectRequest objectRequest = GetObjectRequest .builder() diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/async/PutObjectFromStreamAsync.java b/javav2/example_code/s3/src/main/java/com/example/s3/async/PutObjectFromStreamAsync.java index 62cf63d9472..3883ab305ce 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/async/PutObjectFromStreamAsync.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/async/PutObjectFromStreamAsync.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3.async; // snippet-start:[s3.java2.async_stream.complete] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/async/S3AsyncOps.java b/javav2/example_code/s3/src/main/java/com/example/s3/async/S3AsyncOps.java index bb7a6f35b7a..38334db8c93 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/async/S3AsyncOps.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/async/S3AsyncOps.java @@ -1,13 +1,8 @@ -//snippet-sourcedescription:[S3AsyncOps.java demonstrates how to use the asynchronous client to place an object into an Amazon Simple Storage Service (Amazon S3) bucket.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3.async; + // snippet-start:[s3.java2.async_ops.complete] // snippet-start:[s3.java2.async_ops.import] import software.amazon.awssdk.core.async.AsyncRequestBody; @@ -21,7 +16,8 @@ // snippet-start:[s3.java2.async_ops.main] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,44 +25,43 @@ */ public class S3AsyncOps { - public static void main(String[] args) { + public static void main(String[] args) { - final String usage = """ + final String usage = """ - Usage: - + Usage: + - Where: - bucketName - The name of the Amazon S3 bucket (for example, bucket1).\s - key - The name of the object (for example, book.pdf).\s - path - The local path to the file (for example, C:/AWS/book.pdf).\s - """; + Where: + bucketName - The name of the Amazon S3 bucket (for example, bucket1).\s + key - The name of the object (for example, book.pdf).\s + path - The local path to the file (for example, C:/AWS/book.pdf).\s + """; - if (args.length != 3) { - System.out.println(usage); - System.exit(1); - } + if (args.length != 3) { + System.out.println(usage); + System.exit(1); + } - String bucketName = args[0]; - String key = args[1]; - String path = args[2]; - Region region = Region.US_EAST_1; - S3AsyncClient s3AsyncClient = S3AsyncClient.builder() - .region(region) - .build(); + String bucketName = args[0]; + String key = args[1]; + String path = args[2]; + Region region = Region.US_EAST_1; + S3AsyncClient s3AsyncClient = S3AsyncClient.builder() + .region(region) + .build(); - putObjectAsync(s3AsyncClient, bucketName, key, path); - } + putObjectAsync(s3AsyncClient, bucketName, key, path); + } - public static void putObjectAsync(S3AsyncClient client,String bucketName, String key, String path) { + public static void putObjectAsync(S3AsyncClient client, String bucketName, String key, String path) { PutObjectRequest objectRequest = PutObjectRequest.builder() .bucket(bucketName) .key(key) .build(); CompletableFuture future = client.putObject(objectRequest, - AsyncRequestBody.fromFile(Paths.get(path)) - ); + AsyncRequestBody.fromFile(Paths.get(path))); future.whenComplete((resp, err) -> { try { if (resp != null) { diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/async/S3AsyncStreamOps.java b/javav2/example_code/s3/src/main/java/com/example/s3/async/S3AsyncStreamOps.java index cd3acb908a0..79f0eef1450 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/async/S3AsyncStreamOps.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/async/S3AsyncStreamOps.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[S3AsyncStreamOps.java demonstrates how to use the streaming operations of an Amazon Simple Storage Service (Amazon S3) asynchronous client.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.s3.async; // snippet-start:[s3.java2.async_stream_ops.complete] @@ -22,7 +17,8 @@ // snippet-start:[s3.java2.async_stream_ops.main] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,33 +28,33 @@ public class S3AsyncStreamOps { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - bucketName - The name of the Amazon S3 bucket (for example, bucket1).\s + Where: + bucketName - The name of the Amazon S3 bucket (for example, bucket1).\s - objectKey - The name of the object (for example, book.pdf).\s - path - The local path to the file (for example, C:/AWS/book.pdf).\s - """; + objectKey - The name of the object (for example, book.pdf).\s + path - The local path to the file (for example, C:/AWS/book.pdf).\s + """; if (args.length != 3) { System.out.println(usage); System.exit(1); - } + } String bucketName = args[0]; String objectKey = args[1]; String path = args[2]; Region region = Region.US_EAST_1; S3AsyncClient s3AsyncClient = S3AsyncClient.builder() - .region(region) - .build(); + .region(region) + .build(); GetObjectRequest objectRequest = GetObjectRequest.builder() - .bucket(bucketName) - .key(objectKey) - .build(); + .bucket(bucketName) + .key(objectKey) + .build(); CompletableFuture futureGet = s3AsyncClient.getObject(objectRequest, AsyncResponseTransformer.toFile(Paths.get(path))); @@ -66,12 +62,12 @@ public static void main(String[] args) { futureGet.whenComplete((resp, err) -> { try { if (resp != null) { - System.out.println("Object downloaded. Details: "+resp); + System.out.println("Object downloaded. Details: " + resp); } else { err.printStackTrace(); } } finally { - // Only close the client when you are completely done with it. + // Only close the client when you are completely done with it. s3AsyncClient.close(); } }); diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadFile.java b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadFile.java index cc37a7a4468..c13b96db5af 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadFile.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadFile.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[DownloadFile.java demonstrates how to download a file using the Amazon Simple Storage Service (Amazon S3) TransferManager.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.s3.transfermanager; // snippet-start:[s3.tm.java2.downloadfile.import] @@ -26,7 +21,8 @@ // snippet-end:[s3.tm.java2.downloadfile.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -46,15 +42,15 @@ public DownloadFile() { public static void main(String[] args) { DownloadFile download = new DownloadFile(); - download.downloadFile(S3ClientFactory.transferManager, download.bucketName, download.key, download.downloadedFileWithPath); + download.downloadFile(S3ClientFactory.transferManager, download.bucketName, download.key, + download.downloadedFileWithPath); download.cleanUp(); } // snippet-start:[s3.tm.java2.downloadfile.main] public Long downloadFile(S3TransferManager transferManager, String bucketName, - String key, String downloadedFileWithPath) { - DownloadFileRequest downloadFileRequest = - DownloadFileRequest.builder() + String key, String downloadedFileWithPath) { + DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder() .getObjectRequest(b -> b.bucket(bucketName).key(key)) .addTransferListener(LoggingTransferListener.create()) .destination(Paths.get(downloadedFileWithPath)) @@ -68,16 +64,16 @@ public Long downloadFile(S3TransferManager transferManager, String bucketName, } // snippet-end:[s3.tm.java2.downloadfile.main] - private void setUp(){ + private void setUp() { S3ClientFactory.s3Client.createBucket(b -> b.bucket(bucketName)); S3ClientFactory.s3Client.putObject(builder -> builder - .bucket(bucketName) - .key(key), RequestBody.fromString("Hello World")); + .bucket(bucketName) + .key(key), RequestBody.fromString("Hello World")); URL resource = DownloadFile.class.getClassLoader().getResource("."); downloadedFileWithPath = resource.getFile() + downloadedFileName; } - public void cleanUp(){ + public void cleanUp() { S3ClientFactory.s3Client.deleteObject(b -> b.bucket(bucketName).key(key)); S3ClientFactory.s3Client.deleteBucket(b -> b.bucket(bucketName)); URL url = DownloadFile.class.getClassLoader().getResource(downloadedFileName); diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadToDirectory.java b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadToDirectory.java index c2c4c74c4e5..44cafbf3562 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadToDirectory.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadToDirectory.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[DownloadToDirectory.java demonstrates how to copy all objects in an Amazon Simple Storage Service (Amazon S3) bucket to a local directory using the Amazon S3 TransferManager.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.s3.transfermanager; // snippet-start:[s3.tm.java2.downloadtodirectory.import] @@ -28,7 +23,8 @@ // snippet-end:[s3.tm.java2.downloadtodirectory.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -48,23 +44,23 @@ public DownloadToDirectory() { public static void main(String[] args) { DownloadToDirectory download = new DownloadToDirectory(); - Integer numFilesFailedToDownload = download.downloadObjectsToDirectory(S3ClientFactory.transferManager, download.destinationPath, download.bucketName); + Integer numFilesFailedToDownload = download.downloadObjectsToDirectory(S3ClientFactory.transferManager, + download.destinationPath, download.bucketName); logger.info("Number of files that failed to download [{}].", numFilesFailedToDownload); download.cleanUp(); } // snippet-start:[s3.tm.java2.downloadtodirectory.main] public Integer downloadObjectsToDirectory(S3TransferManager transferManager, - String destinationPath, String bucketName) { - DirectoryDownload directoryDownload = - transferManager.downloadDirectory(DownloadDirectoryRequest.builder() + String destinationPath, String bucketName) { + DirectoryDownload directoryDownload = transferManager.downloadDirectory(DownloadDirectoryRequest.builder() .destination(Paths.get(destinationPath)) .bucket(bucketName) .build()); CompletedDirectoryDownload completedDirectoryDownload = directoryDownload.completionFuture().join(); - completedDirectoryDownload.failedTransfers().forEach(fail -> - logger.warn("Object [{}] failed to transfer", fail.toString())); + completedDirectoryDownload.failedTransfers() + .forEach(fail -> logger.warn("Object [{}] failed to transfer", fail.toString())); return completedDirectoryDownload.failedTransfers().size(); } // snippet-end:[s3.tm.java2.downloadtodirectory.main] @@ -74,28 +70,26 @@ private void setUp() { RequestBody requestBody = RequestBody.fromString("Hello World."); java.util.stream.IntStream.rangeClosed(1, 3).forEach(i -> { - String fileName = "downloadedFile" + i + ".txt"; - downloadedFileNameSet.add(fileName); - S3ClientFactory.s3Client.putObject(b -> b - .bucket(bucketName) - .key(fileName), + String fileName = "downloadedFile" + i + ".txt"; + downloadedFileNameSet.add(fileName); + S3ClientFactory.s3Client.putObject(b -> b + .bucket(bucketName) + .key(fileName), requestBody); - } - ); + }); destinationPath = DownloadToDirectory.class.getClassLoader().getResource(destinationDirName).getPath(); } - public void cleanUp() { // Delete items uploaded to bucket for download. Set items = downloadedFileNameSet - .stream() - .map(name -> ObjectIdentifier.builder().key(name).build()) - .collect(Collectors.toSet()); + .stream() + .map(name -> ObjectIdentifier.builder().key(name).build()) + .collect(Collectors.toSet()); S3ClientFactory.s3Client.deleteObjects(b -> b - .bucket(bucketName) - .delete(b1 -> b1.objects(items))); + .bucket(bucketName) + .delete(b1 -> b1.objects(items))); // Delete bucket. S3ClientFactory.s3Client.deleteBucket(b -> b.bucket(bucketName)); diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/ObjectCopy.java b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/ObjectCopy.java index 5b3b22e7a85..a7aa0d7c711 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/ObjectCopy.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/ObjectCopy.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[ObjectCopy.java demonstrates how to copy an object between Amazon Simple Storage Service (Amazon S3) buckets using the Amazon S3 TransferManager.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.s3.transfermanager; // snippet-start:[s3.tm.java2.objectcopy.import] @@ -22,7 +17,8 @@ // snippet-end:[s3.tm.java2.objectcopy.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -43,25 +39,25 @@ public ObjectCopy() { public static void main(String[] args) { ObjectCopy copy = new ObjectCopy(); - String etag = copy.copyObject(S3ClientFactory.transferManager,copy.bucketName, - copy.key, copy.destinationBucket, copy.destinationKey); + String etag = copy.copyObject(S3ClientFactory.transferManager, copy.bucketName, + copy.key, copy.destinationBucket, copy.destinationKey); logger.info("etag [{}]", etag); copy.cleanUp(); } // snippet-start:[s3.tm.java2.objectcopy.main] public String copyObject(S3TransferManager transferManager, String bucketName, - String key, String destinationBucket, String destinationKey){ + String key, String destinationBucket, String destinationKey) { CopyObjectRequest copyObjectRequest = CopyObjectRequest.builder() - .sourceBucket(bucketName) - .sourceKey(key) - .destinationBucket(destinationBucket) - .destinationKey(destinationKey) - .build(); + .sourceBucket(bucketName) + .sourceKey(key) + .destinationBucket(destinationBucket) + .destinationKey(destinationKey) + .build(); CopyRequest copyRequest = CopyRequest.builder() - .copyObjectRequest(copyObjectRequest) - .build(); + .copyObjectRequest(copyObjectRequest) + .build(); Copy copy = transferManager.copy(copyRequest); @@ -73,12 +69,12 @@ public String copyObject(S3TransferManager transferManager, String bucketName, private void setUp() { S3ClientFactory.s3Client.createBucket(b -> b.bucket(bucketName)); S3ClientFactory.s3Client.putObject(builder -> builder - .bucket(bucketName) - .key(key), RequestBody.fromString("Hello World")); + .bucket(bucketName) + .key(key), RequestBody.fromString("Hello World")); S3ClientFactory.s3Client.createBucket(b -> b.bucket(destinationBucket)); } - public void cleanUp(){ + public void cleanUp() { S3ClientFactory.s3Client.deleteObject(b -> b.bucket(bucketName).key(key)); S3ClientFactory.s3Client.deleteBucket(b -> b.bucket(bucketName)); S3ClientFactory.s3Client.deleteObject(b -> b.bucket(destinationBucket).key(destinationKey)); diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/S3ClientFactory.java b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/S3ClientFactory.java index 0a2f680391b..3d69835f284 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/S3ClientFactory.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/S3ClientFactory.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[S3ClientFactory.java demonstrates how to create instances of the Amazon Simple Storage Service (Amazon S3) TransferManager.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.s3.transfermanager; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; @@ -17,7 +12,8 @@ import static software.amazon.awssdk.transfer.s3.SizeConstant.MB; /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,25 +24,23 @@ public class S3ClientFactory { public static final S3TransferManager transferManager = createCustonTm(); public static final S3Client s3Client; - private static S3TransferManager createCustonTm(){ + private static S3TransferManager createCustonTm() { // snippet-start:[s3.tm.java2.s3clientfactory.create_custom_tm] - S3AsyncClient s3AsyncClient = - S3AsyncClient.crtBuilder() + S3AsyncClient s3AsyncClient = S3AsyncClient.crtBuilder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .targetThroughputInGbps(20.0) .minimumPartSizeInBytes(8 * MB) .build(); - S3TransferManager transferManager = - S3TransferManager.builder() + S3TransferManager transferManager = S3TransferManager.builder() .s3Client(s3AsyncClient) .build(); // snippet-end:[s3.tm.java2.s3clientfactory.create_custom_tm] return transferManager; } - private static S3TransferManager createDefaultTm(){ + private static S3TransferManager createDefaultTm() { // snippet-start:[s3.tm.java2.s3clientfactory.create_default_tm] S3TransferManager transferManager = S3TransferManager.create(); // snippet-end:[s3.tm.java2.s3clientfactory.create_default_tm] @@ -55,8 +49,8 @@ private static S3TransferManager createDefaultTm(){ static { s3Client = S3Client.builder() - .credentialsProvider(DefaultCredentialsProvider.create()) - .region(Region.US_EAST_1) - .build(); + .credentialsProvider(DefaultCredentialsProvider.create()) + .region(Region.US_EAST_1) + .build(); } } diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadADirectory.java b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadADirectory.java index 1a6d3508ecb..b089e37b40a 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadADirectory.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadADirectory.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[UploadADirectory.java demonstrates how to recursively copy a local directory to an Amazon Simple Storage Service (Amazon S3) bucket the Amazon S3 TransferManager.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.s3.transfermanager; // snippet-start:[s3.tm.java2.uploadadirectory.import] @@ -23,7 +18,8 @@ // snippet-end:[s3.tm.java2.uploadadirectory.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -42,42 +38,41 @@ public UploadADirectory() { public static void main(String[] args) { UploadADirectory upload = new UploadADirectory(); - Integer numFailedUploads = upload.uploadDirectory(S3ClientFactory.transferManager, upload.sourceDirectory, upload.bucketName); + Integer numFailedUploads = upload.uploadDirectory(S3ClientFactory.transferManager, upload.sourceDirectory, + upload.bucketName); logger.info("Number of failed transfers [{}].", numFailedUploads); upload.cleanUp(); } // snippet-start:[s3.tm.java2.uploadadirectory.main] public Integer uploadDirectory(S3TransferManager transferManager, - String sourceDirectory, String bucketName){ - DirectoryUpload directoryUpload = - transferManager.uploadDirectory(UploadDirectoryRequest.builder() + String sourceDirectory, String bucketName) { + DirectoryUpload directoryUpload = transferManager.uploadDirectory(UploadDirectoryRequest.builder() .source(Paths.get(sourceDirectory)) .bucket(bucketName) .build()); CompletedDirectoryUpload completedDirectoryUpload = directoryUpload.completionFuture().join(); - completedDirectoryUpload.failedTransfers().forEach(fail -> - logger.warn("Object [{}] failed to transfer", fail.toString())); + completedDirectoryUpload.failedTransfers() + .forEach(fail -> logger.warn("Object [{}] failed to transfer", fail.toString())); return completedDirectoryUpload.failedTransfers().size(); } // snippet-end:[s3.tm.java2.uploadadirectory.main] - private void setUp(){ + private void setUp() { S3ClientFactory.s3Client.createBucket(b -> b.bucket(bucketName)); URL dirResource = UploadADirectory.class.getClassLoader().getResource("uploadDirectory"); sourceDirectory = dirResource.getPath(); } - public void cleanUp(){ + public void cleanUp() { S3ClientFactory.s3Client.deleteObjects(b -> b - .bucket(bucketName) - .delete(b1 -> b1 - .objects( - ObjectIdentifier.builder().key("file1.txt").build(), - ObjectIdentifier.builder().key("file2.txt").build(), - ObjectIdentifier.builder().key("file3.txt").build() - ))); + .bucket(bucketName) + .delete(b1 -> b1 + .objects( + ObjectIdentifier.builder().key("file1.txt").build(), + ObjectIdentifier.builder().key("file2.txt").build(), + ObjectIdentifier.builder().key("file3.txt").build()))); S3ClientFactory.s3Client.deleteBucket(b -> b.bucket(bucketName)); } } diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadFile.java b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadFile.java index e7a9a3fb08a..70ca9547240 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadFile.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadFile.java @@ -1,11 +1,6 @@ -//snippet-sourcedescription:[UploadFile.java demonstrates how to upload a file using the Amazon Simple Storage Service (Amazon S3) TransferManager.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[Amazon S3] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.s3.transfermanager; // snippet-start:[s3.tm.java2.uploadfile.import] @@ -23,7 +18,8 @@ // snippet-end:[s3.tm.java2.uploadfile.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -48,9 +44,8 @@ public static void main(String[] args) { // snippet-start:[s3.tm.java2.uploadfile.main] public String uploadFile(S3TransferManager transferManager, String bucketName, - String key, String filePath) { - UploadFileRequest uploadFileRequest = - UploadFileRequest.builder() + String key, String filePath) { + UploadFileRequest uploadFileRequest = UploadFileRequest.builder() .putObjectRequest(b -> b.bucket(bucketName).key(key)) .addTransferListener(LoggingTransferListener.create()) .source(Paths.get(filePath)) @@ -63,14 +58,14 @@ public String uploadFile(S3TransferManager transferManager, String bucketName, } // snippet-end:[s3.tm.java2.uploadfile.main] - private void setUp(){ + private void setUp() { S3ClientFactory.s3Client.createBucket(b -> b.bucket(bucketName)); // get the file system path to the provided file to upload URL resource = UploadFile.class.getClassLoader().getResource("image.png"); filePath = resource.getPath(); } - public void cleanUp(){ + public void cleanUp() { S3ClientFactory.s3Client.deleteObject(b -> b.bucket(bucketName).key(key)); S3ClientFactory.s3Client.deleteBucket(b -> b.bucket(bucketName)); } diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadStream.java b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadStream.java index 7cfc256bc5c..ae1377a6fbe 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadStream.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadStream.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3.transfermanager; // snippet-start:[s3.tm.java2.upload_stream.complete] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/util/AsyncExampleUtils.java b/javav2/example_code/s3/src/main/java/com/example/s3/util/AsyncExampleUtils.java index a8b5448659b..c9a965828a7 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/util/AsyncExampleUtils.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/util/AsyncExampleUtils.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3.util; import org.slf4j.Logger; diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/util/MemoryLog4jAppender.java b/javav2/example_code/s3/src/main/java/com/example/s3/util/MemoryLog4jAppender.java index e85b3a4d55d..f2d2b7d3cb4 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/util/MemoryLog4jAppender.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/util/MemoryLog4jAppender.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3.util; import org.apache.logging.log4j.core.Appender; diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/util/PresignUrlUtils.java b/javav2/example_code/s3/src/main/java/com/example/s3/util/PresignUrlUtils.java index 90b3e3a45c7..f42f6a26af4 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/util/PresignUrlUtils.java +++ b/javav2/example_code/s3/src/main/java/com/example/s3/util/PresignUrlUtils.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3.util; import org.slf4j.Logger; diff --git a/javav2/example_code/s3/src/test/java/AmazonS3Test.java b/javav2/example_code/s3/src/test/java/AmazonS3Test.java index 2e984e68b1c..40635b703ad 100644 --- a/javav2/example_code/s3/src/test/java/AmazonS3Test.java +++ b/javav2/example_code/s3/src/test/java/AmazonS3Test.java @@ -1,8 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -46,7 +43,6 @@ import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; - /** * To run these integration tests, you must set the required values * in the config.properties file or AWS Secrets Manager. @@ -65,19 +61,19 @@ public class AmazonS3Test { private static String toBucket = ""; private static String policyText = ""; private static String id = ""; - private static String presignKey=""; - private static String presignBucket=""; - private static String path=""; - private static String bucketNamePolicy=""; - private static String accountId=""; - private static String accessPointName=""; - private static String bucketNameZip=""; + private static String presignKey = ""; + private static String presignBucket = ""; + private static String path = ""; + private static String bucketNamePolicy = ""; + private static String accountId = ""; + private static String accessPointName = ""; + private static String bucketNameZip = ""; // Used for the encryption test. - private static String encryptObjectName=""; - private static String encryptObjectPath=""; - private static String encryptOutPath=""; - private static String keyId=""; + private static String encryptObjectName = ""; + private static String encryptObjectPath = ""; + private static String encryptOutPath = ""; + private static String keyId = ""; // Used for restore tests. private static String restoreImagePath = ""; @@ -90,38 +86,38 @@ public class AmazonS3Test { private static String objectPathSc = ""; private static String savePathSc = ""; private static String toBucketSc = ""; - private static String images= ""; - private static String[] imageKeys ; + private static String images = ""; + private static String[] imageKeys; @BeforeAll public static void setUp() throws IOException { s3 = S3Client.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); presigner = S3Presigner.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); s3ControlClient = S3ControlClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); String json = getSecretValues(); SecretValues values = gson.fromJson(json, SecretValues.class); - bucketName = values.getBucketName()+ java.util.UUID.randomUUID(); + bucketName = values.getBucketName() + java.util.UUID.randomUUID(); objectKey = values.getObjectKey(); - objectPath= values.getObjectPath(); + objectPath = values.getObjectPath(); toBucket = values.getToBucket(); policyText = values.getPolicyText(); id = values.getId(); presignKey = values.getPresignKey(); - presignBucket= values.getPresignBucket(); + presignBucket = values.getPresignBucket(); path = values.getPath(); bucketNamePolicy = values.getBucketNamePolicy(); accountId = values.getAccountId(); @@ -133,7 +129,7 @@ public static void setUp() throws IOException { restoreImagePath = values.getRestoreImagePath(); restoreBucket = values.getRestoreBucket(); restoreImageName = values.getRestoreImageName(); - bucketNameSc = values.getBucketNameSc()+ java.util.UUID.randomUUID(); + bucketNameSc = values.getBucketNameSc() + java.util.UUID.randomUUID(); keySc = values.getKeySc(); objectPathSc = values.getObjectPathSc(); savePathSc = values.getSavePathSc(); @@ -142,89 +138,92 @@ public static void setUp() throws IOException { images = values.getImages(); imageKeys = images.split("[,]", 0); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - try (InputStream input = AmazonS3Test.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - prop.load(input); - bucketName = prop.getProperty("bucketName")+ java.util.UUID.randomUUID();; - objectKey = prop.getProperty("objectKey"); - objectPath= prop.getProperty("objectPath"); - toBucket = prop.getProperty("toBucket"); - policyText = prop.getProperty("policyText"); - id = prop.getProperty("id"); - presignKey = prop.getProperty("presignKey"); - presignBucket= prop.getProperty("presignBucket"); - path = prop.getProperty("path"); - bucketNamePolicy = prop.getProperty("bucketNamePolicy"); - accountId = prop.getProperty("accountId"); - accessPointName = prop.getProperty("accessPointName"); - encryptObjectName = prop.getProperty("encryptObjectName"); - encryptObjectPath = prop.getProperty("encryptObjectPath"); - encryptOutPath = prop.getProperty("encryptOutPath"); - keyId = prop.getProperty("keyId"); - restoreImagePath = prop.getProperty("restoreImagePath"); - restoreBucket = prop.getProperty("restoreBucket"); - restoreImageName = prop.getProperty("restoreImageName"); - bucketNameSc = prop.getProperty("bucketNameSc")+ java.util.UUID.randomUUID();; - keySc = prop.getProperty("keySc"); - objectPathSc = prop.getProperty("objectPathSc"); - savePathSc = prop.getProperty("savePathSc"); - toBucketSc = prop.getProperty("toBucketSc"); - bucketNameZip = prop.getProperty("bucketNameZip"); - images = prop.getProperty("images"); - imageKeys = images.split("[,]", 0); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * try (InputStream input = + * AmazonS3Test.class.getClassLoader().getResourceAsStream("config.properties")) + * { + * Properties prop = new Properties(); + * + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * prop.load(input); + * bucketName = prop.getProperty("bucketName")+ java.util.UUID.randomUUID();; + * objectKey = prop.getProperty("objectKey"); + * objectPath= prop.getProperty("objectPath"); + * toBucket = prop.getProperty("toBucket"); + * policyText = prop.getProperty("policyText"); + * id = prop.getProperty("id"); + * presignKey = prop.getProperty("presignKey"); + * presignBucket= prop.getProperty("presignBucket"); + * path = prop.getProperty("path"); + * bucketNamePolicy = prop.getProperty("bucketNamePolicy"); + * accountId = prop.getProperty("accountId"); + * accessPointName = prop.getProperty("accessPointName"); + * encryptObjectName = prop.getProperty("encryptObjectName"); + * encryptObjectPath = prop.getProperty("encryptObjectPath"); + * encryptOutPath = prop.getProperty("encryptOutPath"); + * keyId = prop.getProperty("keyId"); + * restoreImagePath = prop.getProperty("restoreImagePath"); + * restoreBucket = prop.getProperty("restoreBucket"); + * restoreImageName = prop.getProperty("restoreImageName"); + * bucketNameSc = prop.getProperty("bucketNameSc")+ + * java.util.UUID.randomUUID();; + * keySc = prop.getProperty("keySc"); + * objectPathSc = prop.getProperty("objectPathSc"); + * savePathSc = prop.getProperty("savePathSc"); + * toBucketSc = prop.getProperty("toBucketSc"); + * bucketNameZip = prop.getProperty("bucketNameZip"); + * images = prop.getProperty("images"); + * imageKeys = images.split("[,]", 0); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ + } + + @Test + @Tag("IntegrationTest") + @Order(1) + public void createBucket() { + assertDoesNotThrow(() -> CreateBucket.createBucket(s3, bucketName)); + System.out.println("Test 1 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(2) + public void putObject() { + assertDoesNotThrow(() -> PutObject.putS3Object(s3, bucketName, objectKey, objectPath)); + System.out.println("Test 2 passed"); } - @Test - @Tag("IntegrationTest") - @Order(1) - public void createBucket() { - assertDoesNotThrow(() ->CreateBucket.createBucket(s3,bucketName)); - System.out.println("Test 1 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(2) - public void putObject() { - assertDoesNotThrow(() ->PutObject.putS3Object(s3, bucketName, objectKey, objectPath)); - System.out.println("Test 2 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(3) - public void copyBucketObject() { - String result = CopyObject.copyBucketObject(s3,bucketName,objectKey,toBucket); - assertFalse(result.isEmpty()); - System.out.println("Test 3 passed"); - } + @Test + @Tag("IntegrationTest") + @Order(3) + public void copyBucketObject() { + String result = CopyObject.copyBucketObject(s3, bucketName, objectKey, toBucket); + assertFalse(result.isEmpty()); + System.out.println("Test 3 passed"); + } @Test @Tag("IntegrationTest") @Order(6) public void deleteBucketPolicy() { - assertDoesNotThrow(() ->DeleteBucketPolicy.deleteS3BucketPolicy(s3,bucketNamePolicy)); + assertDoesNotThrow(() -> DeleteBucketPolicy.deleteS3BucketPolicy(s3, bucketNamePolicy)); System.out.println("Test 6 passed"); } - @Test @Tag("IntegrationTest") @Order(7) public void getObjectPresignedUrl() { - assertDoesNotThrow(() ->GetObjectPresignedUrl.getPresignedUrl(presigner, presignBucket, presignKey)); + assertDoesNotThrow(() -> GetObjectPresignedUrl.getPresignedUrl(presigner, presignBucket, presignKey)); System.out.println("Test 8 passed"); } @@ -232,7 +231,7 @@ public void getObjectPresignedUrl() { @Tag("IntegrationTest") @Order(8) public void getObjectData() { - assertDoesNotThrow(() ->GetObjectData.getObjectBytes(s3,bucketName,objectKey, path)); + assertDoesNotThrow(() -> GetObjectData.getObjectBytes(s3, bucketName, objectKey, path)); System.out.println("Test 9 passed"); } @@ -240,7 +239,7 @@ public void getObjectData() { @Tag("IntegrationTest") @Order(9) public void listObjects() { - assertDoesNotThrow(() ->ListObjects.listBucketObjects(s3,bucketName)); + assertDoesNotThrow(() -> ListObjects.listBucketObjects(s3, bucketName)); System.out.println("Test 10 passed"); } @@ -248,8 +247,10 @@ public void listObjects() { @Tag("IntegrationTest") @Order(10) public void createAccessPoint() { - assertDoesNotThrow(() ->CreateAccessPoint.createSpecificAccessPoint(s3ControlClient, accountId, bucketName, accessPointName)); - assertDoesNotThrow(() ->CreateAccessPoint.deleteSpecificAccessPoint(s3ControlClient, accountId, accessPointName)); + assertDoesNotThrow(() -> CreateAccessPoint.createSpecificAccessPoint(s3ControlClient, accountId, bucketName, + accessPointName)); + assertDoesNotThrow( + () -> CreateAccessPoint.deleteSpecificAccessPoint(s3ControlClient, accountId, accessPointName)); System.out.println("Test 11 passed"); } @@ -257,9 +258,9 @@ public void createAccessPoint() { @Tag("IntegrationTest") @Order(11) public void lifecycleConfiguration() { - assertDoesNotThrow(() ->LifecycleConfiguration.setLifecycleConfig(s3, bucketName, accountId)); - assertDoesNotThrow(() ->LifecycleConfiguration.getLifecycleConfig(s3, bucketName, accountId)); - assertDoesNotThrow(() ->LifecycleConfiguration.deleteLifecycleConfig(s3, bucketName, accountId)); + assertDoesNotThrow(() -> LifecycleConfiguration.setLifecycleConfig(s3, bucketName, accountId)); + assertDoesNotThrow(() -> LifecycleConfiguration.getLifecycleConfig(s3, bucketName, accountId)); + assertDoesNotThrow(() -> LifecycleConfiguration.deleteLifecycleConfig(s3, bucketName, accountId)); System.out.println("Test 12 passed"); } @@ -267,9 +268,9 @@ public void lifecycleConfiguration() { @Tag("IntegrationTest") @Order(12) public void s3Cors() { - assertDoesNotThrow(() ->S3Cors.setCorsInformation(s3, bucketName, accountId)); - assertDoesNotThrow(() ->S3Cors.getBucketCorsInformation(s3, bucketName, accountId)); - assertDoesNotThrow(() ->S3Cors.deleteBucketCorsInformation(s3, bucketName, accountId)); + assertDoesNotThrow(() -> S3Cors.setCorsInformation(s3, bucketName, accountId)); + assertDoesNotThrow(() -> S3Cors.getBucketCorsInformation(s3, bucketName, accountId)); + assertDoesNotThrow(() -> S3Cors.deleteBucketCorsInformation(s3, bucketName, accountId)); System.out.println("Test 13 passed"); } @@ -277,7 +278,7 @@ public void s3Cors() { @Tag("IntegrationTest") @Order(13) public void deleteMultiObjects() { - assertDoesNotThrow(() ->DeleteMultiObjects.deleteBucketObjects(s3, bucketName)); + assertDoesNotThrow(() -> DeleteMultiObjects.deleteBucketObjects(s3, bucketName)); System.out.println("Test 14 passed"); } @@ -285,8 +286,8 @@ public void deleteMultiObjects() { @Tag("IntegrationTest") @Order(14) public void deleteObjects() { - assertDoesNotThrow(() ->DeleteObjects.deleteBucketObjects(s3,bucketName,objectKey)); - assertDoesNotThrow(() ->DeleteObjects.deleteBucketObjects(s3,bucketName,encryptObjectName)); + assertDoesNotThrow(() -> DeleteObjects.deleteBucketObjects(s3, bucketName, objectKey)); + assertDoesNotThrow(() -> DeleteObjects.deleteBucketObjects(s3, bucketName, encryptObjectName)); System.out.println("Test 15 passed"); } @@ -294,8 +295,9 @@ public void deleteObjects() { @Tag("IntegrationTest") @Order(15) public void copyObjectStorage() { - assertDoesNotThrow(() ->PutObject.putS3Object(s3, restoreBucket, restoreImageName, restoreImagePath)); - assertDoesNotThrow(() ->CopyObjectStorage.copyBucketObject(s3,restoreBucket, restoreImageName, restoreBucket)); + assertDoesNotThrow(() -> PutObject.putS3Object(s3, restoreBucket, restoreImageName, restoreImagePath)); + assertDoesNotThrow( + () -> CopyObjectStorage.copyBucketObject(s3, restoreBucket, restoreImageName, restoreBucket)); System.out.println("Test 16 passed"); } @@ -303,7 +305,7 @@ public void copyObjectStorage() { @Tag("IntegrationTest") @Order(16) public void restoreObject() { - assertDoesNotThrow(() ->RestoreObject.restoreS3Object(s3, restoreBucket, restoreImageName, accountId)); + assertDoesNotThrow(() -> RestoreObject.restoreS3Object(s3, restoreBucket, restoreImageName, accountId)); System.out.println("Test 17 passed"); } @@ -311,7 +313,7 @@ public void restoreObject() { @Tag("IntegrationTest") @Order(17) public void getRestoreStatus() { - assertDoesNotThrow(() ->GetObjectRestoreStatus.checkStatus(s3, restoreBucket, restoreImageName)); + assertDoesNotThrow(() -> GetObjectRestoreStatus.checkStatus(s3, restoreBucket, restoreImageName)); System.out.println("Test 18 passed"); } @@ -319,7 +321,7 @@ public void getRestoreStatus() { @Tag("IntegrationTest") @Order(18) public void s3ZipExample() { - assertDoesNotThrow(() ->S3ZipExample.createZIPFile(s3, bucketNameZip, imageKeys)); + assertDoesNotThrow(() -> S3ZipExample.createZIPFile(s3, bucketNameZip, imageKeys)); System.out.println("Test 19 passed"); } @@ -327,7 +329,7 @@ public void s3ZipExample() { @Tag("IntegrationTest") @Order(19) public void deleteBucket() { - assertDoesNotThrow(() ->S3Scenario.deleteBucket(s3, bucketName)); + assertDoesNotThrow(() -> S3Scenario.deleteBucket(s3, bucketName)); System.out.println("Test 19 passed"); } @@ -337,58 +339,59 @@ public void deleteBucket() { public void testScenario() { System.out.println(S3Scenario.DASHES); System.out.println("1. Create an Amazon S3 bucket."); - assertDoesNotThrow(() ->S3Scenario.createBucket(s3, bucketNameSc)); - System.out.println( S3Scenario.DASHES); + assertDoesNotThrow(() -> S3Scenario.createBucket(s3, bucketNameSc)); + System.out.println(S3Scenario.DASHES); - System.out.println( S3Scenario.DASHES); + System.out.println(S3Scenario.DASHES); System.out.println("2. Update a local file to the Amazon S3 bucket."); - assertDoesNotThrow(() ->S3Scenario.uploadLocalFile(s3, bucketNameSc, keySc, objectPathSc)); + assertDoesNotThrow(() -> S3Scenario.uploadLocalFile(s3, bucketNameSc, keySc, objectPathSc)); System.out.println(S3Scenario.DASHES); - System.out.println( S3Scenario.DASHES); + System.out.println(S3Scenario.DASHES); System.out.println("3. Download the object to another local file."); - assertDoesNotThrow(() ->S3Scenario.getObjectBytes (s3, bucketNameSc, keySc, savePathSc)); - System.out.println( S3Scenario.DASHES); + assertDoesNotThrow(() -> S3Scenario.getObjectBytes(s3, bucketNameSc, keySc, savePathSc)); + System.out.println(S3Scenario.DASHES); System.out.println(S3Scenario.DASHES); System.out.println("4. Perform a multipart upload."); String multipartKey = "multiPartKey"; - assertDoesNotThrow(() ->S3Scenario.multipartUpload(s3, toBucketSc, multipartKey)); + assertDoesNotThrow(() -> S3Scenario.multipartUpload(s3, toBucketSc, multipartKey)); System.out.println(S3Scenario.DASHES); System.out.println(S3Scenario.DASHES); System.out.println("5. List all objects located in the Amazon S3 bucket."); - assertDoesNotThrow(() ->S3Scenario.listAllObjects(s3, bucketNameSc)); - assertDoesNotThrow(() ->S3Scenario.anotherListExample(s3, bucketNameSc)) ; + assertDoesNotThrow(() -> S3Scenario.listAllObjects(s3, bucketNameSc)); + assertDoesNotThrow(() -> S3Scenario.anotherListExample(s3, bucketNameSc)); System.out.println(S3Scenario.DASHES); System.out.println(S3Scenario.DASHES); System.out.println("6. Copy the object to another Amazon S3 bucket."); - assertDoesNotThrow(() ->S3Scenario.copyBucketObject (s3, bucketNameSc, keySc, toBucketSc)); + assertDoesNotThrow(() -> S3Scenario.copyBucketObject(s3, bucketNameSc, keySc, toBucketSc)); System.out.println(S3Scenario.DASHES); System.out.println(S3Scenario.DASHES); System.out.println("7. Delete the object from the Amazon S3 bucket."); - assertDoesNotThrow(() ->S3Scenario.deleteObjectFromBucket(s3, bucketNameSc, keySc)); + assertDoesNotThrow(() -> S3Scenario.deleteObjectFromBucket(s3, bucketNameSc, keySc)); System.out.println(S3Scenario.DASHES); System.out.println(S3Scenario.DASHES); System.out.println("8. Delete the Amazon S3 bucket."); - assertDoesNotThrow(() ->S3Scenario.deleteBucket(s3, bucketNameSc)); + assertDoesNotThrow(() -> S3Scenario.deleteBucket(s3, bucketNameSc)); System.out.println(S3Scenario.DASHES); System.out.println("Test 20 passed"); } + private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/s3"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -492,6 +495,7 @@ public String getAccountId() { public String getAccessPointName() { return accessPointName; } + public String getEncryptObjectName() { return encryptObjectName; } @@ -549,4 +553,3 @@ public String getImages() { } } } - diff --git a/javav2/example_code/s3/src/test/java/S3TestWatcher.java b/javav2/example_code/s3/src/test/java/S3TestWatcher.java index 161d8f85c20..e2d3afbe0ea 100644 --- a/javav2/example_code/s3/src/test/java/S3TestWatcher.java +++ b/javav2/example_code/s3/src/test/java/S3TestWatcher.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.TestWatcher; import org.slf4j.Logger; diff --git a/javav2/example_code/s3/src/test/java/TransferManagerTest.java b/javav2/example_code/s3/src/test/java/TransferManagerTest.java index f6ce4e556c2..752400b1017 100644 --- a/javav2/example_code/s3/src/test/java/TransferManagerTest.java +++ b/javav2/example_code/s3/src/test/java/TransferManagerTest.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.s3.transfermanager.DownloadFile; import com.example.s3.transfermanager.DownloadToDirectory; import com.example.s3.transfermanager.ObjectCopy; diff --git a/javav2/example_code/s3/src/test/java/com/example/s3/BasicOpsWithChecksumsTests.java b/javav2/example_code/s3/src/test/java/com/example/s3/BasicOpsWithChecksumsTests.java index 07b6e0d69ee..7f9693c1b9a 100644 --- a/javav2/example_code/s3/src/test/java/com/example/s3/BasicOpsWithChecksumsTests.java +++ b/javav2/example_code/s3/src/test/java/com/example/s3/BasicOpsWithChecksumsTests.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; import org.junit.jupiter.api.Assertions; diff --git a/javav2/example_code/s3/src/test/java/com/example/s3/PerformMultiPartUploadTests.java b/javav2/example_code/s3/src/test/java/com/example/s3/PerformMultiPartUploadTests.java index db182eab009..25b01207a99 100644 --- a/javav2/example_code/s3/src/test/java/com/example/s3/PerformMultiPartUploadTests.java +++ b/javav2/example_code/s3/src/test/java/com/example/s3/PerformMultiPartUploadTests.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3; import org.junit.jupiter.api.Assertions; diff --git a/javav2/example_code/s3/src/test/java/com/example/s3/async/AsyncTests.java b/javav2/example_code/s3/src/test/java/com/example/s3/async/AsyncTests.java index 71cedc1d3c3..627eb7a7eac 100644 --- a/javav2/example_code/s3/src/test/java/com/example/s3/async/AsyncTests.java +++ b/javav2/example_code/s3/src/test/java/com/example/s3/async/AsyncTests.java @@ -1,3 +1,5 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.s3.async; import com.example.s3.util.AsyncExampleUtils; diff --git a/javav2/example_code/s3/src/test/java/com/example/s3/presignurl/GeneratePresignedGetUrlTests.java b/javav2/example_code/s3/src/test/java/com/example/s3/presignurl/GeneratePresignedGetUrlTests.java index 445e150328a..7104bb477a7 100644 --- a/javav2/example_code/s3/src/test/java/com/example/s3/presignurl/GeneratePresignedGetUrlTests.java +++ b/javav2/example_code/s3/src/test/java/com/example/s3/presignurl/GeneratePresignedGetUrlTests.java @@ -1,3 +1,6 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.s3.presignurl; import com.example.s3.GeneratePresignedGetUrlAndRetrieve; diff --git a/javav2/example_code/s3/src/test/java/com/example/s3/presignurl/GeneratePresignedPutUrlTests.java b/javav2/example_code/s3/src/test/java/com/example/s3/presignurl/GeneratePresignedPutUrlTests.java index b3060a1098b..ce331823256 100644 --- a/javav2/example_code/s3/src/test/java/com/example/s3/presignurl/GeneratePresignedPutUrlTests.java +++ b/javav2/example_code/s3/src/test/java/com/example/s3/presignurl/GeneratePresignedPutUrlTests.java @@ -1,3 +1,6 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package com.example.s3.presignurl; import com.example.s3.GeneratePresignedUrlAndPutFileWithMetadata; @@ -21,8 +24,8 @@ class GeneratePresignedPutUrlTests { private static final String KEY_NAME = "k-" + UUID.randomUUID(); private static final S3Client s3Client = S3Client.create(); private static final Map METADATA = Map.of("meta1", "value1"); - private static final File PDF_FILE = GeneratePresignedUrlAndPutFileWithMetadata.getFileForForClasspathResource("multipartUploadFiles/s3-userguide.pdf"); - + private static final File PDF_FILE = GeneratePresignedUrlAndPutFileWithMetadata + .getFileForForClasspathResource("multipartUploadFiles/s3-userguide.pdf"); @BeforeAll static void beforeAll() { diff --git a/javav2/example_code/sagemaker/src/main/java/com/example/sage/CreateModel.java b/javav2/example_code/sagemaker/src/main/java/com/example/sage/CreateModel.java index 7754a25715d..6cfa3dda779 100644 --- a/javav2/example_code/sagemaker/src/main/java/com/example/sage/CreateModel.java +++ b/javav2/example_code/sagemaker/src/main/java/com/example/sage/CreateModel.java @@ -1,16 +1,10 @@ -//snippet-sourcedescription:[CreateModel.java demonstrates how to create a model in Amazon SageMaker.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon SageMaker] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.sage; -//snippet-start:[sagemaker.java2.create_model.main] -//snippet-start:[sagemaker.java2.create_model.import] +// snippet-start:[sagemaker.java2.create_model.main] +// snippet-start:[sagemaker.java2.create_model.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sagemaker.SageMakerClient; import software.amazon.awssdk.services.sagemaker.model.ContainerDefinition; @@ -20,10 +14,11 @@ import software.amazon.awssdk.services.sagemaker.model.ImageConfig; import software.amazon.awssdk.services.sagemaker.model.RepositoryAccessMode; import software.amazon.awssdk.services.sagemaker.model.SageMakerException; -//snippet-end:[sagemaker.java2.create_model.import] +// snippet-end:[sagemaker.java2.create_model.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -33,15 +28,15 @@ public class CreateModel { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - dataUrl - The Amazon S3 path where the model artifacts, which result from model training, are stored. - image - The Amazon EC2 Container Registry (Amazon ECR) path where inference code is stored (for example, xxxxx5047983.dkr.ecr.us-west-2.amazonaws.com/train). - modelName - The name of the model. - executionRoleArn - The Amazon Resource Name (ARN) of the IAM role that Amazon SageMaker can assume to access model artifacts (for example, arn:aws:iam::xxxxx5047983:role/service-role/AmazonSageMaker-ExecutionRole-20200627T12xxxx). - """; + Where: + dataUrl - The Amazon S3 path where the model artifacts, which result from model training, are stored. + image - The Amazon EC2 Container Registry (Amazon ECR) path where inference code is stored (for example, xxxxx5047983.dkr.ecr.us-west-2.amazonaws.com/train). + modelName - The name of the model. + executionRoleArn - The Amazon Resource Name (ARN) of the IAM role that Amazon SageMaker can assume to access model artifacts (for example, arn:aws:iam::xxxxx5047983:role/service-role/AmazonSageMaker-ExecutionRole-20200627T12xxxx). + """; if (args.length != 4) { System.out.println(usage); @@ -55,35 +50,35 @@ public static void main(String[] args) { Region region = Region.US_WEST_2; SageMakerClient sageMakerClient = SageMakerClient.builder() - .region(region) - .build(); + .region(region) + .build(); createSagemakerModel(sageMakerClient, dataUrl, image, modelName, executionRoleArn); sageMakerClient.close(); } public static void createSagemakerModel(SageMakerClient sageMakerClient, - String dataUrl, - String image, - String modelName, - String executionRoleArn) { + String dataUrl, + String image, + String modelName, + String executionRoleArn) { try { ImageConfig config = ImageConfig.builder() - .repositoryAccessMode(RepositoryAccessMode.PLATFORM) - .build(); + .repositoryAccessMode(RepositoryAccessMode.PLATFORM) + .build(); ContainerDefinition containerDefinition = ContainerDefinition.builder() - .modelDataUrl(dataUrl) - .imageConfig(config) - .image(image) - .mode(ContainerMode.SINGLE_MODEL) - .build(); + .modelDataUrl(dataUrl) + .imageConfig(config) + .image(image) + .mode(ContainerMode.SINGLE_MODEL) + .build(); CreateModelRequest modelRequest = CreateModelRequest.builder() - .modelName(modelName) - .executionRoleArn(executionRoleArn) - .primaryContainer(containerDefinition) - .build(); + .modelName(modelName) + .executionRoleArn(executionRoleArn) + .primaryContainer(containerDefinition) + .build(); CreateModelResponse response = sageMakerClient.createModel(modelRequest); System.out.println("The ARN of the model is " + response.modelArn()); @@ -94,4 +89,4 @@ public static void createSagemakerModel(SageMakerClient sageMakerClient, } } } -//snippet-end:[sagemaker.java2.create_model.main] +// snippet-end:[sagemaker.java2.create_model.main] diff --git a/javav2/example_code/sagemaker/src/main/java/com/example/sage/CreateTrainingJob.java b/javav2/example_code/sagemaker/src/main/java/com/example/sage/CreateTrainingJob.java index 4b874f39fa0..e4f10a90d79 100644 --- a/javav2/example_code/sagemaker/src/main/java/com/example/sage/CreateTrainingJob.java +++ b/javav2/example_code/sagemaker/src/main/java/com/example/sage/CreateTrainingJob.java @@ -1,16 +1,10 @@ -//snippet-sourcedescription:[CreateTrainingJob.java demonstrates how to start a model training job for Amazon SageMaker.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon SageMaker] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.sage; -//snippet-start:[sagemaker.java2.train_job.main] -//snippet-start:[sagemaker.java2.train_job.import] +// snippet-start:[sagemaker.java2.train_job.main] +// snippet-start:[sagemaker.java2.train_job.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sagemaker.SageMakerClient; import software.amazon.awssdk.services.sagemaker.model.S3DataSource; @@ -30,11 +24,12 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -//snippet-end:[sagemaker.java2.train_job.import] +// snippet-end:[sagemaker.java2.train_job.import] /** - * To set up the model data and other requirements to make this Java V2 example work, follow this AWS tutorial prior to running this Java code example. - * https://aws.amazon.com/getting-started/hands-on/build-train-deploy-machine-learning-model-sagemaker/ + * To set up the model data and other requirements to make this Java V2 example + * work, follow this AWS tutorial prior to running this Java code example. + * https://aws.amazon.com/getting-started/hands-on/build-train-deploy-machine-learning-model-sagemaker/ * * Also, set up your development environment, including your credentials. * @@ -44,128 +39,130 @@ */ public class CreateTrainingJob { - public static void main(String[] args) { - - final String usage = """ - - Usage: - - - Where: - s3UriData - The location of the training data (for example, s3://trainbucket/train.csv). - s3Uri - The Amazon S3 path where you want Amazon SageMaker to store checkpoints (for example, s3://trainbucket). - trainingJobName - The name of the training job.\s - roleArn - The Amazon Resource Name (ARN) of the IAM role that SageMaker uses. - s3OutputPath - The output path located in an Amazon S3 bucket (for example, s3://trainbucket/sagemaker). - channelName - The channel name (for example, s3://trainbucket/sagemaker). - trainingImage - The training image (for example, 000007028032.bbb.zzz.us-west-2.amazonaws.com/xgboost:latest. - """; - - if (args.length != 7) { - System.out.println(usage); - System.exit(1); + public static void main(String[] args) { + + final String usage = """ + + Usage: + + + Where: + s3UriData - The location of the training data (for example, s3://trainbucket/train.csv). + s3Uri - The Amazon S3 path where you want Amazon SageMaker to store checkpoints (for example, s3://trainbucket). + trainingJobName - The name of the training job.\s + roleArn - The Amazon Resource Name (ARN) of the IAM role that SageMaker uses. + s3OutputPath - The output path located in an Amazon S3 bucket (for example, s3://trainbucket/sagemaker). + channelName - The channel name (for example, s3://trainbucket/sagemaker). + trainingImage - The training image (for example, 000007028032.bbb.zzz.us-west-2.amazonaws.com/xgboost:latest. + """; + + if (args.length != 7) { + System.out.println(usage); + System.exit(1); + } + + String s3UriData = args[0]; + String s3Uri = args[1]; + String trainingJobName = args[2]; + String roleArn = args[3]; + String s3OutputPath = args[4]; + String channelName = args[5]; + String trainingImage = args[6]; + + Region region = Region.US_WEST_2; + SageMakerClient sageMakerClient = SageMakerClient.builder() + .region(region) + .build(); + + trainJob(sageMakerClient, s3UriData, s3Uri, trainingJobName, roleArn, s3OutputPath, channelName, + trainingImage); + sageMakerClient.close(); } - String s3UriData = args[0]; - String s3Uri = args[1]; - String trainingJobName = args[2]; - String roleArn = args[3]; - String s3OutputPath = args[4]; - String channelName = args[5]; - String trainingImage = args[6]; - - Region region = Region.US_WEST_2; - SageMakerClient sageMakerClient = SageMakerClient.builder() - .region(region) - .build(); - - trainJob(sageMakerClient, s3UriData, s3Uri, trainingJobName, roleArn, s3OutputPath, channelName, trainingImage); - sageMakerClient.close(); - } - - public static void trainJob(SageMakerClient sageMakerClient, - String s3UriData, - String s3Uri, - String trainingJobName, - String roleArn, - String s3OutputPath, - String channelName, - String trainingImage) { - - try { - S3DataSource s3DataSource = S3DataSource.builder() - .s3Uri(s3UriData) - .s3DataType("S3Prefix") - .s3DataDistributionType("FullyReplicated") - .build(); - - DataSource dataSource = DataSource.builder() - .s3DataSource(s3DataSource) - .build(); - - Channel channel = Channel.builder() - .channelName(channelName) - .contentType("csv") - .dataSource(dataSource) - .build(); - - // Build a list of channels - List myChannel = new ArrayList<>(); - myChannel.add(channel); - - ResourceConfig resourceConfig = ResourceConfig.builder() - .instanceType(TrainingInstanceType.ML_M5_2_XLARGE) // ml.c5.2xlarge - .instanceCount(10) - .volumeSizeInGB(1) - .build(); - - CheckpointConfig checkpointConfig = CheckpointConfig.builder() - .s3Uri(s3Uri) - .build(); - - OutputDataConfig outputDataConfig = OutputDataConfig.builder() - .s3OutputPath(s3OutputPath) - .build(); - - StoppingCondition stoppingCondition = StoppingCondition.builder() - .maxRuntimeInSeconds(1200) - .build(); - - AlgorithmSpecification algorithmSpecification = AlgorithmSpecification.builder() - .trainingImage(trainingImage) - .trainingInputMode(TrainingInputMode.FILE) - .build(); - - // Set hyper parameters. - Map hyperParameters = new HashMap<>(); - hyperParameters.put("num_round", "100"); - hyperParameters.put("eta", "0.2"); - hyperParameters.put("gamma", "4"); - hyperParameters.put("max_depth", "5"); - hyperParameters.put("min_child_weight", "6"); - hyperParameters.put("objective", "binary:logistic"); - hyperParameters.put("silent", "0"); - hyperParameters.put("subsample", "0.8"); - - CreateTrainingJobRequest trainingJobRequest = CreateTrainingJobRequest.builder() - .trainingJobName(trainingJobName) - .algorithmSpecification(algorithmSpecification) - .roleArn(roleArn) - .resourceConfig(resourceConfig) - .checkpointConfig(checkpointConfig) - .inputDataConfig(myChannel) - .outputDataConfig(outputDataConfig) - .stoppingCondition(stoppingCondition) - .hyperParameters(hyperParameters) - .build(); - - CreateTrainingJobResponse jobResponse = sageMakerClient.createTrainingJob(trainingJobRequest); - System.out.println("The Amazon Resource Name (ARN) of the training job is " + jobResponse.trainingJobArn()); - - } catch (SageMakerException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + public static void trainJob(SageMakerClient sageMakerClient, + String s3UriData, + String s3Uri, + String trainingJobName, + String roleArn, + String s3OutputPath, + String channelName, + String trainingImage) { + + try { + S3DataSource s3DataSource = S3DataSource.builder() + .s3Uri(s3UriData) + .s3DataType("S3Prefix") + .s3DataDistributionType("FullyReplicated") + .build(); + + DataSource dataSource = DataSource.builder() + .s3DataSource(s3DataSource) + .build(); + + Channel channel = Channel.builder() + .channelName(channelName) + .contentType("csv") + .dataSource(dataSource) + .build(); + + // Build a list of channels + List myChannel = new ArrayList<>(); + myChannel.add(channel); + + ResourceConfig resourceConfig = ResourceConfig.builder() + .instanceType(TrainingInstanceType.ML_M5_2_XLARGE) // ml.c5.2xlarge + .instanceCount(10) + .volumeSizeInGB(1) + .build(); + + CheckpointConfig checkpointConfig = CheckpointConfig.builder() + .s3Uri(s3Uri) + .build(); + + OutputDataConfig outputDataConfig = OutputDataConfig.builder() + .s3OutputPath(s3OutputPath) + .build(); + + StoppingCondition stoppingCondition = StoppingCondition.builder() + .maxRuntimeInSeconds(1200) + .build(); + + AlgorithmSpecification algorithmSpecification = AlgorithmSpecification.builder() + .trainingImage(trainingImage) + .trainingInputMode(TrainingInputMode.FILE) + .build(); + + // Set hyper parameters. + Map hyperParameters = new HashMap<>(); + hyperParameters.put("num_round", "100"); + hyperParameters.put("eta", "0.2"); + hyperParameters.put("gamma", "4"); + hyperParameters.put("max_depth", "5"); + hyperParameters.put("min_child_weight", "6"); + hyperParameters.put("objective", "binary:logistic"); + hyperParameters.put("silent", "0"); + hyperParameters.put("subsample", "0.8"); + + CreateTrainingJobRequest trainingJobRequest = CreateTrainingJobRequest.builder() + .trainingJobName(trainingJobName) + .algorithmSpecification(algorithmSpecification) + .roleArn(roleArn) + .resourceConfig(resourceConfig) + .checkpointConfig(checkpointConfig) + .inputDataConfig(myChannel) + .outputDataConfig(outputDataConfig) + .stoppingCondition(stoppingCondition) + .hyperParameters(hyperParameters) + .build(); + + CreateTrainingJobResponse jobResponse = sageMakerClient.createTrainingJob(trainingJobRequest); + System.out.println("The Amazon Resource Name (ARN) of the training job is " + + jobResponse.trainingJobArn()); + + } catch (SageMakerException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } } - } } -//snippet-end:[sagemaker.java2.train_job.main] +// snippet-end:[sagemaker.java2.train_job.main] diff --git a/javav2/example_code/sagemaker/src/main/java/com/example/sage/CreateTransformJob.java b/javav2/example_code/sagemaker/src/main/java/com/example/sage/CreateTransformJob.java index f65987d8a8e..a02b3104d38 100644 --- a/javav2/example_code/sagemaker/src/main/java/com/example/sage/CreateTransformJob.java +++ b/javav2/example_code/sagemaker/src/main/java/com/example/sage/CreateTransformJob.java @@ -1,16 +1,10 @@ -//snippet-sourcedescription:[CreateTransformJob.java demonstrates how to start a transform job that uses a trained model to get inferences on a dataset.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon SageMaker] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.sage; -//snippet-start:[sagemaker.java2.transform_job.main] -//snippet-start:[sagemaker.java2.transform_job.import] +// snippet-start:[sagemaker.java2.transform_job.main] +// snippet-start:[sagemaker.java2.transform_job.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sagemaker.SageMakerClient; import software.amazon.awssdk.services.sagemaker.model.TransformS3DataSource; @@ -21,12 +15,12 @@ import software.amazon.awssdk.services.sagemaker.model.CreateTransformJobRequest; import software.amazon.awssdk.services.sagemaker.model.CreateTransformJobResponse; import software.amazon.awssdk.services.sagemaker.model.SageMakerException; -//snippet-end:[sagemaker.java2.transform_job.import] - +// snippet-end:[sagemaker.java2.transform_job.import] /** - * To set up the model data and other requirements to make this Java V2 example work, follow this AWS tutorial prior to running this Java code example. - * https://aws.amazon.com/blogs/machine-learning/predicting-customer-churn-with-amazon-machine-learning/ + * To set up the model data and other requirements to make this Java V2 example + * work, follow this AWS tutorial prior to running this Java code example. + * https://aws.amazon.com/blogs/machine-learning/predicting-customer-churn-with-amazon-machine-learning/ * * Also, set up your development environment, including your credentials. * @@ -35,79 +29,79 @@ * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateTransformJob { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - s3Uri - Identifies the key name of an Amazon S3 object that contains the data (ie, s3://mybucket/churn.txt). - s3OutputPath - The Amazon S3 location where the results are stored. - modelName - The name of the model. - transformJobName - The name of the transform job. - """; - - if (args.length != 4) { - System.out.println(usage); - System.exit(1); + public static void main(String[] args) { + final String usage = """ + + Usage: + + + Where: + s3Uri - Identifies the key name of an Amazon S3 object that contains the data (ie, s3://mybucket/churn.txt). + s3OutputPath - The Amazon S3 location where the results are stored. + modelName - The name of the model. + transformJobName - The name of the transform job. + """; + + if (args.length != 4) { + System.out.println(usage); + System.exit(1); + } + + String s3Uri = args[0]; + String s3OutputPath = args[1]; + String modelName = args[2]; + String transformJobName = args[3]; + Region region = Region.US_WEST_2; + SageMakerClient sageMakerClient = SageMakerClient.builder() + .region(region) + .build(); + + transformJob(sageMakerClient, s3Uri, s3OutputPath, modelName, transformJobName); + sageMakerClient.close(); } - String s3Uri = args[0]; - String s3OutputPath = args[1]; - String modelName = args[2]; - String transformJobName = args[3]; - Region region = Region.US_WEST_2; - SageMakerClient sageMakerClient = SageMakerClient.builder() - .region(region) - .build(); - - transformJob(sageMakerClient, s3Uri, s3OutputPath, modelName, transformJobName); - sageMakerClient.close(); - } - - - public static void transformJob(SageMakerClient sageMakerClient, String s3Uri, String s3OutputPath, String modelName, String transformJobName) { - try { - TransformS3DataSource s3DataSource = TransformS3DataSource.builder() - .s3DataType("S3Prefix") - .s3Uri(s3Uri) - .build(); - - TransformDataSource dataSource = TransformDataSource.builder() - .s3DataSource(s3DataSource) - .build(); - - TransformInput input = TransformInput.builder() - .dataSource(dataSource) - .contentType("text/csv") - .splitType("Line") - .build(); - - TransformOutput output = TransformOutput.builder() - .s3OutputPath(s3OutputPath) - .build(); - - TransformResources resources = TransformResources.builder() - .instanceCount(1) - .instanceType("ml.m4.xlarge") - .build(); - - CreateTransformJobRequest jobRequest = CreateTransformJobRequest.builder() - .transformJobName(transformJobName) - .modelName(modelName) - .transformInput(input) - .transformOutput(output) - .transformResources(resources) - .build(); - - CreateTransformJobResponse jobResponse = sageMakerClient.createTransformJob(jobRequest); - System.out.println("Response " + jobResponse.transformJobArn()); - - } catch (SageMakerException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + public static void transformJob(SageMakerClient sageMakerClient, String s3Uri, String s3OutputPath, + String modelName, String transformJobName) { + try { + TransformS3DataSource s3DataSource = TransformS3DataSource.builder() + .s3DataType("S3Prefix") + .s3Uri(s3Uri) + .build(); + + TransformDataSource dataSource = TransformDataSource.builder() + .s3DataSource(s3DataSource) + .build(); + + TransformInput input = TransformInput.builder() + .dataSource(dataSource) + .contentType("text/csv") + .splitType("Line") + .build(); + + TransformOutput output = TransformOutput.builder() + .s3OutputPath(s3OutputPath) + .build(); + + TransformResources resources = TransformResources.builder() + .instanceCount(1) + .instanceType("ml.m4.xlarge") + .build(); + + CreateTransformJobRequest jobRequest = CreateTransformJobRequest.builder() + .transformJobName(transformJobName) + .modelName(modelName) + .transformInput(input) + .transformOutput(output) + .transformResources(resources) + .build(); + + CreateTransformJobResponse jobResponse = sageMakerClient.createTransformJob(jobRequest); + System.out.println("Response " + jobResponse.transformJobArn()); + + } catch (SageMakerException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } } - } } -//snippet-end:[sagemaker.java2.transform_job.main] +// snippet-end:[sagemaker.java2.transform_job.main] diff --git a/javav2/example_code/sagemaker/src/main/java/com/example/sage/DeleteModel.java b/javav2/example_code/sagemaker/src/main/java/com/example/sage/DeleteModel.java index ebb15a3a019..128cb251b02 100644 --- a/javav2/example_code/sagemaker/src/main/java/com/example/sage/DeleteModel.java +++ b/javav2/example_code/sagemaker/src/main/java/com/example/sage/DeleteModel.java @@ -1,25 +1,19 @@ -//snippet-sourcedescription:[DeleteModel.java demonstrates how to delete a model in Amazon SageMaker.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon SageMaker] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.sage; -//snippet-start:[sagemaker.java2.delete_model.main] -//snippet-start:[sagemaker.java2.delete_model.import] +// snippet-start:[sagemaker.java2.delete_model.main] +// snippet-start:[sagemaker.java2.delete_model.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sagemaker.model.DeleteModelRequest; import software.amazon.awssdk.services.sagemaker.SageMakerClient; import software.amazon.awssdk.services.sagemaker.model.SageMakerException; -//snippet-end:[sagemaker.java2.delete_model.import] - +// snippet-end:[sagemaker.java2.delete_model.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,12 +23,12 @@ public class DeleteModel { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - modelName - The name of the model. - """; + Where: + modelName - The name of the model. + """; if (args.length != 1) { System.out.println(usage); @@ -44,8 +38,8 @@ public static void main(String[] args) { String modelName = args[0]; Region region = Region.US_WEST_2; SageMakerClient sageMakerClient = SageMakerClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteSagemakerModel(sageMakerClient, modelName); sageMakerClient.close(); @@ -54,8 +48,8 @@ public static void main(String[] args) { public static void deleteSagemakerModel(SageMakerClient sageMakerClient, String modelName) { try { DeleteModelRequest deleteModelRequest = DeleteModelRequest.builder() - .modelName(modelName) - .build(); + .modelName(modelName) + .build(); sageMakerClient.deleteModel(deleteModelRequest); @@ -65,4 +59,4 @@ public static void deleteSagemakerModel(SageMakerClient sageMakerClient, String } } } -//snippet-end:[sagemaker.java2.delete_model.main] +// snippet-end:[sagemaker.java2.delete_model.main] diff --git a/javav2/example_code/sagemaker/src/main/java/com/example/sage/DescribeTrainingJob.java b/javav2/example_code/sagemaker/src/main/java/com/example/sage/DescribeTrainingJob.java index 4321fcad362..ac42126b707 100644 --- a/javav2/example_code/sagemaker/src/main/java/com/example/sage/DescribeTrainingJob.java +++ b/javav2/example_code/sagemaker/src/main/java/com/example/sage/DescribeTrainingJob.java @@ -1,24 +1,20 @@ -//snippet-sourcedescription:[DescribeTrainingJob.java demonstrates how to obtain information about a training job.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon SageMaker] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.sage; -//snippet-start:[sagemaker.java2.describe_train_job.main] -//snippet-start:[sagemaker.java2.describe_train_job.import] +// snippet-start:[sagemaker.java2.describe_train_job.main] +// snippet-start:[sagemaker.java2.describe_train_job.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sagemaker.SageMakerClient; import software.amazon.awssdk.services.sagemaker.model.DescribeTrainingJobRequest; import software.amazon.awssdk.services.sagemaker.model.DescribeTrainingJobResponse; import software.amazon.awssdk.services.sagemaker.model.SageMakerException; -//snippet-end:[sagemaker.java2.describe_train_job.import] +// snippet-end:[sagemaker.java2.describe_train_job.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,12 +24,12 @@ public class DescribeTrainingJob { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - trainingJobName - The name of the training job. - """; + Where: + trainingJobName - The name of the training job. + """; if (args.length != 1) { System.out.println(usage); @@ -43,8 +39,8 @@ public static void main(String[] args) { String trainingJobName = args[0]; Region region = Region.US_WEST_2; SageMakerClient sageMakerClient = SageMakerClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeTrainJob(sageMakerClient, trainingJobName); sageMakerClient.close(); @@ -53,8 +49,8 @@ public static void main(String[] args) { public static void describeTrainJob(SageMakerClient sageMakerClient, String trainingJobName) { try { DescribeTrainingJobRequest trainingJobRequest = DescribeTrainingJobRequest.builder() - .trainingJobName(trainingJobName) - .build(); + .trainingJobName(trainingJobName) + .build(); DescribeTrainingJobResponse jobResponse = sageMakerClient.describeTrainingJob(trainingJobRequest); System.out.println("The job status is " + jobResponse.trainingJobStatusAsString()); @@ -65,4 +61,4 @@ public static void describeTrainJob(SageMakerClient sageMakerClient, String trai } } } -//snippet-end:[sagemaker.java2.describe_train_job.main] +// snippet-end:[sagemaker.java2.describe_train_job.main] diff --git a/javav2/example_code/sagemaker/src/main/java/com/example/sage/HelloSageMaker.java b/javav2/example_code/sagemaker/src/main/java/com/example/sage/HelloSageMaker.java index e41f3abd710..ee44da48bf7 100644 --- a/javav2/example_code/sagemaker/src/main/java/com/example/sage/HelloSageMaker.java +++ b/javav2/example_code/sagemaker/src/main/java/com/example/sage/HelloSageMaker.java @@ -1,26 +1,21 @@ -//snippet-sourcedescription:[HelloSageMaker.java demonstrates how to list notebooks.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon SageMaker] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.sage; -//snippet-start:[sagemaker.java2.list_books.import] +// snippet-start:[sagemaker.java2.list_books.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sagemaker.SageMakerClient; import software.amazon.awssdk.services.sagemaker.model.ListNotebookInstancesResponse; import software.amazon.awssdk.services.sagemaker.model.NotebookInstanceSummary; import software.amazon.awssdk.services.sagemaker.model.SageMakerException; import java.util.List; -//snippet-end:[sagemaker.java2.list_books.import] +// snippet-end:[sagemaker.java2.list_books.import] -//snippet-start:[sagemaker.java2.list_books.main] +// snippet-start:[sagemaker.java2.list_books.main] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,8 +25,8 @@ public class HelloSageMaker { public static void main(String[] args) { Region region = Region.US_WEST_2; SageMakerClient sageMakerClient = SageMakerClient.builder() - .region(region) - .build(); + .region(region) + .build(); listBooks(sageMakerClient); sageMakerClient.close(); @@ -51,4 +46,4 @@ public static void listBooks(SageMakerClient sageMakerClient) { } } } -//snippet-end:[sagemaker.java2.list_books.main] +// snippet-end:[sagemaker.java2.list_books.main] diff --git a/javav2/example_code/sagemaker/src/main/java/com/example/sage/InvokeEndpoint.java b/javav2/example_code/sagemaker/src/main/java/com/example/sage/InvokeEndpoint.java index b83c0b75571..c1a0d3d13bd 100644 --- a/javav2/example_code/sagemaker/src/main/java/com/example/sage/InvokeEndpoint.java +++ b/javav2/example_code/sagemaker/src/main/java/com/example/sage/InvokeEndpoint.java @@ -1,35 +1,30 @@ -//snippet-sourcedescription:[InvokeEndpoint.java demonstrates how to get inferences from the model hosted at the specified endpoint .] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon SageMaker] -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.sage; -//snippet-start:[sagemaker.java2._invoke.main] -//snippet-start:[sagemaker.java2._invoke.import] +// snippet-start:[sagemaker.java2._invoke.main] +// snippet-start:[sagemaker.java2._invoke.import] import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sagemakerruntime.SageMakerRuntimeClient; import software.amazon.awssdk.services.sagemakerruntime.model.InvokeEndpointRequest; import software.amazon.awssdk.services.sagemakerruntime.model.InvokeEndpointResponse; import java.nio.charset.Charset; -//snippet-end:[sagemaker.java2._invoke.import] +// snippet-end:[sagemaker.java2._invoke.import] public class InvokeEndpoint { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - endpointName - The name of the endpoint. - payload - The data used to invoke the endpoint. This must be in a valid format. See https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-inference.html. - contentType - The MIME type of the input data in the request body. - """; + Where: + endpointName - The name of the endpoint. + payload - The data used to invoke the endpoint. This must be in a valid format. See https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-inference.html. + contentType - The MIME type of the input data in the request body. + """; if (args.length != 3) { System.out.println(usage); @@ -41,21 +36,22 @@ public static void main(String[] args) { String contentType = args[2]; Region region = Region.US_WEST_2; SageMakerRuntimeClient runtimeClient = SageMakerRuntimeClient.builder() - .region(region) - .build(); + .region(region) + .build(); invokeSpecficEndpoint(runtimeClient, endpointName, payload, contentType); } - public static void invokeSpecficEndpoint(SageMakerRuntimeClient runtimeClient, String endpointName, String payload, String contentType) { + public static void invokeSpecficEndpoint(SageMakerRuntimeClient runtimeClient, String endpointName, String payload, + String contentType) { InvokeEndpointRequest endpointRequest = InvokeEndpointRequest.builder() - .endpointName(endpointName) - .contentType(contentType) - .body(SdkBytes.fromString(payload, Charset.defaultCharset())) - .build(); + .endpointName(endpointName) + .contentType(contentType) + .body(SdkBytes.fromString(payload, Charset.defaultCharset())) + .build(); InvokeEndpointResponse response = runtimeClient.invokeEndpoint(endpointRequest); System.out.println(response.body().asString(Charset.defaultCharset())); } } -//snippet-end:[sagemaker.java2._invoke.main] +// snippet-end:[sagemaker.java2._invoke.main] diff --git a/javav2/example_code/sagemaker/src/main/java/com/example/sage/ListAlgorithms.java b/javav2/example_code/sagemaker/src/main/java/com/example/sage/ListAlgorithms.java index f5aecac622a..8aca5e7d820 100644 --- a/javav2/example_code/sagemaker/src/main/java/com/example/sage/ListAlgorithms.java +++ b/javav2/example_code/sagemaker/src/main/java/com/example/sage/ListAlgorithms.java @@ -1,25 +1,21 @@ -//snippet-sourcedescription:[ListAlgorithms.java demonstrates how to list algorithms.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon SageMaker] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.sage; -//snippet-start:[sagemaker.java2.list_algs.main] -//snippet-start:[sagemaker.java2.list_algs.import] +// snippet-start:[sagemaker.java2.list_algs.main] +// snippet-start:[sagemaker.java2.list_algs.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sagemaker.SageMakerClient; import software.amazon.awssdk.services.sagemaker.model.ListAlgorithmsResponse; import software.amazon.awssdk.services.sagemaker.model.AlgorithmSummary; import software.amazon.awssdk.services.sagemaker.model.SageMakerException; import java.util.List; -//snippet-end:[sagemaker.java2.list_algs.import] +// snippet-end:[sagemaker.java2.list_algs.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,8 +25,8 @@ public class ListAlgorithms { public static void main(String[] args) { Region region = Region.US_WEST_2; SageMakerClient sageMakerClient = SageMakerClient.builder() - .region(region) - .build(); + .region(region) + .build(); listAlgs(sageMakerClient); sageMakerClient.close(); @@ -50,4 +46,4 @@ public static void listAlgs(SageMakerClient sageMakerClient) { } } } -//snippet-end:[sagemaker.java2.list_algs.main] +// snippet-end:[sagemaker.java2.list_algs.main] diff --git a/javav2/example_code/sagemaker/src/main/java/com/example/sage/ListModels.java b/javav2/example_code/sagemaker/src/main/java/com/example/sage/ListModels.java index 370e289bba9..cf4b7c7719b 100644 --- a/javav2/example_code/sagemaker/src/main/java/com/example/sage/ListModels.java +++ b/javav2/example_code/sagemaker/src/main/java/com/example/sage/ListModels.java @@ -1,17 +1,10 @@ -//snippet-sourcedescription:[ListModels.java demonstrates how to retrieve a list of models.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon SageMaker] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.sage; -//snippet-start:[sagemaker.java2.list_models.main] -//snippet-start:[sagemaker.java2.list_models.import] +// snippet-start:[sagemaker.java2.list_models.main] +// snippet-start:[sagemaker.java2.list_models.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sagemaker.SageMakerClient; import software.amazon.awssdk.services.sagemaker.model.ListModelsRequest; @@ -19,10 +12,11 @@ import software.amazon.awssdk.services.sagemaker.model.ModelSummary; import software.amazon.awssdk.services.sagemaker.model.SageMakerException; import java.util.List; -//snippet-end:[sagemaker.java2.list_models.import] +// snippet-end:[sagemaker.java2.list_models.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -33,19 +27,18 @@ public class ListModels { public static void main(String[] args) { Region region = Region.US_WEST_2; SageMakerClient sageMakerClient = SageMakerClient.builder() - .region(region) - .build(); + .region(region) + .build(); listAllModels(sageMakerClient); sageMakerClient.close(); } - public static void listAllModels(SageMakerClient sageMakerClient) { try { ListModelsRequest modelsRequest = ListModelsRequest.builder() - .maxResults(15) - .build(); + .maxResults(15) + .build(); ListModelsResponse modelResponse = sageMakerClient.listModels(modelsRequest); List items = modelResponse.models(); @@ -59,4 +52,4 @@ public static void listAllModels(SageMakerClient sageMakerClient) { } } } -//snippet-end:[sagemaker.java2.list_models.main] +// snippet-end:[sagemaker.java2.list_models.main] diff --git a/javav2/example_code/sagemaker/src/main/java/com/example/sage/ListTrainingJobs.java b/javav2/example_code/sagemaker/src/main/java/com/example/sage/ListTrainingJobs.java index c5c4e505528..d743b7ee430 100644 --- a/javav2/example_code/sagemaker/src/main/java/com/example/sage/ListTrainingJobs.java +++ b/javav2/example_code/sagemaker/src/main/java/com/example/sage/ListTrainingJobs.java @@ -1,16 +1,10 @@ -//snippet-sourcedescription:[ListTrainingJobs.java demonstrates how to retrieve a list of training jobs.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-keyword:[Amazon SageMaker] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.sage; -//snippet-start:[sagemaker.java2.list_jobs.main] -//snippet-start:[sagemaker.java2.list_jobs.import] +// snippet-start:[sagemaker.java2.list_jobs.main] +// snippet-start:[sagemaker.java2.list_jobs.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sagemaker.SageMakerClient; @@ -18,10 +12,11 @@ import software.amazon.awssdk.services.sagemaker.model.SageMakerException; import software.amazon.awssdk.services.sagemaker.model.TrainingJobSummary; import java.util.List; -//snippet-end:[sagemaker.java2.list_jobs.import] +// snippet-end:[sagemaker.java2.list_jobs.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -31,9 +26,9 @@ public class ListTrainingJobs { public static void main(String[] args) { Region region = Region.US_WEST_2; SageMakerClient sageMakerClient = SageMakerClient.builder() - .region(region) - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(ProfileCredentialsProvider.create()) + .build(); listJobs(sageMakerClient); sageMakerClient.close(); @@ -54,8 +49,4 @@ public static void listJobs(SageMakerClient sageMakerClient) { } } } -//snippet-end:[sagemaker.java2.list_jobs.main] - - - - +// snippet-end:[sagemaker.java2.list_jobs.main] diff --git a/javav2/example_code/sagemaker/src/test/java/SageMakerTest.java b/javav2/example_code/sagemaker/src/test/java/SageMakerTest.java index 1b4037566aa..3edb6f750d8 100644 --- a/javav2/example_code/sagemaker/src/test/java/SageMakerTest.java +++ b/javav2/example_code/sagemaker/src/test/java/SageMakerTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.sage.*; import com.google.gson.Gson; @@ -22,7 +20,7 @@ @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class SageMakerTest { - private static SageMakerClient sageMakerClient ; + private static SageMakerClient sageMakerClient; private static String image = ""; private static String modelDataUrl = ""; private static String executionRoleArn = ""; @@ -36,14 +34,13 @@ public class SageMakerTest { private static String trainingImage = ""; private static String existingModel = ""; - @BeforeAll public static void setUp() throws IOException { Region region = Region.US_WEST_2; sageMakerClient = SageMakerClient.builder() - .region(region) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); @@ -52,52 +49,57 @@ public static void setUp() throws IOException { image = values.getImage(); modelDataUrl = values.getModelDataUrl(); executionRoleArn = values.getExecutionRoleArn(); - modelName = values.getModelName()+ java.util.UUID.randomUUID(); + modelName = values.getModelName() + java.util.UUID.randomUUID(); s3UriData = values.getS3UriData(); s3Uri = values.getS3Uri(); roleArn = values.getRoleArn(); - trainingJobName = values.getTrainingJobName()+ java.util.UUID.randomUUID(); + trainingJobName = values.getTrainingJobName() + java.util.UUID.randomUUID(); s3OutputPath = values.getS3OutputPath(); channelName = values.getChannelName(); trainingImage = values.getTrainingImage(); existingModel = values.getModelName(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - - try (InputStream input = SageMakerTest.class.getClassLoader().getResourceAsStream("config.properties")) { - Properties prop = new Properties(); - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - // Populate the data members required for all tests - prop.load(input); - image = prop.getProperty("image"); - modelDataUrl = prop.getProperty("modelDataUrl"); - executionRoleArn = prop.getProperty("executionRoleArn"); - modelName = prop.getProperty("modelName")+ java.util.UUID.randomUUID(); - s3UriData = prop.getProperty("s3UriData"); - s3Uri = prop.getProperty("s3Uri"); - roleArn = prop.getProperty("roleArn"); - trainingJobName = prop.getProperty("trainingJobName")+ java.util.UUID.randomUUID(); - s3OutputPath = prop.getProperty("s3OutputPath"); - channelName = prop.getProperty("channelName"); - trainingImage = prop.getProperty("trainingImage"); - existingModel = prop.getProperty("existingModel"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * + * try (InputStream input = + * SageMakerTest.class.getClassLoader().getResourceAsStream("config.properties") + * ) { + * Properties prop = new Properties(); + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * // Populate the data members required for all tests + * prop.load(input); + * image = prop.getProperty("image"); + * modelDataUrl = prop.getProperty("modelDataUrl"); + * executionRoleArn = prop.getProperty("executionRoleArn"); + * modelName = prop.getProperty("modelName")+ java.util.UUID.randomUUID(); + * s3UriData = prop.getProperty("s3UriData"); + * s3Uri = prop.getProperty("s3Uri"); + * roleArn = prop.getProperty("roleArn"); + * trainingJobName = prop.getProperty("trainingJobName")+ + * java.util.UUID.randomUUID(); + * s3OutputPath = prop.getProperty("s3OutputPath"); + * channelName = prop.getProperty("channelName"); + * trainingImage = prop.getProperty("trainingImage"); + * existingModel = prop.getProperty("existingModel"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } @Test @Tag("IntegrationTest") @Order(1) public void CreateModel() { - assertDoesNotThrow(() ->CreateModel.createSagemakerModel(sageMakerClient, modelDataUrl, image, modelName,executionRoleArn)); + assertDoesNotThrow(() -> CreateModel.createSagemakerModel(sageMakerClient, modelDataUrl, image, modelName, + executionRoleArn)); System.out.println("Test 1 passed"); } @@ -105,7 +107,8 @@ public void CreateModel() { @Tag("IntegrationTest") @Order(2) public void CreateTrainingJob() { - assertDoesNotThrow(() ->CreateTrainingJob.trainJob(sageMakerClient, s3UriData, s3Uri, trainingJobName, roleArn, s3OutputPath, channelName, trainingImage)); + assertDoesNotThrow(() -> CreateTrainingJob.trainJob(sageMakerClient, s3UriData, s3Uri, trainingJobName, roleArn, + s3OutputPath, channelName, trainingImage)); System.out.println("Test 2 passed"); } @@ -113,7 +116,7 @@ public void CreateTrainingJob() { @Tag("IntegrationTest") @Order(3) public void DescribeTrainingJob() { - assertDoesNotThrow(() ->DescribeTrainingJob.describeTrainJob(sageMakerClient, trainingJobName)); + assertDoesNotThrow(() -> DescribeTrainingJob.describeTrainJob(sageMakerClient, trainingJobName)); System.out.println("Test 3 passed"); } @@ -121,7 +124,7 @@ public void DescribeTrainingJob() { @Tag("IntegrationTest") @Order(4) public void ListModels() { - assertDoesNotThrow(() ->ListModels.listAllModels(sageMakerClient)); + assertDoesNotThrow(() -> ListModels.listAllModels(sageMakerClient)); System.out.println("Test 4 passed"); } @@ -129,7 +132,7 @@ public void ListModels() { @Tag("IntegrationTest") @Order(5) public void ListNotebooks() { - assertDoesNotThrow(() ->ListNotebooks.listBooks(sageMakerClient)); + assertDoesNotThrow(() -> ListNotebooks.listBooks(sageMakerClient)); System.out.println("Test 5 passed"); } @@ -137,7 +140,7 @@ public void ListNotebooks() { @Tag("IntegrationTest") @Order(6) public void ListAlgorithms() { - assertDoesNotThrow(() ->ListAlgorithms.listAlgs(sageMakerClient)); + assertDoesNotThrow(() -> ListAlgorithms.listAlgs(sageMakerClient)); System.out.println("Test 6 passed"); } @@ -145,7 +148,7 @@ public void ListAlgorithms() { @Tag("IntegrationTest") @Order(7) public void ListTrainingJobs() { - assertDoesNotThrow(() ->ListTrainingJobs.listJobs(sageMakerClient)); + assertDoesNotThrow(() -> ListTrainingJobs.listJobs(sageMakerClient)); System.out.println("Test 7 passed"); } @@ -153,19 +156,20 @@ public void ListTrainingJobs() { @Tag("IntegrationTest") @Order(8) public void DeleteModel() { - assertDoesNotThrow(() ->DeleteModel.deleteSagemakerModel(sageMakerClient, modelName)); + assertDoesNotThrow(() -> DeleteModel.deleteSagemakerModel(sageMakerClient, modelName)); System.out.println("Test 8 passed"); } + private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/sagemaker"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -238,4 +242,3 @@ public String getTrainingImage() { } } } - diff --git a/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/CreateSecret.java b/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/CreateSecret.java index 3e46500aa07..72f8e8dab28 100644 --- a/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/CreateSecret.java +++ b/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/CreateSecret.java @@ -1,25 +1,20 @@ -//snippet-sourcedescription:[CreateSecret.java demonstrates how to create a secret for AWS Secrets Manager.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Secrets Manager] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.secrets; -//snippet-start:[secretsmanager.java2.create_secret.main] -//snippet-start:[secretsmanager.java2.create_secret.import] +// snippet-start:[secretsmanager.java2.create_secret.main] +// snippet-start:[secretsmanager.java2.create_secret.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.CreateSecretRequest; import software.amazon.awssdk.services.secretsmanager.model.CreateSecretResponse; import software.amazon.awssdk.services.secretsmanager.model.SecretsManagerException; -//snippet-end:[secretsmanager.java2.create_secret.import] +// snippet-end:[secretsmanager.java2.create_secret.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,13 +24,13 @@ public class CreateSecret { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - secretName - The name of the secret (for example, tutorials/MyFirstSecret).\s - secretValue - The secret value.\s - """; + Where: + secretName - The name of the secret (for example, tutorials/MyFirstSecret).\s + secretValue - The secret value.\s + """; if (args.length != 2) { System.out.println(usage); @@ -46,8 +41,8 @@ public static void main(String[] args) { String secretValue = args[1]; Region region = Region.US_EAST_1; SecretsManagerClient secretsClient = SecretsManagerClient.builder() - .region(region) - .build(); + .region(region) + .build(); String secretARN = createNewSecret(secretsClient, secretName, secretValue); System.out.println("The secret ARN is " + secretARN); @@ -57,10 +52,10 @@ public static void main(String[] args) { public static String createNewSecret(SecretsManagerClient secretsClient, String secretName, String secretValue) { try { CreateSecretRequest secretRequest = CreateSecretRequest.builder() - .name(secretName) - .description("This secret was created by the AWS Secret Manager Java API") - .secretString(secretValue) - .build(); + .name(secretName) + .description("This secret was created by the AWS Secret Manager Java API") + .secretString(secretValue) + .build(); CreateSecretResponse secretResponse = secretsClient.createSecret(secretRequest); return secretResponse.arn(); @@ -72,4 +67,4 @@ public static String createNewSecret(SecretsManagerClient secretsClient, String return ""; } } -//snippet-end:[secretsmanager.java2.create_secret.main] +// snippet-end:[secretsmanager.java2.create_secret.main] diff --git a/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/DeleteSecret.java b/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/DeleteSecret.java index 2334ebfec4a..e7f2167f015 100644 --- a/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/DeleteSecret.java +++ b/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/DeleteSecret.java @@ -1,24 +1,19 @@ -//snippet-sourcedescription:[DeleteSecret.java demonstrates how to delete a secret.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Secrets Manager] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.secrets; -//snippet-start:[secretsmanager.java2.delete_secret.main] -//snippet-start:[secretsmanager.java2.delete_secret.import] +// snippet-start:[secretsmanager.java2.delete_secret.main] +// snippet-start:[secretsmanager.java2.delete_secret.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.DeleteSecretRequest; import software.amazon.awssdk.services.secretsmanager.model.SecretsManagerException; -//snippet-end:[secretsmanager.java2.delete_secret.import] +// snippet-end:[secretsmanager.java2.delete_secret.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -29,12 +24,12 @@ public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - secretName - The name of the secret (for example, tutorials/MyFirstSecret).\s - """; + Where: + secretName - The name of the secret (for example, tutorials/MyFirstSecret).\s + """; if (args.length != 1) { System.out.println(usage); @@ -44,8 +39,8 @@ public static void main(String[] args) { String secretName = args[0]; Region region = Region.US_EAST_1; SecretsManagerClient secretsClient = SecretsManagerClient.builder() - .region(region) - .build(); + .region(region) + .build(); deleteSpecificSecret(secretsClient, secretName); secretsClient.close(); @@ -54,8 +49,8 @@ public static void main(String[] args) { public static void deleteSpecificSecret(SecretsManagerClient secretsClient, String secretName) { try { DeleteSecretRequest secretRequest = DeleteSecretRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); secretsClient.deleteSecret(secretRequest); System.out.println(secretName + " is deleted."); @@ -66,4 +61,4 @@ public static void deleteSpecificSecret(SecretsManagerClient secretsClient, Stri } } } -//snippet-end:[secretsmanager.java2.delete_secret.main] +// snippet-end:[secretsmanager.java2.delete_secret.main] diff --git a/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/DescribeSecret.java b/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/DescribeSecret.java index d629d4f2ddb..e614c6c223d 100644 --- a/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/DescribeSecret.java +++ b/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/DescribeSecret.java @@ -1,15 +1,10 @@ -//snippet-sourcedescription:[DescribeSecret.java demonstrates how to describe a secret.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Secrets Manager] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ package com.example.secrets; -//snippet-start:[secretsmanager.java2.describe_secret.main] -//snippet-start:[secretsmanager.java2.describe_secret.import] +// snippet-start:[secretsmanager.java2.describe_secret.main] +// snippet-start:[secretsmanager.java2.describe_secret.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.DescribeSecretRequest; @@ -20,10 +15,11 @@ import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.util.Locale; -//snippet-end:[secretsmanager.java2.describe_secret.import] +// snippet-end:[secretsmanager.java2.describe_secret.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -33,12 +29,12 @@ public class DescribeSecret { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - secretName - The name of the secret (for example, tutorials/MyFirstSecret).\s - """; + Where: + secretName - The name of the secret (for example, tutorials/MyFirstSecret).\s + """; if (args.length != 1) { System.out.println(usage); @@ -48,8 +44,8 @@ public static void main(String[] args) { String secretName = args[0]; Region region = Region.US_EAST_1; SecretsManagerClient secretsClient = SecretsManagerClient.builder() - .region(region) - .build(); + .region(region) + .build(); describeGivenSecret(secretsClient, secretName); secretsClient.close(); @@ -58,15 +54,14 @@ public static void main(String[] args) { public static void describeGivenSecret(SecretsManagerClient secretsClient, String secretName) { try { DescribeSecretRequest secretRequest = DescribeSecretRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); DescribeSecretResponse secretResponse = secretsClient.describeSecret(secretRequest); Instant lastChangedDate = secretResponse.lastChangedDate(); // Convert the Instant to readable date. - DateTimeFormatter formatter = - DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) + DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) .withLocale(Locale.US) .withZone(ZoneId.systemDefault()); @@ -79,4 +74,4 @@ public static void describeGivenSecret(SecretsManagerClient secretsClient, Strin } } } -//snippet-end:[secretsmanager.java2.describe_secret.main] +// snippet-end:[secretsmanager.java2.describe_secret.main] diff --git a/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/GetSecretValue.java b/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/GetSecretValue.java index 5ab3ad75dfe..9213cd3e4a3 100644 --- a/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/GetSecretValue.java +++ b/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/GetSecretValue.java @@ -1,25 +1,20 @@ -//snippet-sourcedescription:[GetSecretValue.java demonstrates how to get the value of a secret from AWS Secrets Manager.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Secrets Manager] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.secrets; -//snippet-start:[secretsmanager.java2.get_secret.main] -//snippet-start:[secretsmanager.java2.get_secret.import] +// snippet-start:[secretsmanager.java2.get_secret.main] +// snippet-start:[secretsmanager.java2.get_secret.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; import software.amazon.awssdk.services.secretsmanager.model.SecretsManagerException; -//snippet-end:[secretsmanager.java2.get_secret.import] +// snippet-end:[secretsmanager.java2.get_secret.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -27,7 +22,8 @@ * * We recommend that you cache your secret values by using client-side caching. * - * Caching secrets improves speed and reduces your costs. For more information, see the following documentation topic: + * Caching secrets improves speed and reduces your costs. For more information, + * see the following documentation topic: * * https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieving-secrets.html */ @@ -35,12 +31,12 @@ public class GetSecretValue { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - secretName - The name of the secret (for example, tutorials/MyFirstSecret).\s - """; + Where: + secretName - The name of the secret (for example, tutorials/MyFirstSecret).\s + """; if (args.length != 1) { System.out.println(usage); @@ -50,8 +46,8 @@ public static void main(String[] args) { String secretName = args[0]; Region region = Region.US_EAST_1; SecretsManagerClient secretsClient = SecretsManagerClient.builder() - .region(region) - .build(); + .region(region) + .build(); getValue(secretsClient, secretName); secretsClient.close(); @@ -60,8 +56,8 @@ public static void main(String[] args) { public static void getValue(SecretsManagerClient secretsClient, String secretName) { try { GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretsClient.getSecretValue(valueRequest); String secret = valueResponse.secretString(); @@ -73,4 +69,4 @@ public static void getValue(SecretsManagerClient secretsClient, String secretNam } } } -//snippet-end:[secretsmanager.java2.get_secret.main] +// snippet-end:[secretsmanager.java2.get_secret.main] diff --git a/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/ListSecrets.java b/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/ListSecrets.java index e071a2d352c..da319a6bbc2 100644 --- a/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/ListSecrets.java +++ b/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/ListSecrets.java @@ -1,26 +1,21 @@ -//snippet-sourcedescription:[ListSecrets.java demonstrates how to list all of the secrets that are stored by Secrets Manager.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Secrets Manager] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.secrets; -//snippet-start:[secretsmanager.java2.list_secrets.main] -//snippet-start:[secretsmanager.java2.list_secrets.import] +// snippet-start:[secretsmanager.java2.list_secrets.main] +// snippet-start:[secretsmanager.java2.list_secrets.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.ListSecretsResponse; import software.amazon.awssdk.services.secretsmanager.model.SecretListEntry; import software.amazon.awssdk.services.secretsmanager.model.SecretsManagerException; import java.util.List; -//snippet-end:[secretsmanager.java2.list_secrets.import] +// snippet-end:[secretsmanager.java2.list_secrets.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -30,8 +25,8 @@ public class ListSecrets { public static void main(String[] args) { Region region = Region.US_EAST_1; SecretsManagerClient secretsClient = SecretsManagerClient.builder() - .region(region) - .build(); + .region(region) + .build(); listAllSecrets(secretsClient); secretsClient.close(); @@ -52,4 +47,4 @@ public static void listAllSecrets(SecretsManagerClient secretsClient) { } } } -//snippet-end:[secretsmanager.java2.list_secrets.main] +// snippet-end:[secretsmanager.java2.list_secrets.main] diff --git a/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/PutSecret.java b/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/PutSecret.java index 7eb2aafbe15..cba389a923b 100644 --- a/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/PutSecret.java +++ b/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/PutSecret.java @@ -1,24 +1,19 @@ -//snippet-sourcedescription:[PutSecret.java demonstrates how to create a new version with a new encrypted secret value and attaches it to the secret.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Secrets Manager] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.secrets; -//snippet-start:[secretsmanager.java2.put_secret.main] -//snippet-start:[secretsmanager.java2.put_secret.import] +// snippet-start:[secretsmanager.java2.put_secret.main] +// snippet-start:[secretsmanager.java2.put_secret.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.PutSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.SecretsManagerException; -//snippet-end:[secretsmanager.java2.put_secret.import] +// snippet-end:[secretsmanager.java2.put_secret.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,13 +23,13 @@ public class PutSecret { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - secretName - The name of the secret (for example, tutorials/MyFirstSecret).\s - secretValue - The text to encrypt and store in the new version of the secret.\s - """; + Where: + secretName - The name of the secret (for example, tutorials/MyFirstSecret).\s + secretValue - The text to encrypt and store in the new version of the secret.\s + """; if (args.length < 2) { System.out.println(usage); @@ -45,8 +40,8 @@ public static void main(String[] args) { String secretValue = args[1]; Region region = Region.US_EAST_1; SecretsManagerClient secretsClient = SecretsManagerClient.builder() - .region(region) - .build(); + .region(region) + .build(); putSecret(secretsClient, secretName, secretValue); secretsClient.close(); @@ -55,9 +50,9 @@ public static void main(String[] args) { public static void putSecret(SecretsManagerClient secretsClient, String secretName, String secretValue) { try { PutSecretValueRequest secretRequest = PutSecretValueRequest.builder() - .secretId(secretName) - .secretString(secretValue) - .build(); + .secretId(secretName) + .secretString(secretValue) + .build(); secretsClient.putSecretValue(secretRequest); System.out.println("A new version was created."); @@ -68,4 +63,4 @@ public static void putSecret(SecretsManagerClient secretsClient, String secretNa } } } -//snippet-end:[secretsmanager.java2.put_secret.main] +// snippet-end:[secretsmanager.java2.put_secret.main] diff --git a/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/UpdateSecret.java b/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/UpdateSecret.java index 754f6e533a3..ffcd897a954 100644 --- a/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/UpdateSecret.java +++ b/javav2/example_code/secretsmanager/src/main/java/com/example/secrets/UpdateSecret.java @@ -1,24 +1,19 @@ -//snippet-sourcedescription:[UpdateSecret.java demonstrates how to update a secret for AWS Secrets Manager.] -//snippet-keyword:[AWS SDK for Java v2] -//snippet-service:[AWS Secrets Manager] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.secrets; -//snippet-start:[secretsmanager.java2.update_secret.main] -//snippet-start:[secretsmanager.java2.update_secret.import] +// snippet-start:[secretsmanager.java2.update_secret.main] +// snippet-start:[secretsmanager.java2.update_secret.import] import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.SecretsManagerException; import software.amazon.awssdk.services.secretsmanager.model.UpdateSecretRequest; -//snippet-end:[secretsmanager.java2.update_secret.import] +// snippet-end:[secretsmanager.java2.update_secret.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -28,13 +23,13 @@ public class UpdateSecret { public static void main(String[] args) { final String usage = """ - Usage: - + Usage: + - Where: - secretName - The name of the secret (for example, tutorials/MyFirstSecret).\s - secretValue - The secret value that is updated.\s - """; + Where: + secretName - The name of the secret (for example, tutorials/MyFirstSecret).\s + secretValue - The secret value that is updated.\s + """; if (args.length < 2) { System.out.println(usage); @@ -45,8 +40,8 @@ public static void main(String[] args) { String secretValue = args[1]; Region region = Region.US_EAST_1; SecretsManagerClient secretsClient = SecretsManagerClient.builder() - .region(region) - .build(); + .region(region) + .build(); updateMySecret(secretsClient, secretName, secretValue); secretsClient.close(); @@ -55,9 +50,9 @@ public static void main(String[] args) { public static void updateMySecret(SecretsManagerClient secretsClient, String secretName, String secretValue) { try { UpdateSecretRequest secretRequest = UpdateSecretRequest.builder() - .secretId(secretName) - .secretString(secretValue) - .build(); + .secretId(secretName) + .secretString(secretValue) + .build(); secretsClient.updateSecret(secretRequest); @@ -67,4 +62,4 @@ public static void updateMySecret(SecretsManagerClient secretsClient, String sec } } } -//snippet-end:[secretsmanager.java2.update_secret.main] +// snippet-end:[secretsmanager.java2.update_secret.main] diff --git a/javav2/example_code/secretsmanager/src/test/java/SecretManagerTest.java b/javav2/example_code/secretsmanager/src/test/java/SecretManagerTest.java index beb35099889..9bc7bd8c673 100644 --- a/javav2/example_code/secretsmanager/src/test/java/SecretManagerTest.java +++ b/javav2/example_code/secretsmanager/src/test/java/SecretManagerTest.java @@ -1,7 +1,5 @@ -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 import com.example.secrets.*; import com.google.gson.Gson; @@ -26,56 +24,60 @@ public class SecretManagerTest { private static SecretsManagerClient secretsClient; - private static String newSecretName=""; - private static String secretValue=""; - private static String secretARN=""; - private static String modSecretValue=""; + private static String newSecretName = ""; + private static String secretValue = ""; + private static String secretARN = ""; + private static String modSecretValue = ""; @BeforeAll public static void setUp() throws IOException, URISyntaxException { Region region = Region.US_EAST_1; secretsClient = SecretsManagerClient.builder() - .region(region) - .credentialsProvider(ProfileCredentialsProvider.create()) - .build(); + .region(region) + .credentialsProvider(ProfileCredentialsProvider.create()) + .build(); Random random = new Random(); int randomNum = random.nextInt((10000 - 1) + 1) + 1; // Get the values to run these tests from AWS Secrets Manager. Gson gson = new Gson(); String json = getSecretValues(); SecretValues values = gson.fromJson(json, SecretValues.class); - newSecretName = values.getNewSecretName()+randomNum; + newSecretName = values.getNewSecretName() + randomNum; secretValue = values.getSecretValue(); modSecretValue = values.getModSecretValue(); - // Uncomment this code block if you prefer using a config.properties file to retrieve AWS values required for these tests. - /* - try (InputStream input = SecretManagerTest.class.getClassLoader().getResourceAsStream("config.properties")) { - - Properties prop = new Properties(); - - if (input == null) { - System.out.println("Sorry, unable to find config.properties"); - return; - } - - //load a properties file from class path, inside static method - prop.load(input); - - // Populate the data members required for all tests - newSecretName = prop.getProperty("newSecretName"); - secretValue = prop.getProperty("secretValue"); - modSecretValue = prop.getProperty("modSecretValue"); - - } catch (IOException ex) { - ex.printStackTrace(); - } - */ + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * try (InputStream input = + * SecretManagerTest.class.getClassLoader().getResourceAsStream( + * "config.properties")) { + * + * Properties prop = new Properties(); + * + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * + * //load a properties file from class path, inside static method + * prop.load(input); + * + * // Populate the data members required for all tests + * newSecretName = prop.getProperty("newSecretName"); + * secretValue = prop.getProperty("secretValue"); + * modSecretValue = prop.getProperty("modSecretValue"); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ } + @Test @Order(1) public void CreateSecret() { - secretARN = CreateSecret.createNewSecret(secretsClient, newSecretName,secretValue); + secretARN = CreateSecret.createNewSecret(secretsClient, newSecretName, secretValue); assertFalse(secretARN.isEmpty()); System.out.println("Test 2 passed"); } @@ -83,28 +85,28 @@ public void CreateSecret() { @Test @Order(2) public void DescribeSecret() { - assertDoesNotThrow(() ->DescribeSecret.describeGivenSecret(secretsClient, secretARN)); + assertDoesNotThrow(() -> DescribeSecret.describeGivenSecret(secretsClient, secretARN)); System.out.println("Test 3 passed"); } @Test @Order(3) public void GetSecretValue() { - assertDoesNotThrow(() ->GetSecretValue.getValue(secretsClient, secretARN)); + assertDoesNotThrow(() -> GetSecretValue.getValue(secretsClient, secretARN)); System.out.println("Test 4 passed"); } @Test @Order(4) public void UpdateSecret() { - assertDoesNotThrow(() ->UpdateSecret.updateMySecret(secretsClient,secretARN, modSecretValue)); + assertDoesNotThrow(() -> UpdateSecret.updateMySecret(secretsClient, secretARN, modSecretValue)); System.out.println("Test 5 passed"); } @Test @Order(5) public void ListSecrets() { - assertDoesNotThrow(() ->ListSecrets.listAllSecrets(secretsClient)); + assertDoesNotThrow(() -> ListSecrets.listAllSecrets(secretsClient)); System.out.println("Test 6 passed"); } @@ -117,14 +119,14 @@ public void DeleteSecret() { private static String getSecretValues() { SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); String secretName = "test/secretmanager"; GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); + .secretId(secretName) + .build(); GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); return valueResponse.secretString(); @@ -150,5 +152,3 @@ public String getModSecretValue() { } } } - - diff --git a/javav2/example_code/ses/src/main/java/com/example/ses/ListIdentities.java b/javav2/example_code/ses/src/main/java/com/example/ses/ListIdentities.java index 1c4b3debaa9..6a7b04f6ff3 100644 --- a/javav2/example_code/ses/src/main/java/com/example/ses/ListIdentities.java +++ b/javav2/example_code/ses/src/main/java/com/example/ses/ListIdentities.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[ListIdentities.java demonstrates how to obtain a list of identities for your AWS account.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-keyword:[Amazon Simple Email Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.ses; @@ -21,7 +14,8 @@ // snippet-end:[ses.java2.identities.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,8 +26,8 @@ public class ListIdentities { public static void main(String[] args) throws IOException { Region region = Region.US_WEST_2; SesClient client = SesClient.builder() - .region(region) - .build(); + .region(region) + .build(); listSESIdentities(client); } diff --git a/javav2/example_code/ses/src/main/java/com/example/ses/SendMessage.java b/javav2/example_code/ses/src/main/java/com/example/ses/SendMessage.java index 153d9621aa0..25d9ddf7dd5 100644 --- a/javav2/example_code/ses/src/main/java/com/example/ses/SendMessage.java +++ b/javav2/example_code/ses/src/main/java/com/example/ses/SendMessage.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[SendMessage.java demonstrates how to send an email message by using the Amazon Simple Email Service (Amazon SES).] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-keyword:[Amazon Simple Email Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[ses.java2.sendmessage.complete] package com.example.ses; @@ -34,7 +27,8 @@ // snippet-end:[ses.java2.sendmessage.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -44,27 +38,27 @@ public class SendMessage { public static void main(String[] args) throws IOException { final String usage = """ - Usage: - \s + Usage: + \s - Where: - sender - An email address that represents the sender.\s - recipient - An email address that represents the recipient.\s - subject - The subject line.\s - """; + Where: + sender - An email address that represents the sender.\s + recipient - An email address that represents the recipient.\s + subject - The subject line.\s + """; - if (args.length != 3) { - System.out.println(usage); - System.exit(1); - } + if (args.length != 3) { + System.out.println(usage); + System.exit(1); + } String sender = args[0]; String recipient = args[1]; String subject = args[2]; Region region = Region.US_EAST_1; SesClient client = SesClient.builder() - .region(region) - .build(); + .region(region) + .build(); // The email body for non-HTML email clients. String bodyText = "Hello,\r\n" + "See the list of customers. "; @@ -84,12 +78,11 @@ public static void main(String[] args) throws IOException { } public static void send(SesClient client, - String sender, - String recipient, - String subject, - String bodyText, - String bodyHTML - ) throws MessagingException, IOException { + String sender, + String recipient, + String subject, + String bodyText, + String bodyHTML) throws MessagingException, IOException { Session session = Session.getDefaultInstance(new Properties()); MimeMessage message = new MimeMessage(session); @@ -140,16 +133,16 @@ public static void send(SesClient client, SdkBytes data = SdkBytes.fromByteArray(arr); RawMessage rawMessage = RawMessage.builder() - .data(data) - .build(); + .data(data) + .build(); AwsRequestOverrideConfiguration myConf = AwsRequestOverrideConfiguration.builder() - .build() ; + .build(); SendRawEmailRequest rawEmailRequest = SendRawEmailRequest.builder() - .rawMessage(rawMessage) - .overrideConfiguration(myConf) - .build(); + .rawMessage(rawMessage) + .overrideConfiguration(myConf) + .build(); client.sendRawEmail(rawEmailRequest); System.out.println("Email message Sent"); diff --git a/javav2/example_code/ses/src/main/java/com/example/ses/SendMessageAttachment.java b/javav2/example_code/ses/src/main/java/com/example/ses/SendMessageAttachment.java index 18d3d6819ba..bb9e6123783 100644 --- a/javav2/example_code/ses/src/main/java/com/example/ses/SendMessageAttachment.java +++ b/javav2/example_code/ses/src/main/java/com/example/ses/SendMessageAttachment.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[SendMessageAttachment.java demonstrates how to send an email message with an attachment by using the Amazon Simple Email Service (Amazon SES).] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-keyword:[Amazon Simple Email Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 // snippet-start:[ses.java2.sendmessageattachment.complete] package com.example.ses; @@ -38,7 +31,8 @@ // snippet-end:[ses.java2.sendmessageattachment.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -49,15 +43,15 @@ public class SendMessageAttachment { public static void main(String[] args) throws IOException { final String usage = """ - Usage: - \s + Usage: + \s - Where: - sender - An email address that represents the sender.\s - recipient - An email address that represents the recipient.\s - subject - The subject line.\s - fileLocation - The location of a Microsoft Excel file to use as an attachment (C:/AWS/customers.xls).\s - """; + Where: + sender - An email address that represents the sender.\s + recipient - An email address that represents the recipient.\s + subject - The subject line.\s + fileLocation - The location of a Microsoft Excel file to use as an attachment (C:/AWS/customers.xls).\s + """; if (args.length != 4) { System.out.println(usage); @@ -71,16 +65,17 @@ public static void main(String[] args) throws IOException { // The email body for recipients with non-HTML email clients. String bodyText = "Hello,\r\n" + "Please see the attached file for a list " - + "of customers to contact."; + + "of customers to contact."; // The HTML body of the email. String bodyHTML = "" + "" + "" + "

    Hello!

    " - + "

    Please see the attached file for a " + "list of customers to contact.

    " + "" + ""; + + "

    Please see the attached file for a " + "list of customers to contact.

    " + "" + + ""; Region region = Region.US_WEST_2; SesClient client = SesClient.builder() - .region(region) - .build(); + .region(region) + .build(); try { sendemailAttachment(client, sender, recipient, subject, bodyText, bodyHTML, fileLocation); @@ -93,12 +88,12 @@ public static void main(String[] args) throws IOException { } public static void sendemailAttachment(SesClient client, - String sender, - String recipient, - String subject, - String bodyText, - String bodyHTML, - String fileLocation) throws AddressException, MessagingException, IOException { + String sender, + String recipient, + String subject, + String bodyText, + String bodyHTML, + String fileLocation) throws AddressException, MessagingException, IOException { java.io.File theFile = new java.io.File(fileLocation); byte[] fileContent = Files.readAllBytes(theFile.toPath()); @@ -143,7 +138,8 @@ public static void sendemailAttachment(SesClient client, // Define the attachment. MimeBodyPart att = new MimeBodyPart(); - DataSource fds = new ByteArrayDataSource(fileContent, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + DataSource fds = new ByteArrayDataSource(fileContent, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); att.setDataHandler(new DataHandler(fds)); String reportName = "WorkReport.xls"; @@ -165,12 +161,12 @@ public static void sendemailAttachment(SesClient client, SdkBytes data = SdkBytes.fromByteArray(arr); RawMessage rawMessage = RawMessage.builder() - .data(data) - .build(); + .data(data) + .build(); SendRawEmailRequest rawEmailRequest = SendRawEmailRequest.builder() - .rawMessage(rawMessage) - .build(); + .rawMessage(rawMessage) + .build(); client.sendRawEmail(rawEmailRequest); diff --git a/javav2/example_code/ses/src/main/java/com/example/ses/SendMessageEmailRequest.java b/javav2/example_code/ses/src/main/java/com/example/ses/SendMessageEmailRequest.java index a08cf8922c0..775601587e2 100644 --- a/javav2/example_code/ses/src/main/java/com/example/ses/SendMessageEmailRequest.java +++ b/javav2/example_code/ses/src/main/java/com/example/ses/SendMessageEmailRequest.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[SendMessage.java demonstrates how to send an email message by using the Amazon Simple Email Service (Amazon SES) and a SendEmailRequest object.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-keyword:[Amazon Simple Email Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.ses; @@ -25,7 +18,8 @@ // snippet-end:[ses.java2.sendmessage.request.import] /** - * Before running this Java V2 code example, set up your development environment, including your credentials. + * Before running this Java V2 code example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -35,14 +29,14 @@ public class SendMessageEmailRequest { public static void main(String[] args) { final String usage = """ - Usage: - \s + Usage: + \s - Where: - sender - An email address that represents the sender.\s - recipient - An email address that represents the recipient.\s - subject - The subject line.\s - """; + Where: + sender - An email address that represents the sender.\s + recipient - An email address that represents the recipient.\s + subject - The subject line.\s + """; if (args.length != 3) { System.out.println(usage); @@ -55,12 +49,12 @@ public static void main(String[] args) { Region region = Region.US_EAST_1; SesClient client = SesClient.builder() - .region(region) - .build(); + .region(region) + .build(); // The HTML body of the email. String bodyHTML = "" + "" + "" + "

    Hello!

    " - + "

    See the list of customers.

    " + "" + ""; + + "

    See the list of customers.

    " + "" + ""; try { send(client, sender, recipient, subject, bodyHTML); @@ -73,38 +67,37 @@ public static void main(String[] args) { } public static void send(SesClient client, - String sender, - String recipient, - String subject, - String bodyHTML - ) throws MessagingException { + String sender, + String recipient, + String subject, + String bodyHTML) throws MessagingException { Destination destination = Destination.builder() - .toAddresses(recipient) - .build(); + .toAddresses(recipient) + .build(); Content content = Content.builder() - .data(bodyHTML) - .build(); + .data(bodyHTML) + .build(); Content sub = Content.builder() - .data(subject) - .build(); + .data(subject) + .build(); Body body = Body.builder() - .html(content) - .build(); + .html(content) + .build(); Message msg = Message.builder() - .subject(sub) - .body(body) - .build(); + .subject(sub) + .body(body) + .build(); SendEmailRequest emailRequest = SendEmailRequest.builder() - .destination(destination) - .message(msg) - .source(sender) - .build(); + .destination(destination) + .message(msg) + .source(sender) + .build(); try { System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java..."); @@ -117,4 +110,3 @@ public static void send(SesClient client, } } // snippet-end:[ses.java2.sendmessage.request.main] - diff --git a/javav2/example_code/ses/src/main/java/com/example/sesv2/ListEmailIdentities.java b/javav2/example_code/ses/src/main/java/com/example/sesv2/ListEmailIdentities.java index 97e5dd55efa..ca9f5c6810c 100644 --- a/javav2/example_code/ses/src/main/java/com/example/sesv2/ListEmailIdentities.java +++ b/javav2/example_code/ses/src/main/java/com/example/sesv2/ListEmailIdentities.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[ListEmailIdentities.java demonstrates how to get a list of email identities that are associated with your Amazon Web Services account.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-keyword:[Amazon Simple Email Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.sesv2; @@ -21,9 +14,9 @@ import java.util.List; // snippet-end:[ses.java2.identities.sesv2.import] - /** - * Before running this AWS SDK for Java (v2) code example, set up your development environment, including your credentials. + * Before running this AWS SDK for Java (v2) code example, set up your + * development environment, including your credentials. * * For more information, see the following documentation topic: * @@ -34,16 +27,16 @@ public class ListEmailIdentities { public static void main(String[] args) { Region region = Region.US_EAST_1; SesV2Client sesv2Client = SesV2Client.builder() - .region(region) - .build(); + .region(region) + .build(); listSESIdentities(sesv2Client); } public static void listSESIdentities(SesV2Client sesV2Client) { ListEmailIdentitiesRequest identitiesRequest = ListEmailIdentitiesRequest.builder() - .pageSize(5) - .build(); + .pageSize(5) + .build(); try { ListEmailIdentitiesResponse response = sesV2Client.listEmailIdentities(identitiesRequest); diff --git a/javav2/example_code/ses/src/main/java/com/example/sesv2/ListTemplates.java b/javav2/example_code/ses/src/main/java/com/example/sesv2/ListTemplates.java index 97ff17e54b6..5b099242a18 100644 --- a/javav2/example_code/ses/src/main/java/com/example/sesv2/ListTemplates.java +++ b/javav2/example_code/ses/src/main/java/com/example/sesv2/ListTemplates.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[SendEmailTemplate.java demonstrates how to send an email message based on a template by using the SesV2Client.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-keyword:[Amazon Simple Email Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.sesv2; @@ -24,8 +17,8 @@ public class ListTemplates { public static void main(String[] args) { Region region = Region.US_EAST_1; SesV2Client sesv2Client = SesV2Client.builder() - .region(region) - .build(); + .region(region) + .build(); listAllTemplates(sesv2Client); } @@ -33,12 +26,12 @@ public static void main(String[] args) { public static void listAllTemplates(SesV2Client sesv2Client) { try { ListEmailTemplatesRequest templatesRequest = ListEmailTemplatesRequest.builder() - .pageSize(1) - .build(); + .pageSize(1) + .build(); ListEmailTemplatesResponse response = sesv2Client.listEmailTemplates(templatesRequest); - response.templatesMetadata().forEach(template -> - System.out.println("Template name: " + template.templateName())); + response.templatesMetadata() + .forEach(template -> System.out.println("Template name: " + template.templateName())); } catch (SesV2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); diff --git a/javav2/example_code/ses/src/main/java/com/example/sesv2/SendEmail.java b/javav2/example_code/ses/src/main/java/com/example/sesv2/SendEmail.java index 8265e4173c6..530a6790711 100644 --- a/javav2/example_code/ses/src/main/java/com/example/sesv2/SendEmail.java +++ b/javav2/example_code/ses/src/main/java/com/example/sesv2/SendEmail.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[SendMessage.java demonstrates how to send an email message by using the SesV2Client.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-keyword:[Amazon Simple Email Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.sesv2; @@ -24,7 +17,8 @@ // snippet-end:[ses.java2.sendmessage.sesv2.import] /** - * Before running this AWS SDK for Java (v2) example, set up your development environment, including your credentials. + * Before running this AWS SDK for Java (v2) example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * @@ -32,86 +26,86 @@ */ public class SendEmail { - public static void main(String[] args) { - final String usage = """ + public static void main(String[] args) { + final String usage = """ + + Usage: + \s + + Where: + sender - An email address that represents the sender.\s + recipient - An email address that represents the recipient.\s + subject - The subject line.\s + """; + + if (args.length != 3) { + System.out.println(usage); + System.exit(1); + } + + String sender = args[0]; + String recipient = args[1]; + String subject = args[2]; - Usage: - \s + Region region = Region.US_EAST_1; + SesV2Client sesv2Client = SesV2Client.builder() + .region(region) + .build(); - Where: - sender - An email address that represents the sender.\s - recipient - An email address that represents the recipient.\s - subject - The subject line.\s - """; + // The HTML body of the email. + String bodyHTML = "" + "" + "" + "

    Hello!

    " + + "

    See the list of customers.

    " + "" + ""; - if (args.length != 3) { - System.out.println(usage); - System.exit(1); + send(sesv2Client, sender, recipient, subject, bodyHTML); } - String sender = args[0]; - String recipient = args[1]; - String subject = args[2]; - - Region region = Region.US_EAST_1; - SesV2Client sesv2Client = SesV2Client.builder() - .region(region) - .build(); - - // The HTML body of the email. - String bodyHTML = "" + "" + "" + "

    Hello!

    " - + "

    See the list of customers.

    " + "" + ""; - - send(sesv2Client, sender, recipient, subject, bodyHTML); - } - - public static void send(SesV2Client client, - String sender, - String recipient, - String subject, - String bodyHTML - ) { - - Destination destination = Destination.builder() - .toAddresses(recipient) - .build(); - - Content content = Content.builder() - .data(bodyHTML) - .build(); - - Content sub = Content.builder() - .data(subject) - .build(); - - Body body = Body.builder() - .html(content) - .build(); - - Message msg = Message.builder() - .subject(sub) - .body(body) - .build(); - - EmailContent emailContent = EmailContent.builder() - .simple(msg) - .build(); - - SendEmailRequest emailRequest = SendEmailRequest.builder() - .destination(destination) - .content(emailContent) - .fromEmailAddress(sender) - .build(); - - try { - System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java..."); - client.sendEmail(emailRequest); - System.out.println("email was sent"); - - } catch (SesV2Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); + public static void send(SesV2Client client, + String sender, + String recipient, + String subject, + String bodyHTML) { + + Destination destination = Destination.builder() + .toAddresses(recipient) + .build(); + + Content content = Content.builder() + .data(bodyHTML) + .build(); + + Content sub = Content.builder() + .data(subject) + .build(); + + Body body = Body.builder() + .html(content) + .build(); + + Message msg = Message.builder() + .subject(sub) + .body(body) + .build(); + + EmailContent emailContent = EmailContent.builder() + .simple(msg) + .build(); + + SendEmailRequest emailRequest = SendEmailRequest.builder() + .destination(destination) + .content(emailContent) + .fromEmailAddress(sender) + .build(); + + try { + System.out.println("Attempting to send an email through Amazon SES " + + "using the AWS SDK for Java..."); + client.sendEmail(emailRequest); + System.out.println("email was sent"); + + } catch (SesV2Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } } - } } - // snippet-end:[ses.java2.sendmessage.sesv2.main] +// snippet-end:[ses.java2.sendmessage.sesv2.main] diff --git a/javav2/example_code/ses/src/main/java/com/example/sesv2/SendEmailTemplate.java b/javav2/example_code/ses/src/main/java/com/example/sesv2/SendEmailTemplate.java index 667c2e45f8a..469d47ed944 100644 --- a/javav2/example_code/ses/src/main/java/com/example/sesv2/SendEmailTemplate.java +++ b/javav2/example_code/ses/src/main/java/com/example/sesv2/SendEmailTemplate.java @@ -1,12 +1,5 @@ -// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] -// snippet-sourcedescription:[SendEmailTemplate.java demonstrates how to send an email message based on a template by using the SesV2Client.] -// snippet-keyword:[AWS SDK for Java v2] -// snippet-keyword:[Amazon Simple Email Service] - -/* - Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.example.sesv2; @@ -22,13 +15,15 @@ // snippet-end:[ses.java2.sendmessage.template.sesv2.import] /** - * Before running this AWS SDK for Java (v2) example, set up your development environment, including your credentials. + * Before running this AWS SDK for Java (v2) example, set up your development + * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * - * Also, make sure that you create a template. See the following documentation topic: + * Also, make sure that you create a template. See the following documentation + * topic: * * https://docs.aws.amazon.com/ses/latest/dg/send-personalized-email-api.html */ @@ -37,14 +32,14 @@ public class SendEmailTemplate { public static void main(String[] args) { final String usage = """ - Usage: -